{ "cells": [ { "cell_type": "code", "execution_count": 16, "id": "7daa1bf0", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Collecting langchain_huggingface\n", " Downloading langchain_huggingface-1.2.1-py3-none-any.whl.metadata (3.3 kB)\n", "Requirement already satisfied: huggingface-hub<2.0.0,>=0.33.4 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from langchain_huggingface) (1.6.0)\n", "Requirement already satisfied: langchain-core<2.0.0,>=1.2.11 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from langchain_huggingface) (1.2.18)\n", "Requirement already satisfied: tokenizers<1.0.0,>=0.19.1 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from langchain_huggingface) (0.22.2)\n", "Requirement already satisfied: filelock>=3.10.0 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from huggingface-hub<2.0.0,>=0.33.4->langchain_huggingface) (3.25.2)\n", "Requirement already satisfied: fsspec>=2023.5.0 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from huggingface-hub<2.0.0,>=0.33.4->langchain_huggingface) (2026.2.0)\n", "Requirement already satisfied: hf-xet<2.0.0,>=1.3.2 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from huggingface-hub<2.0.0,>=0.33.4->langchain_huggingface) (1.4.0)\n", "Requirement already satisfied: httpx<1,>=0.23.0 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from huggingface-hub<2.0.0,>=0.33.4->langchain_huggingface) (0.28.1)\n", "Requirement already satisfied: packaging>=20.9 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from huggingface-hub<2.0.0,>=0.33.4->langchain_huggingface) (26.0)\n", "Requirement already satisfied: pyyaml>=5.1 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from huggingface-hub<2.0.0,>=0.33.4->langchain_huggingface) (6.0.3)\n", "Requirement already satisfied: tqdm>=4.42.1 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from huggingface-hub<2.0.0,>=0.33.4->langchain_huggingface) (4.67.3)\n", "Requirement already satisfied: typer in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from huggingface-hub<2.0.0,>=0.33.4->langchain_huggingface) (0.24.1)\n", "Requirement already satisfied: typing-extensions>=4.1.0 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from huggingface-hub<2.0.0,>=0.33.4->langchain_huggingface) (4.15.0)\n", "Requirement already satisfied: anyio in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from httpx<1,>=0.23.0->huggingface-hub<2.0.0,>=0.33.4->langchain_huggingface) (4.12.1)\n", "Requirement already satisfied: certifi in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from httpx<1,>=0.23.0->huggingface-hub<2.0.0,>=0.33.4->langchain_huggingface) (2026.2.25)\n", "Requirement already satisfied: httpcore==1.* in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from httpx<1,>=0.23.0->huggingface-hub<2.0.0,>=0.33.4->langchain_huggingface) (1.0.9)\n", "Requirement already satisfied: idna in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from httpx<1,>=0.23.0->huggingface-hub<2.0.0,>=0.33.4->langchain_huggingface) (3.11)\n", "Requirement already satisfied: h11>=0.16 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from httpcore==1.*->httpx<1,>=0.23.0->huggingface-hub<2.0.0,>=0.33.4->langchain_huggingface) (0.16.0)\n", "Requirement already satisfied: jsonpatch<2.0.0,>=1.33.0 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from langchain-core<2.0.0,>=1.2.11->langchain_huggingface) (1.33)\n", "Requirement already satisfied: langsmith<1.0.0,>=0.3.45 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from langchain-core<2.0.0,>=1.2.11->langchain_huggingface) (0.7.17)\n", "Requirement already satisfied: pydantic<3.0.0,>=2.7.4 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from langchain-core<2.0.0,>=1.2.11->langchain_huggingface) (2.12.5)\n", "Requirement already satisfied: tenacity!=8.4.0,<10.0.0,>=8.1.0 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from langchain-core<2.0.0,>=1.2.11->langchain_huggingface) (9.1.4)\n", "Requirement already satisfied: uuid-utils<1.0,>=0.12.0 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from langchain-core<2.0.0,>=1.2.11->langchain_huggingface) (0.14.1)\n", "Requirement already satisfied: jsonpointer>=1.9 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from jsonpatch<2.0.0,>=1.33.0->langchain-core<2.0.0,>=1.2.11->langchain_huggingface) (3.0.0)\n", "Requirement already satisfied: orjson>=3.9.14 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from langsmith<1.0.0,>=0.3.45->langchain-core<2.0.0,>=1.2.11->langchain_huggingface) (3.11.7)\n", "Requirement already satisfied: requests-toolbelt>=1.0.0 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from langsmith<1.0.0,>=0.3.45->langchain-core<2.0.0,>=1.2.11->langchain_huggingface) (1.0.0)\n", "Requirement already satisfied: requests>=2.0.0 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from langsmith<1.0.0,>=0.3.45->langchain-core<2.0.0,>=1.2.11->langchain_huggingface) (2.32.5)\n", "Requirement already satisfied: xxhash>=3.0.0 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from langsmith<1.0.0,>=0.3.45->langchain-core<2.0.0,>=1.2.11->langchain_huggingface) (3.6.0)\n", "Requirement already satisfied: zstandard>=0.23.0 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from langsmith<1.0.0,>=0.3.45->langchain-core<2.0.0,>=1.2.11->langchain_huggingface) (0.25.0)\n", "Requirement already satisfied: annotated-types>=0.6.0 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from pydantic<3.0.0,>=2.7.4->langchain-core<2.0.0,>=1.2.11->langchain_huggingface) (0.7.0)\n", "Requirement already satisfied: pydantic-core==2.41.5 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from pydantic<3.0.0,>=2.7.4->langchain-core<2.0.0,>=1.2.11->langchain_huggingface) (2.41.5)\n", "Requirement already satisfied: typing-inspection>=0.4.2 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from pydantic<3.0.0,>=2.7.4->langchain-core<2.0.0,>=1.2.11->langchain_huggingface) (0.4.2)\n", "Requirement already satisfied: charset_normalizer<4,>=2 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from requests>=2.0.0->langsmith<1.0.0,>=0.3.45->langchain-core<2.0.0,>=1.2.11->langchain_huggingface) (3.4.5)\n", "Requirement already satisfied: urllib3<3,>=1.21.1 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from requests>=2.0.0->langsmith<1.0.0,>=0.3.45->langchain-core<2.0.0,>=1.2.11->langchain_huggingface) (2.6.3)\n", "Requirement already satisfied: colorama in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from tqdm>=4.42.1->huggingface-hub<2.0.0,>=0.33.4->langchain_huggingface) (0.4.6)\n", "Requirement already satisfied: click>=8.2.1 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from typer->huggingface-hub<2.0.0,>=0.33.4->langchain_huggingface) (8.3.1)\n", "Requirement already satisfied: shellingham>=1.3.0 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from typer->huggingface-hub<2.0.0,>=0.33.4->langchain_huggingface) (1.5.4)\n", "Requirement already satisfied: rich>=12.3.0 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from typer->huggingface-hub<2.0.0,>=0.33.4->langchain_huggingface) (14.3.3)\n", "Requirement already satisfied: annotated-doc>=0.0.2 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from typer->huggingface-hub<2.0.0,>=0.33.4->langchain_huggingface) (0.0.4)\n", "Requirement already satisfied: markdown-it-py>=2.2.0 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from rich>=12.3.0->typer->huggingface-hub<2.0.0,>=0.33.4->langchain_huggingface) (4.0.0)\n", "Requirement already satisfied: pygments<3.0.0,>=2.13.0 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from rich>=12.3.0->typer->huggingface-hub<2.0.0,>=0.33.4->langchain_huggingface) (2.19.2)\n", "Requirement already satisfied: mdurl~=0.1 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from markdown-it-py>=2.2.0->rich>=12.3.0->typer->huggingface-hub<2.0.0,>=0.33.4->langchain_huggingface) (0.1.2)\n", "Downloading langchain_huggingface-1.2.1-py3-none-any.whl (30 kB)\n", "Installing collected packages: langchain_huggingface\n", "Successfully installed langchain_huggingface-1.2.1\n", "Note: you may need to restart the kernel to use updated packages.\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "\n", "[notice] A new release of pip is available: 25.1.1 -> 26.0.1\n", "[notice] To update, run: python.exe -m pip install --upgrade pip\n" ] } ], "source": [ "%pip install langchain_huggingface" ] }, { "cell_type": "code", "execution_count": 11, "id": "a41538f6", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Collecting unstructured\n", " Downloading unstructured-0.21.5-py3-none-any.whl.metadata (28 kB)\n", "Requirement already satisfied: beautifulsoup4<5.0.0,>=4.14.3 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from unstructured) (4.14.3)\n", "Requirement already satisfied: charset-normalizer<4.0.0,>=3.4.4 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from unstructured) (3.4.5)\n", "Collecting emoji<3.0.0,>=2.15.0 (from unstructured)\n", " Downloading emoji-2.15.0-py3-none-any.whl.metadata (5.7 kB)\n", "Requirement already satisfied: filelock<4.0.0,>=3.12.0 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from unstructured) (3.25.2)\n", "Collecting filetype<2.0.0,>=1.2.0 (from unstructured)\n", " Using cached filetype-1.2.0-py2.py3-none-any.whl.metadata (6.5 kB)\n", "Collecting html5lib<2.0.0,>=1.1 (from unstructured)\n", " Downloading html5lib-1.1-py2.py3-none-any.whl.metadata (16 kB)\n", "Collecting installer<1.0.0,>=0.7.0 (from unstructured)\n", " Downloading installer-0.7.0-py3-none-any.whl.metadata (936 bytes)\n", "Collecting langdetect<2.0.0,>=1.0.9 (from unstructured)\n", " Downloading langdetect-1.0.9.tar.gz (981 kB)\n", " ---------------------------------------- 0.0/981.5 kB ? eta -:--:--\n", " ---------------------------------------- 0.0/981.5 kB ? eta -:--:--\n", " ---------------------------------------- 0.0/981.5 kB ? eta -:--:--\n", " ---------- ----------------------------- 262.1/981.5 kB ? eta -:--:--\n", " ------------------------------ ------- 786.4/981.5 kB 1.8 MB/s eta 0:00:01\n", " -------------------------------------- 981.5/981.5 kB 1.9 MB/s eta 0:00:00\n", " Installing build dependencies: started\n", " Installing build dependencies: finished with status 'done'\n", " Getting requirements to build wheel: started\n", " Getting requirements to build wheel: finished with status 'done'\n", " Preparing metadata (pyproject.toml): started\n", " Preparing metadata (pyproject.toml): finished with status 'done'\n", "Collecting lxml<7.0.0,>=5.0.0 (from unstructured)\n", " Downloading lxml-6.0.2-cp313-cp313-win_amd64.whl.metadata (3.7 kB)\n", "Collecting numba<1.0.0,>=0.60.0 (from unstructured)\n", " Downloading numba-0.64.0-cp313-cp313-win_amd64.whl.metadata (3.0 kB)\n", "Requirement already satisfied: numpy<3.0.0,>=1.26.0 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from unstructured) (2.4.3)\n", "Requirement already satisfied: psutil<8.0.0,>=7.2.2 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from unstructured) (7.2.2)\n", "Collecting python-iso639<2027.0.0,>=2026.1.31 (from unstructured)\n", " Downloading python_iso639-2026.1.31-py3-none-any.whl.metadata (14 kB)\n", "Collecting python-magic<1.0.0,>=0.4.27 (from unstructured)\n", " Downloading python_magic-0.4.27-py2.py3-none-any.whl.metadata (5.8 kB)\n", "Collecting python-oxmsg<1.0.0,>=0.0.2 (from unstructured)\n", " Downloading python_oxmsg-0.0.2-py3-none-any.whl.metadata (5.0 kB)\n", "Collecting rapidfuzz<4.0.0,>=3.14.3 (from unstructured)\n", " Downloading rapidfuzz-3.14.3-cp313-cp313-win_amd64.whl.metadata (12 kB)\n", "Requirement already satisfied: regex<2027.0.0,>=2024.0.0 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from unstructured) (2026.2.28)\n", "Requirement already satisfied: requests<3.0.0,>=2.32.5 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from unstructured) (2.32.5)\n", "Collecting spacy<4.0.0,>=3.7.0 (from unstructured)\n", " Downloading spacy-3.8.11-cp313-cp313-win_amd64.whl.metadata (28 kB)\n", "Requirement already satisfied: tqdm<5.0.0,>=4.67.3 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from unstructured) (4.67.3)\n", "Requirement already satisfied: typing-extensions<5.0.0,>=4.15.0 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from unstructured) (4.15.0)\n", "Collecting unstructured-client<1.0.0,>=0.25.9 (from unstructured)\n", " Downloading unstructured_client-0.42.10-py3-none-any.whl.metadata (23 kB)\n", "Collecting wrapt<2.0.0,>=1.0.0 (from unstructured)\n", " Downloading wrapt-1.17.3-cp313-cp313-win_amd64.whl.metadata (6.5 kB)\n", "Requirement already satisfied: soupsieve>=1.6.1 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from beautifulsoup4<5.0.0,>=4.14.3->unstructured) (2.8.3)\n", "Requirement already satisfied: six>=1.9 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from html5lib<2.0.0,>=1.1->unstructured) (1.17.0)\n", "Collecting webencodings (from html5lib<2.0.0,>=1.1->unstructured)\n", " Using cached webencodings-0.5.1-py2.py3-none-any.whl.metadata (2.1 kB)\n", "Collecting llvmlite<0.47,>=0.46.0dev0 (from numba<1.0.0,>=0.60.0->unstructured)\n", " Downloading llvmlite-0.46.0-cp313-cp313-win_amd64.whl.metadata (5.1 kB)\n", "Requirement already satisfied: click in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from python-oxmsg<1.0.0,>=0.0.2->unstructured) (8.3.1)\n", "Collecting olefile (from python-oxmsg<1.0.0,>=0.0.2->unstructured)\n", " Downloading olefile-0.47-py2.py3-none-any.whl.metadata (9.7 kB)\n", "Requirement already satisfied: idna<4,>=2.5 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from requests<3.0.0,>=2.32.5->unstructured) (3.11)\n", "Requirement already satisfied: urllib3<3,>=1.21.1 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from requests<3.0.0,>=2.32.5->unstructured) (2.6.3)\n", "Requirement already satisfied: certifi>=2017.4.17 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from requests<3.0.0,>=2.32.5->unstructured) (2026.2.25)\n", "Collecting spacy-legacy<3.1.0,>=3.0.11 (from spacy<4.0.0,>=3.7.0->unstructured)\n", " Downloading spacy_legacy-3.0.12-py2.py3-none-any.whl.metadata (2.8 kB)\n", "Collecting spacy-loggers<2.0.0,>=1.0.0 (from spacy<4.0.0,>=3.7.0->unstructured)\n", " Downloading spacy_loggers-1.0.5-py3-none-any.whl.metadata (23 kB)\n", "Collecting murmurhash<1.1.0,>=0.28.0 (from spacy<4.0.0,>=3.7.0->unstructured)\n", " Downloading murmurhash-1.0.15-cp313-cp313-win_amd64.whl.metadata (2.3 kB)\n", "Collecting cymem<2.1.0,>=2.0.2 (from spacy<4.0.0,>=3.7.0->unstructured)\n", " Downloading cymem-2.0.13-cp313-cp313-win_amd64.whl.metadata (9.9 kB)\n", "Collecting preshed<3.1.0,>=3.0.2 (from spacy<4.0.0,>=3.7.0->unstructured)\n", " Downloading preshed-3.0.12-cp313-cp313-win_amd64.whl.metadata (2.6 kB)\n", "Collecting thinc<8.4.0,>=8.3.4 (from spacy<4.0.0,>=3.7.0->unstructured)\n", " Downloading thinc-8.3.10-cp313-cp313-win_amd64.whl.metadata (15 kB)\n", "Collecting wasabi<1.2.0,>=0.9.1 (from spacy<4.0.0,>=3.7.0->unstructured)\n", " Downloading wasabi-1.1.3-py3-none-any.whl.metadata (28 kB)\n", "Collecting srsly<3.0.0,>=2.4.3 (from spacy<4.0.0,>=3.7.0->unstructured)\n", " Downloading srsly-2.5.2-cp313-cp313-win_amd64.whl.metadata (20 kB)\n", "Collecting catalogue<2.1.0,>=2.0.6 (from spacy<4.0.0,>=3.7.0->unstructured)\n", " Downloading catalogue-2.0.10-py3-none-any.whl.metadata (14 kB)\n", "Collecting weasel<0.5.0,>=0.4.2 (from spacy<4.0.0,>=3.7.0->unstructured)\n", " Downloading weasel-0.4.3-py3-none-any.whl.metadata (4.6 kB)\n", "Collecting typer-slim<1.0.0,>=0.3.0 (from spacy<4.0.0,>=3.7.0->unstructured)\n", " Downloading typer_slim-0.24.0-py3-none-any.whl.metadata (4.2 kB)\n", "Requirement already satisfied: pydantic!=1.8,!=1.8.1,<3.0.0,>=1.7.4 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from spacy<4.0.0,>=3.7.0->unstructured) (2.12.5)\n", "Requirement already satisfied: jinja2 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from spacy<4.0.0,>=3.7.0->unstructured) (3.1.6)\n", "Requirement already satisfied: setuptools in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from spacy<4.0.0,>=3.7.0->unstructured) (82.0.1)\n", "Requirement already satisfied: packaging>=20.0 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from spacy<4.0.0,>=3.7.0->unstructured) (26.0)\n", "Requirement already satisfied: annotated-types>=0.6.0 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from pydantic!=1.8,!=1.8.1,<3.0.0,>=1.7.4->spacy<4.0.0,>=3.7.0->unstructured) (0.7.0)\n", "Requirement already satisfied: pydantic-core==2.41.5 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from pydantic!=1.8,!=1.8.1,<3.0.0,>=1.7.4->spacy<4.0.0,>=3.7.0->unstructured) (2.41.5)\n", "Requirement already satisfied: typing-inspection>=0.4.2 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from pydantic!=1.8,!=1.8.1,<3.0.0,>=1.7.4->spacy<4.0.0,>=3.7.0->unstructured) (0.4.2)\n", "Collecting blis<1.4.0,>=1.3.0 (from thinc<8.4.0,>=8.3.4->spacy<4.0.0,>=3.7.0->unstructured)\n", " Downloading blis-1.3.3-cp313-cp313-win_amd64.whl.metadata (7.7 kB)\n", "Collecting confection<1.0.0,>=0.0.1 (from thinc<8.4.0,>=8.3.4->spacy<4.0.0,>=3.7.0->unstructured)\n", " Downloading confection-0.1.5-py3-none-any.whl.metadata (19 kB)\n", "Requirement already satisfied: colorama in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from tqdm<5.0.0,>=4.67.3->unstructured) (0.4.6)\n", "Requirement already satisfied: typer>=0.24.0 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from typer-slim<1.0.0,>=0.3.0->spacy<4.0.0,>=3.7.0->unstructured) (0.24.1)\n", "Collecting aiofiles>=24.1.0 (from unstructured-client<1.0.0,>=0.25.9->unstructured)\n", " Downloading aiofiles-25.1.0-py3-none-any.whl.metadata (6.3 kB)\n", "Collecting cryptography>=3.1 (from unstructured-client<1.0.0,>=0.25.9->unstructured)\n", " Downloading cryptography-46.0.5-cp311-abi3-win_amd64.whl.metadata (5.7 kB)\n", "Requirement already satisfied: httpcore>=1.0.9 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from unstructured-client<1.0.0,>=0.25.9->unstructured) (1.0.9)\n", "Requirement already satisfied: httpx>=0.27.0 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from unstructured-client<1.0.0,>=0.25.9->unstructured) (0.28.1)\n", "Collecting pypdf>=6.2.0 (from unstructured-client<1.0.0,>=0.25.9->unstructured)\n", " Downloading pypdf-6.8.0-py3-none-any.whl.metadata (7.1 kB)\n", "Collecting pypdfium2>=5.0.0 (from unstructured-client<1.0.0,>=0.25.9->unstructured)\n", " Downloading pypdfium2-5.6.0-py3-none-win_amd64.whl.metadata (68 kB)\n", "Requirement already satisfied: requests-toolbelt>=1.0.0 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from unstructured-client<1.0.0,>=0.25.9->unstructured) (1.0.0)\n", "Collecting cloudpathlib<1.0.0,>=0.7.0 (from weasel<0.5.0,>=0.4.2->spacy<4.0.0,>=3.7.0->unstructured)\n", " Downloading cloudpathlib-0.23.0-py3-none-any.whl.metadata (16 kB)\n", "Collecting smart-open<8.0.0,>=5.2.1 (from weasel<0.5.0,>=0.4.2->spacy<4.0.0,>=3.7.0->unstructured)\n", " Downloading smart_open-7.5.1-py3-none-any.whl.metadata (24 kB)\n", "Collecting cffi>=2.0.0 (from cryptography>=3.1->unstructured-client<1.0.0,>=0.25.9->unstructured)\n", " Downloading cffi-2.0.0-cp313-cp313-win_amd64.whl.metadata (2.6 kB)\n", "Collecting pycparser (from cffi>=2.0.0->cryptography>=3.1->unstructured-client<1.0.0,>=0.25.9->unstructured)\n", " Downloading pycparser-3.0-py3-none-any.whl.metadata (8.2 kB)\n", "Requirement already satisfied: h11>=0.16 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from httpcore>=1.0.9->unstructured-client<1.0.0,>=0.25.9->unstructured) (0.16.0)\n", "Requirement already satisfied: anyio in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from httpx>=0.27.0->unstructured-client<1.0.0,>=0.25.9->unstructured) (4.12.1)\n", "Requirement already satisfied: shellingham>=1.3.0 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from typer>=0.24.0->typer-slim<1.0.0,>=0.3.0->spacy<4.0.0,>=3.7.0->unstructured) (1.5.4)\n", "Requirement already satisfied: rich>=12.3.0 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from typer>=0.24.0->typer-slim<1.0.0,>=0.3.0->spacy<4.0.0,>=3.7.0->unstructured) (14.3.3)\n", "Requirement already satisfied: annotated-doc>=0.0.2 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from typer>=0.24.0->typer-slim<1.0.0,>=0.3.0->spacy<4.0.0,>=3.7.0->unstructured) (0.0.4)\n", "Requirement already satisfied: markdown-it-py>=2.2.0 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from rich>=12.3.0->typer>=0.24.0->typer-slim<1.0.0,>=0.3.0->spacy<4.0.0,>=3.7.0->unstructured) (4.0.0)\n", "Requirement already satisfied: pygments<3.0.0,>=2.13.0 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from rich>=12.3.0->typer>=0.24.0->typer-slim<1.0.0,>=0.3.0->spacy<4.0.0,>=3.7.0->unstructured) (2.19.2)\n", "Requirement already satisfied: mdurl~=0.1 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from markdown-it-py>=2.2.0->rich>=12.3.0->typer>=0.24.0->typer-slim<1.0.0,>=0.3.0->spacy<4.0.0,>=3.7.0->unstructured) (0.1.2)\n", "Requirement already satisfied: MarkupSafe>=2.0 in c:\\parth files\\programming projects\\ollama-test\\venv\\lib\\site-packages (from jinja2->spacy<4.0.0,>=3.7.0->unstructured) (3.0.3)\n", "Downloading unstructured-0.21.5-py3-none-any.whl (1.6 MB)\n", " ---------------------------------------- 0.0/1.6 MB ? eta -:--:--\n", " ---------------------------------------- 0.0/1.6 MB ? eta -:--:--\n", " ------ --------------------------------- 0.3/1.6 MB ? eta -:--:--\n", " -------------------------- ------------- 1.0/1.6 MB 2.7 MB/s eta 0:00:01\n", " ---------------------------------------- 1.6/1.6 MB 3.2 MB/s eta 0:00:00\n", "Downloading emoji-2.15.0-py3-none-any.whl (608 kB)\n", " ---------------------------------------- 0.0/608.4 kB ? eta -:--:--\n", " ---------------------------------------- 608.4/608.4 kB 6.1 MB/s eta 0:00:00\n", "Using cached filetype-1.2.0-py2.py3-none-any.whl (19 kB)\n", "Downloading html5lib-1.1-py2.py3-none-any.whl (112 kB)\n", "Downloading installer-0.7.0-py3-none-any.whl (453 kB)\n", "Downloading lxml-6.0.2-cp313-cp313-win_amd64.whl (4.0 MB)\n", " ---------------------------------------- 0.0/4.0 MB ? eta -:--:--\n", " ------------------ --------------------- 1.8/4.0 MB 9.5 MB/s eta 0:00:01\n", " --------------------------------------- 3.9/4.0 MB 9.9 MB/s eta 0:00:01\n", " ---------------------------------------- 4.0/4.0 MB 9.6 MB/s eta 0:00:00\n", "Downloading numba-0.64.0-cp313-cp313-win_amd64.whl (2.8 MB)\n", " ---------------------------------------- 0.0/2.8 MB ? eta -:--:--\n", " -------------------------------------- - 2.6/2.8 MB 12.5 MB/s eta 0:00:01\n", " ---------------------------------------- 2.8/2.8 MB 11.9 MB/s eta 0:00:00\n", "Downloading llvmlite-0.46.0-cp313-cp313-win_amd64.whl (38.1 MB)\n", " ---------------------------------------- 0.0/38.1 MB ? eta -:--:--\n", " --- ------------------------------------ 3.1/38.1 MB 15.1 MB/s eta 0:00:03\n", " ------ --------------------------------- 6.6/38.1 MB 16.0 MB/s eta 0:00:02\n", " ----------- ---------------------------- 10.7/38.1 MB 17.6 MB/s eta 0:00:02\n", " ---------------- ----------------------- 15.5/38.1 MB 19.1 MB/s eta 0:00:02\n", " ---------------------- ----------------- 21.2/38.1 MB 20.7 MB/s eta 0:00:01\n", " ---------------------------- ----------- 27.0/38.1 MB 22.0 MB/s eta 0:00:01\n", " --------------------------------- ------ 32.2/38.1 MB 22.4 MB/s eta 0:00:01\n", " --------------------------------------- 37.2/38.1 MB 23.1 MB/s eta 0:00:01\n", " ---------------------------------------- 38.1/38.1 MB 21.9 MB/s eta 0:00:00\n", "Downloading python_iso639-2026.1.31-py3-none-any.whl (167 kB)\n", "Downloading python_magic-0.4.27-py2.py3-none-any.whl (13 kB)\n", "Downloading python_oxmsg-0.0.2-py3-none-any.whl (31 kB)\n", "Downloading rapidfuzz-3.14.3-cp313-cp313-win_amd64.whl (1.5 MB)\n", " ---------------------------------------- 0.0/1.5 MB ? eta -:--:--\n", " ---------------------------------------- 1.5/1.5 MB 25.6 MB/s eta 0:00:00\n", "Downloading spacy-3.8.11-cp313-cp313-win_amd64.whl (14.2 MB)\n", " ---------------------------------------- 0.0/14.2 MB ? eta -:--:--\n", " ----------------- ---------------------- 6.3/14.2 MB 30.1 MB/s eta 0:00:01\n", " ------------------------------------ --- 12.8/14.2 MB 31.2 MB/s eta 0:00:01\n", " ---------------------------------------- 14.2/14.2 MB 28.5 MB/s eta 0:00:00\n", "Downloading catalogue-2.0.10-py3-none-any.whl (17 kB)\n", "Downloading cymem-2.0.13-cp313-cp313-win_amd64.whl (40 kB)\n", "Downloading murmurhash-1.0.15-cp313-cp313-win_amd64.whl (25 kB)\n", "Downloading preshed-3.0.12-cp313-cp313-win_amd64.whl (117 kB)\n", "Downloading spacy_legacy-3.0.12-py2.py3-none-any.whl (29 kB)\n", "Downloading spacy_loggers-1.0.5-py3-none-any.whl (22 kB)\n", "Downloading srsly-2.5.2-cp313-cp313-win_amd64.whl (653 kB)\n", " ---------------------------------------- 0.0/653.1 kB ? eta -:--:--\n", " ---------------------------------------- 0.0/653.1 kB ? eta -:--:--\n", " -------------------------------- ------- 524.3/653.1 kB 1.9 MB/s eta 0:00:01\n", " ---------------------------------------- 653.1/653.1 kB 2.1 MB/s eta 0:00:00\n", "Downloading thinc-8.3.10-cp313-cp313-win_amd64.whl (1.7 MB)\n", " ---------------------------------------- 0.0/1.7 MB ? eta -:--:--\n", " ------------ --------------------------- 0.5/1.7 MB 3.2 MB/s eta 0:00:01\n", " ------------------------ --------------- 1.0/1.7 MB 3.3 MB/s eta 0:00:01\n", " ---------------------------------------- 1.7/1.7 MB 3.4 MB/s eta 0:00:00\n", "Downloading blis-1.3.3-cp313-cp313-win_amd64.whl (6.2 MB)\n", " ---------------------------------------- 0.0/6.2 MB ? eta -:--:--\n", " ------ --------------------------------- 1.0/6.2 MB 5.8 MB/s eta 0:00:01\n", " --------------- ------------------------ 2.4/6.2 MB 6.0 MB/s eta 0:00:01\n", " ---------------------------- ----------- 4.5/6.2 MB 7.5 MB/s eta 0:00:01\n", " ---------------------------------------- 6.2/6.2 MB 8.2 MB/s eta 0:00:00\n", "Downloading confection-0.1.5-py3-none-any.whl (35 kB)\n", "Downloading typer_slim-0.24.0-py3-none-any.whl (3.4 kB)\n", "Downloading unstructured_client-0.42.10-py3-none-any.whl (220 kB)\n", "Downloading wasabi-1.1.3-py3-none-any.whl (27 kB)\n", "Downloading weasel-0.4.3-py3-none-any.whl (50 kB)\n", "Downloading cloudpathlib-0.23.0-py3-none-any.whl (62 kB)\n", "Downloading smart_open-7.5.1-py3-none-any.whl (64 kB)\n", "Downloading wrapt-1.17.3-cp313-cp313-win_amd64.whl (38 kB)\n", "Downloading aiofiles-25.1.0-py3-none-any.whl (14 kB)\n", "Downloading cryptography-46.0.5-cp311-abi3-win_amd64.whl (3.5 MB)\n", " ---------------------------------------- 0.0/3.5 MB ? eta -:--:--\n", " --------------- ------------------------ 1.3/3.5 MB 7.3 MB/s eta 0:00:01\n", " ------------------------------------ --- 3.1/3.5 MB 8.0 MB/s eta 0:00:01\n", " ---------------------------------------- 3.5/3.5 MB 7.8 MB/s eta 0:00:00\n", "Downloading cffi-2.0.0-cp313-cp313-win_amd64.whl (183 kB)\n", "Downloading pypdf-6.8.0-py3-none-any.whl (332 kB)\n", "Downloading pypdfium2-5.6.0-py3-none-win_amd64.whl (3.7 MB)\n", " ---------------------------------------- 0.0/3.7 MB ? eta -:--:--\n", " ------------------------- -------------- 2.4/3.7 MB 11.9 MB/s eta 0:00:01\n", " ---------------------------------------- 3.7/3.7 MB 11.5 MB/s eta 0:00:00\n", "Downloading olefile-0.47-py2.py3-none-any.whl (114 kB)\n", "Downloading pycparser-3.0-py3-none-any.whl (48 kB)\n", "Using cached webencodings-0.5.1-py2.py3-none-any.whl (11 kB)\n", "Building wheels for collected packages: langdetect\n", " Building wheel for langdetect (pyproject.toml): started\n", " Building wheel for langdetect (pyproject.toml): finished with status 'done'\n", " Created wheel for langdetect: filename=langdetect-1.0.9-py3-none-any.whl size=993364 sha256=d980e441972bdd1f79c63c5a49f3ce3c7ceb6f876b4ccbeb3a550e7d788e03c8\n", " Stored in directory: c:\\users\\sndes\\appdata\\local\\pip\\cache\\wheels\\eb\\87\\25\\2dddf1c94e1786054e25022ec5530bfed52bad86d882999c48\n", "Successfully built langdetect\n", "Installing collected packages: webencodings, filetype, wrapt, wasabi, spacy-loggers, spacy-legacy, rapidfuzz, python-magic, python-iso639, pypdfium2, pypdf, pycparser, olefile, murmurhash, lxml, llvmlite, langdetect, installer, html5lib, emoji, cymem, cloudpathlib, catalogue, blis, aiofiles, srsly, smart-open, python-oxmsg, preshed, numba, cffi, cryptography, confection, unstructured-client, typer-slim, thinc, weasel, spacy, unstructured\n", "\n", " - -------------------------------------- 1/39 [filetype]\n", " - -------------------------------------- 1/39 [filetype]\n", " - -------------------------------------- 1/39 [filetype]\n", " -- ------------------------------------- 2/39 [wrapt]\n", " -- ------------------------------------- 2/39 [wrapt]\n", " --- ------------------------------------ 3/39 [wasabi]\n", " --- ------------------------------------ 3/39 [wasabi]\n", " ---- ----------------------------------- 4/39 [spacy-loggers]\n", " ---- ----------------------------------- 4/39 [spacy-loggers]\n", " ----- ---------------------------------- 5/39 [spacy-legacy]\n", " ----- ---------------------------------- 5/39 [spacy-legacy]\n", " ------ --------------------------------- 6/39 [rapidfuzz]\n", " ------ --------------------------------- 6/39 [rapidfuzz]\n", " ------ --------------------------------- 6/39 [rapidfuzz]\n", " ------ --------------------------------- 6/39 [rapidfuzz]\n", " ------ --------------------------------- 6/39 [rapidfuzz]\n", " ------- -------------------------------- 7/39 [python-magic]\n", " -------- ------------------------------- 8/39 [python-iso639]\n", " --------- ------------------------------ 9/39 [pypdfium2]\n", " --------- ------------------------------ 9/39 [pypdfium2]\n", " --------- ------------------------------ 9/39 [pypdfium2]\n", " --------- ------------------------------ 9/39 [pypdfium2]\n", " --------- ------------------------------ 9/39 [pypdfium2]\n", " --------- ------------------------------ 9/39 [pypdfium2]\n", " ---------- ----------------------------- 10/39 [pypdf]\n", " ---------- ----------------------------- 10/39 [pypdf]\n", " ---------- ----------------------------- 10/39 [pypdf]\n", " ---------- ----------------------------- 10/39 [pypdf]\n", " ---------- ----------------------------- 10/39 [pypdf]\n", " ---------- ----------------------------- 10/39 [pypdf]\n", " ---------- ----------------------------- 10/39 [pypdf]\n", " ---------- ----------------------------- 10/39 [pypdf]\n", " ---------- ----------------------------- 10/39 [pypdf]\n", " ----------- ---------------------------- 11/39 [pycparser]\n", " ----------- ---------------------------- 11/39 [pycparser]\n", " ------------ --------------------------- 12/39 [olefile]\n", " -------------- ------------------------- 14/39 [lxml]\n", " -------------- ------------------------- 14/39 [lxml]\n", " -------------- ------------------------- 14/39 [lxml]\n", " -------------- ------------------------- 14/39 [lxml]\n", " -------------- ------------------------- 14/39 [lxml]\n", " --------------- ------------------------ 15/39 [llvmlite]\n", " --------------- ------------------------ 15/39 [llvmlite]\n", " --------------- ------------------------ 15/39 [llvmlite]\n", " --------------- ------------------------ 15/39 [llvmlite]\n", " --------------- ------------------------ 15/39 [llvmlite]\n", " --------------- ------------------------ 15/39 [llvmlite]\n", " --------------- ------------------------ 15/39 [llvmlite]\n", " --------------- ------------------------ 15/39 [llvmlite]\n", " --------------- ------------------------ 15/39 [llvmlite]\n", " --------------- ------------------------ 15/39 [llvmlite]\n", " ---------------- ----------------------- 16/39 [langdetect]\n", " ----------------- ---------------------- 17/39 [installer]\n", " ----------------- ---------------------- 17/39 [installer]\n", " ------------------ --------------------- 18/39 [html5lib]\n", " ------------------ --------------------- 18/39 [html5lib]\n", " ------------------ --------------------- 18/39 [html5lib]\n", " ------------------ --------------------- 18/39 [html5lib]\n", " ------------------ --------------------- 18/39 [html5lib]\n", " ------------------- -------------------- 19/39 [emoji]\n", " -------------------- ------------------- 20/39 [cymem]\n", " --------------------- ------------------ 21/39 [cloudpathlib]\n", " --------------------- ------------------ 21/39 [cloudpathlib]\n", " --------------------- ------------------ 21/39 [cloudpathlib]\n", " --------------------- ------------------ 21/39 [cloudpathlib]\n", " ---------------------- ----------------- 22/39 [catalogue]\n", " ----------------------- ---------------- 23/39 [blis]\n", " ------------------------ --------------- 24/39 [aiofiles]\n", " ------------------------ --------------- 24/39 [aiofiles]\n", " ------------------------- -------------- 25/39 [srsly]\n", " ------------------------- -------------- 25/39 [srsly]\n", " ------------------------- -------------- 25/39 [srsly]\n", " ------------------------- -------------- 25/39 [srsly]\n", " ------------------------- -------------- 25/39 [srsly]\n", " ------------------------- -------------- 25/39 [srsly]\n", " ------------------------- -------------- 25/39 [srsly]\n", " ------------------------- -------------- 25/39 [srsly]\n", " ------------------------- -------------- 25/39 [srsly]\n", " ------------------------- -------------- 25/39 [srsly]\n", " ------------------------- -------------- 25/39 [srsly]\n", " ------------------------- -------------- 25/39 [srsly]\n", " ------------------------- -------------- 25/39 [srsly]\n", " ------------------------- -------------- 25/39 [srsly]\n", " ------------------------- -------------- 25/39 [srsly]\n", " ------------------------- -------------- 25/39 [srsly]\n", " ------------------------- -------------- 25/39 [srsly]\n", " -------------------------- ------------- 26/39 [smart-open]\n", " -------------------------- ------------- 26/39 [smart-open]\n", " -------------------------- ------------- 26/39 [smart-open]\n", " --------------------------- ------------ 27/39 [python-oxmsg]\n", " --------------------------- ------------ 27/39 [python-oxmsg]\n", " --------------------------- ------------ 27/39 [python-oxmsg]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ----------------------------- ---------- 29/39 [numba]\n", " ------------------------------ --------- 30/39 [cffi]\n", " ------------------------------ --------- 30/39 [cffi]\n", " ------------------------------ --------- 30/39 [cffi]\n", " ------------------------------- -------- 31/39 [cryptography]\n", " ------------------------------- -------- 31/39 [cryptography]\n", " ------------------------------- -------- 31/39 [cryptography]\n", " ------------------------------- -------- 31/39 [cryptography]\n", " ------------------------------- -------- 31/39 [cryptography]\n", " ------------------------------- -------- 31/39 [cryptography]\n", " ------------------------------- -------- 31/39 [cryptography]\n", " ------------------------------- -------- 31/39 [cryptography]\n", " ------------------------------- -------- 31/39 [cryptography]\n", " ------------------------------- -------- 31/39 [cryptography]\n", " -------------------------------- ------- 32/39 [confection]\n", " --------------------------------- ------ 33/39 [unstructured-client]\n", " --------------------------------- ------ 33/39 [unstructured-client]\n", " --------------------------------- ------ 33/39 [unstructured-client]\n", " --------------------------------- ------ 33/39 [unstructured-client]\n", " --------------------------------- ------ 33/39 [unstructured-client]\n", " --------------------------------- ------ 33/39 [unstructured-client]\n", " --------------------------------- ------ 33/39 [unstructured-client]\n", " --------------------------------- ------ 33/39 [unstructured-client]\n", " --------------------------------- ------ 33/39 [unstructured-client]\n", " --------------------------------- ------ 33/39 [unstructured-client]\n", " --------------------------------- ------ 33/39 [unstructured-client]\n", " --------------------------------- ------ 33/39 [unstructured-client]\n", " --------------------------------- ------ 33/39 [unstructured-client]\n", " --------------------------------- ------ 33/39 [unstructured-client]\n", " --------------------------------- ------ 33/39 [unstructured-client]\n", " --------------------------------- ------ 33/39 [unstructured-client]\n", " --------------------------------- ------ 33/39 [unstructured-client]\n", " --------------------------------- ------ 33/39 [unstructured-client]\n", " --------------------------------- ------ 33/39 [unstructured-client]\n", " --------------------------------- ------ 33/39 [unstructured-client]\n", " --------------------------------- ------ 33/39 [unstructured-client]\n", " --------------------------------- ------ 33/39 [unstructured-client]\n", " --------------------------------- ------ 33/39 [unstructured-client]\n", " --------------------------------- ------ 33/39 [unstructured-client]\n", " --------------------------------- ------ 33/39 [unstructured-client]\n", " --------------------------------- ------ 33/39 [unstructured-client]\n", " --------------------------------- ------ 33/39 [unstructured-client]\n", " --------------------------------- ------ 33/39 [unstructured-client]\n", " --------------------------------- ------ 33/39 [unstructured-client]\n", " ----------------------------------- ---- 35/39 [thinc]\n", " ----------------------------------- ---- 35/39 [thinc]\n", " ----------------------------------- ---- 35/39 [thinc]\n", " ----------------------------------- ---- 35/39 [thinc]\n", " ----------------------------------- ---- 35/39 [thinc]\n", " ----------------------------------- ---- 35/39 [thinc]\n", " ----------------------------------- ---- 35/39 [thinc]\n", " ----------------------------------- ---- 35/39 [thinc]\n", " ----------------------------------- ---- 35/39 [thinc]\n", " ----------------------------------- ---- 35/39 [thinc]\n", " ----------------------------------- ---- 35/39 [thinc]\n", " ----------------------------------- ---- 35/39 [thinc]\n", " ----------------------------------- ---- 35/39 [thinc]\n", " ----------------------------------- ---- 35/39 [thinc]\n", " ----------------------------------- ---- 35/39 [thinc]\n", " ----------------------------------- ---- 35/39 [thinc]\n", " ----------------------------------- ---- 35/39 [thinc]\n", " ----------------------------------- ---- 35/39 [thinc]\n", " ----------------------------------- ---- 35/39 [thinc]\n", " ----------------------------------- ---- 35/39 [thinc]\n", " ------------------------------------ --- 36/39 [weasel]\n", " ------------------------------------ --- 36/39 [weasel]\n", " ------------------------------------ --- 36/39 [weasel]\n", " ------------------------------------ --- 36/39 [weasel]\n", " ------------------------------------ --- 36/39 [weasel]\n", " ------------------------------------ --- 36/39 [weasel]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " ------------------------------------- -- 37/39 [spacy]\n", " -------------------------------------- - 38/39 [unstructured]\n", " -------------------------------------- - 38/39 [unstructured]\n", " -------------------------------------- - 38/39 [unstructured]\n", " -------------------------------------- - 38/39 [unstructured]\n", " -------------------------------------- - 38/39 [unstructured]\n", " -------------------------------------- - 38/39 [unstructured]\n", " -------------------------------------- - 38/39 [unstructured]\n", " -------------------------------------- - 38/39 [unstructured]\n", " -------------------------------------- - 38/39 [unstructured]\n", " -------------------------------------- - 38/39 [unstructured]\n", " -------------------------------------- - 38/39 [unstructured]\n", " -------------------------------------- - 38/39 [unstructured]\n", " -------------------------------------- - 38/39 [unstructured]\n", " -------------------------------------- - 38/39 [unstructured]\n", " -------------------------------------- - 38/39 [unstructured]\n", " -------------------------------------- - 38/39 [unstructured]\n", " ---------------------------------------- 39/39 [unstructured]\n", "\n", "Successfully installed aiofiles-25.1.0 blis-1.3.3 catalogue-2.0.10 cffi-2.0.0 cloudpathlib-0.23.0 confection-0.1.5 cryptography-46.0.5 cymem-2.0.13 emoji-2.15.0 filetype-1.2.0 html5lib-1.1 installer-0.7.0 langdetect-1.0.9 llvmlite-0.46.0 lxml-6.0.2 murmurhash-1.0.15 numba-0.64.0 olefile-0.47 preshed-3.0.12 pycparser-3.0 pypdf-6.8.0 pypdfium2-5.6.0 python-iso639-2026.1.31 python-magic-0.4.27 python-oxmsg-0.0.2 rapidfuzz-3.14.3 smart-open-7.5.1 spacy-3.8.11 spacy-legacy-3.0.12 spacy-loggers-1.0.5 srsly-2.5.2 thinc-8.3.10 typer-slim-0.24.0 unstructured-0.21.5 unstructured-client-0.42.10 wasabi-1.1.3 weasel-0.4.3 webencodings-0.5.1 wrapt-1.17.3\n", "Note: you may need to restart the kernel to use updated packages.\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "\n", "[notice] A new release of pip is available: 25.1.1 -> 26.0.1\n", "[notice] To update, run: python.exe -m pip install --upgrade pip\n" ] } ], "source": [ "%pip install unstructured" ] }, { "cell_type": "code", "execution_count": 5, "id": "9cefd84e", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Note: you may need to restart the kernel to use updated packages.\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "\n", "[notice] A new release of pip is available: 25.1.1 -> 26.0.1\n", "[notice] To update, run: python.exe -m pip install --upgrade pip\n" ] } ], "source": [ "%pip install -qU langchain-community beautifulsoup4" ] }, { "cell_type": "code", "execution_count": 28, "id": "99737f9f", "metadata": {}, "outputs": [], "source": [ "from langchain_community.document_loaders import UnstructuredHTMLLoader, UnstructuredMarkdownLoader, TextLoader, BSHTMLLoader\n", "from langchain_text_splitters import RecursiveCharacterTextSplitter\n", "from langchain_community.embeddings import HuggingFaceEmbeddings\n", "from langchain_community.vectorstores import Chroma\n", "from pathlib import Path" ] }, { "cell_type": "code", "execution_count": 34, "id": "7e520e70", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[Document(metadata={'source': '..\\\\..\\\\docs\\\\abc.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Runtime Services »\\n\\nabc — Abstract Base Classes\\n\\n|\\n\\nabc — Abstract Base Classes¶\\n\\nSource code: Lib/abc.py\\n\\nThis module provides the infrastructure for defining abstract base classes (ABCs) in Python, as outlined in PEP 3119; see the PEP for why this was added to Python. (See also PEP 3141 and the numbers module regarding a type hierarchy for numbers based on ABCs.)\\n\\nThe collections module has some concrete classes that derive from ABCs; these can, of course, be further derived. In addition, the collections.abc submodule has some ABCs that can be used to test whether a class or instance provides a particular interface, for example, if it is hashable or if it is a mapping.\\n\\nThis module provides the metaclass ABCMeta for defining ABCs and a helper class ABC to alternatively define ABCs through inheritance:\\n\\nThe abc module also provides the following decorator:\\n\\nThe abc module also supports the following legacy decorators:\\n\\nThe abc module also provides the following functions:\\n\\nFootnotes\\n\\n[1]\\n\\nC++ programmers should note that Python’s virtual base class concept is not the same as C++’s.\\n\\nPrevious topic\\n\\ncontextlib — Utilities for with-statement contexts\\n\\nNext topic\\n\\natexit — Exit handlers\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Runtime Services »\\n\\nabc — Abstract Base Classes\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\aifc.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nRemoved Modules »\\n\\naifc — Read and write AIFF and AIFC files\\n\\n|\\n\\naifc — Read and write AIFF and AIFC files¶\\n\\nDeprecated since version 3.11, removed in version 3.13.\\n\\nThis module is no longer part of the Python standard library. It was removed in Python 3.13 after being deprecated in Python 3.11. The removal was decided in PEP 594.\\n\\nThe last version of Python that provided the aifc module was Python 3.12.\\n\\nPrevious topic\\n\\nRemoved Modules\\n\\nNext topic\\n\\nasynchat — Asynchronous socket command/response handler\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nRemoved Modules »\\n\\naifc — Read and write AIFF and AIFC files\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\allos.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nGeneric Operating System Services\\n\\n|\\n\\nGeneric Operating System Services¶\\n\\nThe modules described in this chapter provide interfaces to operating system features that are available on (almost) all operating systems, such as files and a clock. The interfaces are generally modeled after the Unix or C interfaces, but they are available on most other systems as well. Here’s an overview:\\n\\nos — Miscellaneous operating system interfaces\\n\\nFile Names, Command Line Arguments, and Environment Variables\\n\\nPython UTF-8 Mode\\n\\nProcess Parameters\\n\\nFile Object Creation\\n\\nFile Descriptor Operations\\n\\nQuerying the size of a terminal\\n\\nInheritance of File Descriptors\\n\\nFiles and Directories\\n\\nTimer File Descriptors\\n\\nLinux extended attributes\\n\\nProcess Management\\n\\nInterface to the scheduler\\n\\nMiscellaneous System Information\\n\\nRandom numbers\\n\\nio — Core tools for working with streams\\n\\nOverview\\n\\nText I/O\\n\\nBinary I/O\\n\\nRaw I/O\\n\\nText Encoding\\n\\nOpt-in EncodingWarning\\n\\nHigh-level Module Interface\\n\\nClass hierarchy\\n\\nI/O Base Classes\\n\\nRaw File I/O\\n\\nBuffered Streams\\n\\nText I/O\\n\\nStatic Typing\\n\\nPerformance\\n\\nBinary I/O\\n\\nText I/O\\n\\nMulti-threading\\n\\nReentrancy\\n\\ntime — Time access and conversions\\n\\nFunctions\\n\\nClock ID Constants\\n\\nTimezone Constants\\n\\nlogging — Logging facility for Python\\n\\nLogger Objects\\n\\nLogging Levels\\n\\nHandler Objects\\n\\nFormatter Objects\\n\\nFilter Objects\\n\\nLogRecord Objects\\n\\nLogRecord attributes\\n\\nLoggerAdapter Objects\\n\\nThread Safety\\n\\nModule-Level Functions\\n\\nModule-Level Attributes\\n\\nIntegration with the warnings module\\n\\nlogging.config — Logging configuration\\n\\nConfiguration functions\\n\\nSecurity considerations\\n\\nConfiguration dictionary schema\\n\\nDictionary Schema Details\\n\\nIncremental Configuration\\n\\nObject connections\\n\\nUser-defined objects\\n\\nHandler configuration order\\n\\nAccess to external objects\\n\\nAccess to internal objects\\n\\nImport resolution and custom importers\\n\\nConfiguring QueueHandler and QueueListener\\n\\nConfiguration file format\\n\\nlogging.handlers — Logging handlers\\n\\nStreamHandler\\n\\nFileHandler\\n\\nNullHandler\\n\\nWatchedFileHandler\\n\\nBaseRotatingHandler\\n\\nRotatingFileHandler\\n\\nTimedRotatingFileHandler\\n\\nSocketHandler\\n\\nDatagramHandler\\n\\nSysLogHandler\\n\\nNTEventLogHandler\\n\\nSMTPHandler\\n\\nMemoryHandler\\n\\nHTTPHandler\\n\\nQueueHandler\\n\\nQueueListener\\n\\nplatform — Access to underlying platform’s identifying data\\n\\nCross platform\\n\\nWindows platform\\n\\nmacOS platform\\n\\niOS platform\\n\\nUnix platforms\\n\\nLinux platforms\\n\\nAndroid platform\\n\\nCommand-line usage\\n\\nerrno — Standard errno system symbols\\n\\nctypes — A foreign function library for Python\\n\\nctypes tutorial\\n\\nLoading dynamic link libraries\\n\\nAccessing functions from loaded dlls\\n\\nCalling functions\\n\\nFundamental data types\\n\\nCalling functions, continued\\n\\nCalling variadic functions\\n\\nCalling functions with your own custom data types\\n\\nSpecifying the required argument types (function prototypes)\\n\\nReturn types\\n\\nPassing pointers (or: passing parameters by reference)\\n\\nStructures and unions\\n\\nStructure/union layout, alignment and byte order\\n\\nBit fields in structures and unions\\n\\nArrays\\n\\nPointers\\n\\nThread safety without the GIL\\n\\nType conversions\\n\\nIncomplete Types\\n\\nCallback functions\\n\\nAccessing values exported from dlls\\n\\nSurprises\\n\\nVariable-sized data types\\n\\nctypes reference\\n\\nFinding shared libraries\\n\\nListing loaded shared libraries\\n\\nLoading shared libraries\\n\\nForeign functions\\n\\nFunction prototypes\\n\\nUtility functions\\n\\nData types\\n\\nFundamental data types\\n\\nStructured data types\\n\\nArrays and pointers\\n\\nExceptions\\n\\nPrevious topic\\n\\nsecrets — Generate secure random numbers for managing secrets\\n\\nNext topic\\n\\nos — Miscellaneous operating system interfaces\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nGeneric Operating System Services\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\annotationlib.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Runtime Services »\\n\\nannotationlib — Functionality for introspecting annotations\\n\\n|\\n\\nannotationlib — Functionality for introspecting annotations¶\\n\\nAdded in version 3.14.\\n\\nSource code: Lib/annotationlib.py\\n\\nThe annotationlib module provides tools for introspecting annotations on modules, classes, and functions.\\n\\nAnnotations are 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.\\n\\nThis module supports retrieving annotations in three main formats (see Format), each of which works best for different use cases:\\n\\nVALUE 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.\\n\\nFORWARDREF returns 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.\\n\\nSTRING 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.\\n\\nThe 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 annotate function that is used to evaluate annotations, such as get_annotate_from_class_namespace() and call_annotate_function(), as well as the call_evaluate_function() function for working with evaluate functions.\\n\\nCaution\\n\\nMost functionality in this module can execute arbitrary code; see the security section for more information.\\n\\nSee also\\n\\nPEP 649 proposed the current model for how annotations work in Python.\\n\\nPEP 749 expanded on various aspects of PEP 649 and introduced the annotationlib module.\\n\\nAnnotations Best Practices provides best practices for working with annotations.\\n\\ntyping-extensions provides a backport of get_annotations() that works on earlier versions of Python.\\n\\nAnnotation semantics¶\\n\\nThe way annotations are evaluated has changed over the history of Python 3, and currently still depends on a future import. There have been execution models for annotations:\\n\\nStock semantics (default in Python 3.0 through 3.13; see PEP 3107 and PEP 526): Annotations are evaluated eagerly, as they are encountered in the source code.\\n\\nStringified annotations (used with from __future__ import annotations in Python 3.7 and newer; see PEP 563): Annotations are stored as strings only.\\n\\nDeferred evaluation (default in Python 3.14 and newer; see PEP 649 and PEP 749): Annotations are evaluated lazily, only when they are accessed.\\n\\nAs an example, consider the following program:\\n\\ndef func(a: Cls) -> None:\\n print(a)\\n\\nclass Cls: pass\\n\\nprint(func.__annotations__)\\n\\nThis will behave as follows:\\n\\nUnder stock semantics (Python 3.13 and earlier), it will throw a NameError at the line where func is defined, because Cls is an undefined name at that point.\\n\\nUnder stringified annotations (if from __future__ import annotations is used), it will print {\\'a\\': \\'Cls\\', \\'return\\': \\'None\\'}.\\n\\nUnder deferred evaluation (Python 3.14 and later), it will print {\\'a\\': , \\'return\\': None}.\\n\\nStock semantics were used when function annotations were first introduced in Python 3.0 (by 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 PEP 526). 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, PEP 563 introduced the ability to store annotations as strings using the 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, PEP 649, introduced the third execution model, deferred evaluation, and was implemented in Python 3.14. Stringified annotations are still used if from __future__ import annotations is present, but this behavior will eventually be removed.\\n\\nClasses¶\\n\\nFunctions¶\\n\\nRecipes¶\\n\\nUsing annotations in a metaclass¶\\n\\nA 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 from __future__ import annotations, the annotations will be in the __annotations__ key of the dictionary. For other classes with annotations, get_annotate_from_class_namespace() can be used to get the annotate function, and call_annotate_function() can be used to call it and retrieve the annotations. Using the 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.\\n\\nTo 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.\\n\\nBelow is an example of a metaclass that filters out all typing.ClassVar annotations from the class and puts them in a separate attribute:\\n\\nimport annotationlib\\nimport typing\\n\\nclass ClassVarSeparator(type):\\n def __new__(mcls, name, bases, ns):\\n if \"__annotations__\" in ns: # from __future__ import annotations\\n annotations = ns[\"__annotations__\"]\\n classvar_keys = {\\n key for key, value in annotations.items()\\n # Use string comparison for simplicity; a more robust solution\\n # could use annotationlib.ForwardRef.evaluate\\n if value.startswith(\"ClassVar\")\\n }\\n classvars = {key: annotations[key] for key in classvar_keys}\\n ns[\"__annotations__\"] = {\\n key: value for key, value in annotations.items()\\n if key not in classvar_keys\\n }\\n wrapped_annotate = None\\n elif annotate := annotationlib.get_annotate_from_class_namespace(ns):\\n annotations = annotationlib.call_annotate_function(\\n annotate, format=annotationlib.Format.FORWARDREF\\n )\\n classvar_keys = {\\n key for key, value in annotations.items()\\n if typing.get_origin(value) is typing.ClassVar\\n }\\n classvars = {key: annotations[key] for key in classvar_keys}\\n\\n def wrapped_annotate(format):\\n annos = annotationlib.call_annotate_function(annotate, format, owner=typ)\\n return {key: value for key, value in annos.items() if key not in classvar_keys}\\n\\n else: # no annotations\\n classvars = {}\\n wrapped_annotate = None\\n typ = super().__new__(mcls, name, bases, ns)\\n\\n if wrapped_annotate is not None:\\n # Wrap the original __annotate__ with a wrapper that removes ClassVars\\n typ.__annotate__ = wrapped_annotate\\n typ.classvars = classvars # Store the ClassVars in a separate attribute\\n return typ\\n\\nLimitations of the STRING format¶\\n\\nThe 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.\\n\\nFirst, 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.\\n\\nSecond, 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 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:\\n\\n>>> def f(x: (1).__class__.__base__.__subclasses__()[-1].__init__.__builtins__[\"print\"](\"Hello world\")): pass\\n...\\n>>> annotationlib.get_annotations(f, format=annotationlib.Format.STRING)\\nHello world\\n{\\'x\\': \\'None\\'}\\n\\nNote\\n\\nThis particular example works as of the time of writing, but it relies on implementation details and is not guaranteed to work in the future.\\n\\nAmong the different kinds of expressions that exist in Python, as represented by the ast module, some expressions are supported, meaning that the STRING format can generally recover the original source code; others are unsupported, meaning that they may result in incorrect output or an error.\\n\\nThe following are supported (sometimes with caveats):\\n\\nast.BinOp\\n\\nast.UnaryOp\\n\\nast.Invert (~), ast.UAdd (+), and ast.USub (-) are supported\\n\\nast.Not (not) is not supported\\n\\nast.Dict (except when using ** unpacking)\\n\\nast.Set\\n\\nast.Compare\\n\\nast.Eq and ast.NotEq are supported\\n\\nast.Lt, ast.LtE, ast.Gt, and ast.GtE are supported, but the operand may be flipped\\n\\nast.Is, ast.IsNot, ast.In, and ast.NotIn are not supported\\n\\nast.Call (except when using ** unpacking)\\n\\nast.Constant (though not the exact representation of the constant; for example, escape sequences in strings are lost; hexadecimal numbers are converted to decimal)\\n\\nast.Attribute (assuming the value is not a constant)\\n\\nast.Subscript (assuming the value is not a constant)\\n\\nast.Starred (* unpacking)\\n\\nast.Name\\n\\nast.List\\n\\nast.Tuple\\n\\nast.Slice\\n\\nThe following are unsupported, but throw an informative error when encountered by the stringifier:\\n\\nast.FormattedValue (f-strings; error is not detected if conversion specifiers like !r are used)\\n\\nast.JoinedStr (f-strings)\\n\\nThe following are unsupported and result in incorrect output:\\n\\nast.BoolOp (and and or)\\n\\nast.IfExp\\n\\nast.Lambda\\n\\nast.ListComp\\n\\nast.SetComp\\n\\nast.DictComp\\n\\nast.GeneratorExp\\n\\nThe following are disallowed in annotation scopes and therefore not relevant:\\n\\nast.NamedExpr (:=)\\n\\nast.Await\\n\\nast.Yield\\n\\nast.YieldFrom\\n\\nLimitations of the FORWARDREF format¶\\n\\nThe FORWARDREF format aims to produce real values as much as possible, with anything that cannot be resolved replaced with ForwardRef objects. It is affected by broadly the same Limitations as the STRING format: annotations that perform operations on literals or that use unsupported expression types may raise exceptions when evaluated using the FORWARDREF format.\\n\\nBelow are a few examples of the behavior with unsupported expressions:\\n\\n>>> from annotationlib import get_annotations, Format\\n>>> def zerodiv(x: 1 / 0): ...\\n>>> get_annotations(zerodiv, format=Format.STRING)\\nTraceback (most recent call last):\\n ...\\nZeroDivisionError: division by zero\\n>>> get_annotations(zerodiv, format=Format.FORWARDREF)\\nTraceback (most recent call last):\\n ...\\nZeroDivisionError: division by zero\\n>>> def ifexp(x: 1 if y else 0): ...\\n>>> get_annotations(ifexp, format=Format.STRING)\\n{\\'x\\': \\'1\\'}\\n\\nSecurity implications of introspecting annotations¶\\n\\nMuch of the functionality in this module involves executing code related to annotations, which can then do arbitrary things. For example, get_annotations() may call an arbitrary annotate function, and ForwardRef.evaluate() may call 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 __annotations__ attribute, and for various functions in the typing module that work with annotations, such as typing.get_type_hints().\\n\\nAny 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 __annotations__ dictionary or directly creating a ForwardRef object.\\n\\nTable of Contents\\n\\nannotationlib — Functionality for introspecting annotations\\n\\nAnnotation semantics\\n\\nClasses\\n\\nFunctions\\n\\nRecipes\\n\\nUsing annotations in a metaclass\\n\\nLimitations of the STRING format\\n\\nLimitations of the FORWARDREF format\\n\\nSecurity implications of introspecting annotations\\n\\nPrevious topic\\n\\ninspect — Inspect live objects\\n\\nNext topic\\n\\nsite — Site-specific configuration hook\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Runtime Services »\\n\\nannotationlib — Functionality for introspecting annotations\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\archiving.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Compression and Archiving\\n\\n|\\n\\nData Compression and Archiving¶\\n\\nThe 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 Archiving operations provided by the shutil module.\\n\\nThe compression package\\n\\ncompression.zstd — Compression compatible with the Zstandard format\\n\\nExceptions\\n\\nReading and writing compressed files\\n\\nCompressing and decompressing data in memory\\n\\nZstandard dictionaries\\n\\nAdvanced parameter control\\n\\nMiscellaneous\\n\\nExamples\\n\\nzlib — Compression compatible with gzip\\n\\ngzip — Support for gzip files\\n\\nExamples of usage\\n\\nCommand-line interface\\n\\nCommand-line options\\n\\nbz2 — Support for bzip2 compression\\n\\n(De)compression of files\\n\\nIncremental (de)compression\\n\\nOne-shot (de)compression\\n\\nExamples of usage\\n\\nlzma — Compression using the LZMA algorithm\\n\\nReading and writing compressed files\\n\\nCompressing and decompressing data in memory\\n\\nMiscellaneous\\n\\nSpecifying custom filter chains\\n\\nExamples\\n\\nzipfile — Work with ZIP archives\\n\\nZipFile objects\\n\\nPath objects\\n\\nPyZipFile objects\\n\\nZipInfo objects\\n\\nCommand-line interface\\n\\nCommand-line options\\n\\nDecompression pitfalls\\n\\nFrom file itself\\n\\nFile system limitations\\n\\nResources limitations\\n\\nInterruption\\n\\nDefault behaviors of extraction\\n\\ntarfile — Read and write tar archive files\\n\\nTarFile Objects\\n\\nTarInfo Objects\\n\\nExtraction filters\\n\\nDefault named filters\\n\\nFilter errors\\n\\nHints for further verification\\n\\nSupporting older Python versions\\n\\nStateful extraction filter example\\n\\nCommand-Line Interface\\n\\nCommand-line options\\n\\nExamples\\n\\nReading examples\\n\\nWriting examples\\n\\nSupported tar formats\\n\\nUnicode issues\\n\\nPrevious topic\\n\\nsqlite3 — DB-API 2.0 interface for SQLite databases\\n\\nNext topic\\n\\nThe compression package\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Compression and Archiving\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\argparse.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nCommand-line interface libraries »\\n\\nargparse — Parser for command-line options, arguments and subcommands\\n\\n|\\n\\nargparse — Parser for command-line options, arguments and subcommands¶\\n\\nAdded in version 3.2.\\n\\nSource code: Lib/argparse.py\\n\\nNote\\n\\nWhile 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 Choosing an argument parsing library for alternatives to consider when 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 - even when they correspond to another defined option).\\n\\nTutorial\\n\\nThis page contains the API reference information. For a more gentle introduction to Python command-line parsing, have a look at the argparse tutorial.\\n\\nThe argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. The argparse module also automatically generates help and usage messages. The module will also issue errors when users give the program invalid arguments.\\n\\nThe argparse module’s support for command-line interfaces is built around an instance of argparse.ArgumentParser. It is a container for argument specifications and has options that apply to the parser as whole:\\n\\nparser = argparse.ArgumentParser(\\n prog=\\'ProgramName\\',\\n description=\\'What the program does\\',\\n epilog=\\'Text at the bottom of help\\')\\n\\nThe ArgumentParser.add_argument() method attaches individual argument specifications to the parser. It supports positional arguments, options that accept values, and on/off flags:\\n\\nparser.add_argument(\\'filename\\') # positional argument\\nparser.add_argument(\\'-c\\', \\'--count\\') # option that takes a value\\nparser.add_argument(\\'-v\\', \\'--verbose\\',\\n action=\\'store_true\\') # on/off flag\\n\\nThe ArgumentParser.parse_args() method runs the parser and places the extracted data in a argparse.Namespace object:\\n\\nargs = parser.parse_args()\\nprint(args.filename, args.count, args.verbose)\\n\\nNote\\n\\nIf you’re looking for a guide about how to upgrade optparse code to argparse, see Upgrading Optparse Code.\\n\\nArgumentParser objects¶\\n\\nThe following sections describe how each of these are used.\\n\\nprog¶\\n\\nBy default, ArgumentParser calculates the name of the program to display in help messages depending on the way the Python interpreter was run:\\n\\nThe base name of sys.argv[0] if a file was passed as argument.\\n\\nThe Python interpreter name followed by sys.argv[0] if a directory or a zipfile was passed as argument.\\n\\nThe Python interpreter name followed by -m followed by the module or package name if the -m option was used.\\n\\nThis 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 prog= argument to ArgumentParser:\\n\\n>>> parser = argparse.ArgumentParser(prog=\\'myprogram\\')\\n>>> parser.print_help()\\nusage: myprogram [-h]\\n\\noptions:\\n -h, --help show this help message and exit\\n\\nNote that the program name, whether determined from sys.argv[0], from the __main__ module attributes or from the prog= argument, is available to help messages using the %(prog)s format specifier.\\n\\n>>> parser = argparse.ArgumentParser(prog=\\'myprogram\\')\\n>>> parser.add_argument(\\'--foo\\', help=\\'foo of the %(prog)s program\\')\\n>>> parser.print_help()\\nusage: myprogram [-h] [--foo FOO]\\n\\noptions:\\n -h, --help show this help message and exit\\n --foo FOO foo of the myprogram program\\n\\nChanged in version 3.14: The default prog value now reflects how __main__ was actually executed, rather than always being os.path.basename(sys.argv[0]).\\n\\nusage¶\\n\\nBy default, ArgumentParser calculates the usage message from the arguments it contains. The default message can be overridden with the usage= keyword argument:\\n\\n>>> parser = argparse.ArgumentParser(prog=\\'PROG\\', usage=\\'%(prog)s [options]\\')\\n>>> parser.add_argument(\\'--foo\\', nargs=\\'?\\', help=\\'foo help\\')\\n>>> parser.add_argument(\\'bar\\', nargs=\\'+\\', help=\\'bar help\\')\\n>>> parser.print_help()\\nusage: PROG [options]\\n\\npositional arguments:\\n bar bar help\\n\\noptions:\\n -h, --help show this help message and exit\\n --foo [FOO] foo help\\n\\nThe %(prog)s format specifier is available to fill in the program name in your usage messages.\\n\\nWhen a custom usage message is specified for the main parser, you may also want to consider passing the prog argument to add_subparsers() or the prog and the usage arguments to add_parser(), to ensure consistent command prefixes and usage information across subparsers.\\n\\ndescription¶\\n\\nMost calls to the ArgumentParser constructor will use the 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.\\n\\nBy default, the description will be line-wrapped so that it fits within the given space. To change this behavior, see the formatter_class argument.\\n\\nepilog¶\\n\\nSome programs like to display additional description of the program after the description of the arguments. Such text can be specified using the epilog= argument to ArgumentParser:\\n\\n>>> parser = argparse.ArgumentParser(\\n... description=\\'A foo that bars\\',\\n... epilog=\"And that\\'s how you\\'d foo a bar\")\\n>>> parser.print_help()\\nusage: argparse.py [-h]\\n\\nA foo that bars\\n\\noptions:\\n -h, --help show this help message and exit\\n\\nAnd that\\'s how you\\'d foo a bar\\n\\nAs with the description argument, the epilog= text is by default line-wrapped, but this behavior can be adjusted with the formatter_class argument to ArgumentParser.\\n\\nparents¶\\n\\nSometimes, several parsers share a common set of arguments. Rather than repeating the definitions of these arguments, a single parser with all the shared arguments and passed to parents= argument to ArgumentParser can be used. The parents= argument takes a list of ArgumentParser objects, collects all the positional and optional actions from them, and adds these actions to the ArgumentParser object being constructed:\\n\\n>>> parent_parser = argparse.ArgumentParser(add_help=False)\\n>>> parent_parser.add_argument(\\'--parent\\', type=int)\\n\\n>>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])\\n>>> foo_parser.add_argument(\\'foo\\')\\n>>> foo_parser.parse_args([\\'--parent\\', \\'2\\', \\'XXX\\'])\\nNamespace(foo=\\'XXX\\', parent=2)\\n\\n>>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])\\n>>> bar_parser.add_argument(\\'--bar\\')\\n>>> bar_parser.parse_args([\\'--bar\\', \\'YYY\\'])\\nNamespace(bar=\\'YYY\\', parent=None)\\n\\nNote that most parent parsers will specify add_help=False. Otherwise, the ArgumentParser will see two -h/--help options (one in the parent and one in the child) and raise an error.\\n\\nNote\\n\\nYou must fully initialize the parsers before passing them via parents=. If you change the parent parsers after the child parser, those changes will not be reflected in the child.\\n\\nformatter_class¶\\n\\nArgumentParser objects allow the help formatting to be customized by specifying an alternate formatting class. Currently, there are four such classes:\\n\\nRawDescriptionHelpFormatter and RawTextHelpFormatter give more control over how textual descriptions are displayed. By default, ArgumentParser objects line-wrap the description and epilog texts in command-line help messages:\\n\\n>>> parser = argparse.ArgumentParser(\\n... prog=\\'PROG\\',\\n... description=\\'\\'\\'this description\\n... was indented weird\\n... but that is okay\\'\\'\\',\\n... epilog=\\'\\'\\'\\n... likewise for this epilog whose whitespace will\\n... be cleaned up and whose words will be wrapped\\n... across a couple lines\\'\\'\\')\\n>>> parser.print_help()\\nusage: PROG [-h]\\n\\nthis description was indented weird but that is okay\\n\\noptions:\\n -h, --help show this help message and exit\\n\\nlikewise for this epilog whose whitespace will be cleaned up and whose words\\nwill be wrapped across a couple lines\\n\\nPassing RawDescriptionHelpFormatter as formatter_class= indicates that description and epilog are already correctly formatted and should not be line-wrapped:\\n\\n>>> parser = argparse.ArgumentParser(\\n... prog=\\'PROG\\',\\n... formatter_class=argparse.RawDescriptionHelpFormatter,\\n... description=textwrap.dedent(\\'\\'\\'\\\\\\n... Please do not mess up this text!\\n... --------------------------------\\n... I have indented it\\n... exactly the way\\n... I want it\\n... \\'\\'\\'))\\n>>> parser.print_help()\\nusage: PROG [-h]\\n\\nPlease do not mess up this text!\\n--------------------------------\\n I have indented it\\n exactly the way\\n I want it\\n\\noptions:\\n -h, --help show this help message and exit\\n\\nRawTextHelpFormatter 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.\\n\\nArgumentDefaultsHelpFormatter automatically adds information about default values to each of the argument help messages:\\n\\n>>> parser = argparse.ArgumentParser(\\n... prog=\\'PROG\\',\\n... formatter_class=argparse.ArgumentDefaultsHelpFormatter)\\n>>> parser.add_argument(\\'--foo\\', type=int, default=42, help=\\'FOO!\\')\\n>>> parser.add_argument(\\'bar\\', nargs=\\'*\\', default=[1, 2, 3], help=\\'BAR!\\')\\n>>> parser.print_help()\\nusage: PROG [-h] [--foo FOO] [bar ...]\\n\\npositional arguments:\\n bar BAR! (default: [1, 2, 3])\\n\\noptions:\\n -h, --help show this help message and exit\\n --foo FOO FOO! (default: 42)\\n\\nMetavarTypeHelpFormatter uses the name of the type argument for each argument as the display name for its values (rather than using the dest as the regular formatter does):\\n\\n>>> parser = argparse.ArgumentParser(\\n... prog=\\'PROG\\',\\n... formatter_class=argparse.MetavarTypeHelpFormatter)\\n>>> parser.add_argument(\\'--foo\\', type=int)\\n>>> parser.add_argument(\\'bar\\', type=float)\\n>>> parser.print_help()\\nusage: PROG [-h] [--foo int] float\\n\\npositional arguments:\\n float\\n\\noptions:\\n -h, --help show this help message and exit\\n --foo int\\n\\nprefix_chars¶\\n\\nMost command-line options will use - as the prefix, e.g. -f/--foo. Parsers that need to support different or additional prefix characters, e.g. for options like +f or /foo, may specify them using the prefix_chars= argument to the ArgumentParser constructor:\\n\\n>>> parser = argparse.ArgumentParser(prog=\\'PROG\\', prefix_chars=\\'-+\\')\\n>>> parser.add_argument(\\'+f\\')\\n>>> parser.add_argument(\\'++bar\\')\\n>>> parser.parse_args(\\'+f X ++bar Y\\'.split())\\nNamespace(bar=\\'Y\\', f=\\'X\\')\\n\\nThe prefix_chars= argument defaults to \\'-\\'. Supplying a set of characters that does not include - will cause -f/--foo options to be disallowed.\\n\\nfromfile_prefix_chars¶\\n\\nSometimes, when dealing with a particularly long argument list, it may make sense to keep the list of arguments in a file rather than typing it out at the command line. If the fromfile_prefix_chars= argument is given to the ArgumentParser constructor, then arguments that start with any of the specified characters will be treated as files, and will be replaced by the arguments they contain. For example:\\n\\n>>> with open(\\'args.txt\\', \\'w\\', encoding=sys.getfilesystemencoding()) as fp:\\n... fp.write(\\'-f\\\\nbar\\')\\n...\\n>>> parser = argparse.ArgumentParser(fromfile_prefix_chars=\\'@\\')\\n>>> parser.add_argument(\\'-f\\')\\n>>> parser.parse_args([\\'-f\\', \\'foo\\', \\'@args.txt\\'])\\nNamespace(f=\\'bar\\')\\n\\nArguments read from a file must be one per line by default (but see also 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 [\\'-f\\', \\'foo\\', \\'@args.txt\\'] is considered equivalent to the expression [\\'-f\\', \\'foo\\', \\'-f\\', \\'bar\\'].\\n\\nNote\\n\\nEmpty lines are treated as empty strings (\\'\\'), which are allowed as values but not as arguments. Empty lines that are read as arguments will result in an “unrecognized arguments” error.\\n\\nArgumentParser uses filesystem encoding and error handler to read the file containing arguments.\\n\\nThe fromfile_prefix_chars= argument defaults to None, meaning that arguments will never be treated as file references.\\n\\nChanged in version 3.12: ArgumentParser changed encoding and errors to read arguments files from default (e.g. locale.getpreferredencoding(False) and \"strict\") to the filesystem encoding and error handler. Arguments file should be encoded in UTF-8 instead of ANSI Codepage on Windows.\\n\\nargument_default¶\\n\\nGenerally, argument defaults are specified either by passing a default to add_argument() or by calling the set_defaults() methods with a specific set of name-value pairs. Sometimes however, it may be useful to specify a single parser-wide default for arguments. This can be accomplished by passing the argument_default= keyword argument to ArgumentParser. For example, to globally suppress attribute creation on parse_args() calls, we supply argument_default=SUPPRESS:\\n\\n>>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)\\n>>> parser.add_argument(\\'--foo\\')\\n>>> parser.add_argument(\\'bar\\', nargs=\\'?\\')\\n>>> parser.parse_args([\\'--foo\\', \\'1\\', \\'BAR\\'])\\nNamespace(bar=\\'BAR\\', foo=\\'1\\')\\n>>> parser.parse_args([])\\nNamespace()\\n\\nallow_abbrev¶\\n\\nNormally, when you pass an argument list to the parse_args() method of an ArgumentParser, it recognizes abbreviations of long options.\\n\\nThis feature can be disabled by setting allow_abbrev to False:\\n\\n>>> parser = argparse.ArgumentParser(prog=\\'PROG\\', allow_abbrev=False)\\n>>> parser.add_argument(\\'--foobar\\', action=\\'store_true\\')\\n>>> parser.add_argument(\\'--foonley\\', action=\\'store_false\\')\\n>>> parser.parse_args([\\'--foon\\'])\\nusage: PROG [-h] [--foobar] [--foonley]\\nPROG: error: unrecognized arguments: --foon\\n\\nAdded in version 3.5.\\n\\nconflict_handler¶\\n\\nArgumentParser objects do not allow two actions with the same option string. By default, ArgumentParser objects raise an exception if an attempt is made to create an argument with an option string that is already in use:\\n\\n>>> parser = argparse.ArgumentParser(prog=\\'PROG\\')\\n>>> parser.add_argument(\\'-f\\', \\'--foo\\', help=\\'old foo help\\')\\n>>> parser.add_argument(\\'--foo\\', help=\\'new foo help\\')\\nTraceback (most recent call last):\\n ..\\nArgumentError: argument --foo: conflicting option string(s): --foo\\n\\nSometimes (e.g. when using parents) it may be useful to simply override any older arguments with the same option string. To get this behavior, the value \\'resolve\\' can be supplied to the conflict_handler= argument of ArgumentParser:\\n\\n>>> parser = argparse.ArgumentParser(prog=\\'PROG\\', conflict_handler=\\'resolve\\')\\n>>> parser.add_argument(\\'-f\\', \\'--foo\\', help=\\'old foo help\\')\\n>>> parser.add_argument(\\'--foo\\', help=\\'new foo help\\')\\n>>> parser.print_help()\\nusage: PROG [-h] [-f FOO] [--foo FOO]\\n\\noptions:\\n -h, --help show this help message and exit\\n -f FOO old foo help\\n --foo FOO new foo help\\n\\nNote that ArgumentParser objects only remove an action if all of its option strings are overridden. So, in the example above, the old -f/--foo action is retained as the -f action, because only the --foo option string was overridden.\\n\\nadd_help¶\\n\\nBy default, ArgumentParser objects add an option which simply displays the parser’s help message. If -h or --help is supplied at the command line, the ArgumentParser help will be printed.\\n\\nOccasionally, it may be useful to disable the addition of this help option. This can be achieved by passing False as the add_help= argument to ArgumentParser:\\n\\n>>> parser = argparse.ArgumentParser(prog=\\'PROG\\', add_help=False)\\n>>> parser.add_argument(\\'--foo\\', help=\\'foo help\\')\\n>>> parser.print_help()\\nusage: PROG [--foo FOO]\\n\\noptions:\\n --foo FOO foo help\\n\\nThe help option is typically -h/--help. The exception to this is if the prefix_chars= is specified and does not include -, in which case -h and --help are not valid options. In this case, the first character in prefix_chars is used to prefix the help options:\\n\\n>>> parser = argparse.ArgumentParser(prog=\\'PROG\\', prefix_chars=\\'+/\\')\\n>>> parser.print_help()\\nusage: PROG [+h]\\n\\noptions:\\n +h, ++help show this help message and exit\\n\\nexit_on_error¶\\n\\nNormally, when you pass an invalid argument list to the parse_args() method of an ArgumentParser, it will print a message to sys.stderr and exit with a status code of 2.\\n\\nIf the user would like to catch errors manually, the feature can be enabled by setting exit_on_error to False:\\n\\n>>> parser = argparse.ArgumentParser(exit_on_error=False)\\n>>> parser.add_argument(\\'--integers\\', type=int)\\n_StoreAction(option_strings=[\\'--integers\\'], dest=\\'integers\\', nargs=None, const=None, default=None, type=, choices=None, help=None, metavar=None)\\n>>> try:\\n... parser.parse_args(\\'--integers a\\'.split())\\n... except argparse.ArgumentError:\\n... print(\\'Catching an argumentError\\')\\n...\\nCatching an argumentError\\n\\nAdded in version 3.9.\\n\\nsuggest_on_error¶\\n\\nBy default, when a user passes an invalid argument choice or subparser name, ArgumentParser will exit with error info and provide suggestions for mistyped arguments. The error message will list the permissible argument choices (if specified) or subparser names, along with a “maybe you meant” suggestion if a close match is found. Note that this only applies for arguments when the choices specified are strings:\\n\\n>>> parser = argparse.ArgumentParser(suggest_on_error=True)\\n>>> parser.add_argument(\\'--action\\', choices=[\\'debug\\', \\'dryrun\\'])\\n>>> parser.parse_args([\\'--action\\', \\'debugg\\'])\\nusage: tester.py [-h] [--action {debug,dryrun}]\\ntester.py: error: argument --action: invalid choice: \\'debugg\\', maybe you meant \\'debug\\'? (choose from debug, dryrun)\\n\\nYou can disable suggestions by setting suggest_on_error to False.\\n\\nAdded in version 3.14.\\n\\nChanged in version 3.15: Changed default value of suggest_on_error from False to True.\\n\\ncolor¶\\n\\nBy default, the help message is printed in color using ANSI escape sequences. If you want plain text help messages, you can disable this in your local environment, or in the argument parser itself by setting color to False:\\n\\n>>> parser = argparse.ArgumentParser(description=\\'Process some integers.\\',\\n... color=False)\\n>>> parser.add_argument(\\'--action\\', choices=[\\'sum\\', \\'max\\'])\\n>>> parser.add_argument(\\'integers\\', metavar=\\'N\\', type=int, nargs=\\'+\\',\\n... help=\\'an integer for the accumulator\\')\\n>>> parser.parse_args([\\'--help\\'])\\n\\nNote that when color=True, colored output depends on both environment variables and terminal capabilities. However, if color=False, colored output is always disabled, even if environment variables like FORCE_COLOR are set.\\n\\nAdded in version 3.14.\\n\\nTo highlight inline code in your description or epilog text, you can use backticks:\\n\\n>>> parser = argparse.ArgumentParser(\\n... formatter_class=argparse.RawDescriptionHelpFormatter,\\n... epilog=\\'\\'\\'Examples:\\n... `python -m myapp --verbose`\\n... `python -m myapp --config settings.json`\\n... \\'\\'\\')\\n\\nWhen colors are enabled, the text inside backticks will be displayed in a distinct color to help examples stand out. When colors are disabled, backticks are preserved as-is, which is readable in plain text.\\n\\nNote\\n\\nBacktick markup only applies to description and epilog text. It does not apply to individual argument help strings.\\n\\nAdded in version 3.15.\\n\\nThe add_argument() method¶\\n\\nThe following sections describe how each of these are used.\\n\\nname or flags¶\\n\\nThe add_argument() method must know whether an optional argument, like -f or --foo, or a positional argument, like a list of filenames, is expected. The first arguments passed to add_argument() must therefore be either a series of flags, or a simple argument name.\\n\\nFor example, an optional argument could be created like:\\n\\n>>> parser.add_argument(\\'-f\\', \\'--foo\\')\\n\\nwhile a positional argument could be created like:\\n\\n>>> parser.add_argument(\\'bar\\')\\n\\nWhen parse_args() is called, optional arguments will be identified by the - prefix, and the remaining arguments will be assumed to be positional:\\n\\n>>> parser = argparse.ArgumentParser(prog=\\'PROG\\')\\n>>> parser.add_argument(\\'-f\\', \\'--foo\\')\\n>>> parser.add_argument(\\'bar\\')\\n>>> parser.parse_args([\\'BAR\\'])\\nNamespace(bar=\\'BAR\\', foo=None)\\n>>> parser.parse_args([\\'BAR\\', \\'--foo\\', \\'FOO\\'])\\nNamespace(bar=\\'BAR\\', foo=\\'FOO\\')\\n>>> parser.parse_args([\\'--foo\\', \\'FOO\\'])\\nusage: PROG [-h] [-f FOO] bar\\nPROG: error: the following arguments are required: bar\\n\\nBy default, 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 dest and metavar parameters. For optional arguments, the dest parameter defaults to the argument name, with underscores _ replacing hyphens -. The metavar parameter defaults to the upper-cased name. For example:\\n\\n>>> parser = argparse.ArgumentParser(prog=\\'PROG\\')\\n>>> parser.add_argument(\\'--foo-bar\\')\\n>>> parser.parse_args([\\'--foo-bar\\', \\'FOO-BAR\\'])\\nNamespace(foo_bar=\\'FOO-BAR\\')\\n>>> parser.print_help()\\nusage: [-h] [--foo-bar FOO-BAR]\\n\\noptional arguments:\\n -h, --help show this help message and exit\\n --foo-bar FOO-BAR\\n\\naction¶\\n\\nArgumentParser objects associate command-line arguments with actions. These actions can do just about anything with the command-line arguments associated with them, though most actions simply add an attribute to the object returned by parse_args(). The action keyword argument specifies how the command-line arguments should be handled. The supplied actions are:\\n\\n\\'store\\' - This just stores the argument’s value. This is the default action.\\n\\n\\'store_const\\' - This stores the value specified by the const keyword argument; note that the const keyword argument defaults to None. The \\'store_const\\' action is most commonly used with optional arguments that specify some sort of flag. For example:\\n\\n>>> parser = argparse.ArgumentParser()\\n>>> parser.add_argument(\\'--foo\\', action=\\'store_const\\', const=42)\\n>>> parser.parse_args([\\'--foo\\'])\\nNamespace(foo=42)\\n\\n\\'store_true\\' and \\'store_false\\' - These are special cases of \\'store_const\\' that respectively store the values True and False with default values of False and True:\\n\\n>>> parser = argparse.ArgumentParser()\\n>>> parser.add_argument(\\'--foo\\', action=\\'store_true\\')\\n>>> parser.add_argument(\\'--bar\\', action=\\'store_false\\')\\n>>> parser.add_argument(\\'--baz\\', action=\\'store_false\\')\\n>>> parser.parse_args(\\'--foo --bar\\'.split())\\nNamespace(foo=True, bar=False, baz=True)\\n\\n\\'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:\\n\\n>>> parser = argparse.ArgumentParser()\\n>>> parser.add_argument(\\'--foo\\', action=\\'append\\', default=[\\'0\\'])\\n>>> parser.parse_args(\\'--foo 1 --foo 2\\'.split())\\nNamespace(foo=[\\'0\\', \\'1\\', \\'2\\'])\\n\\n\\'append_const\\' - This appends the value specified by the const keyword argument to a list; note that the const keyword argument defaults to None. The \\'append_const\\' action is typically useful when multiple arguments need to store constants to the same list. For example:\\n\\n>>> parser = argparse.ArgumentParser()\\n>>> parser.add_argument(\\'--str\\', dest=\\'types\\', action=\\'append_const\\', const=str)\\n>>> parser.add_argument(\\'--int\\', dest=\\'types\\', action=\\'append_const\\', const=int)\\n>>> parser.parse_args(\\'--str --int\\'.split())\\nNamespace(types=[, ])\\n\\n\\'extend\\' - This appends each item from a multi-value argument to a list. The \\'extend\\' action is typically used with the nargs keyword argument value \\'+\\' or \\'*\\'. Note that when nargs is None (the default) or \\'?\\', each character of the argument string will be appended to the list. Example usage:\\n\\n>>> parser = argparse.ArgumentParser()\\n>>> parser.add_argument(\"--foo\", action=\"extend\", nargs=\"+\", type=str)\\n>>> parser.parse_args([\"--foo\", \"f1\", \"--foo\", \"f2\", \"f3\", \"f4\"])\\nNamespace(foo=[\\'f1\\', \\'f2\\', \\'f3\\', \\'f4\\'])\\n\\nAdded in version 3.8.\\n\\n\\'count\\' - This counts the number of times an argument occurs. For example, this is useful for increasing verbosity levels:\\n\\n>>> parser = argparse.ArgumentParser()\\n>>> parser.add_argument(\\'--verbose\\', \\'-v\\', action=\\'count\\', default=0)\\n>>> parser.parse_args([\\'-vvv\\'])\\nNamespace(verbose=3)\\n\\nNote, the default will be None unless explicitly set to 0.\\n\\n\\'help\\' - This prints a complete help message for all the options in the current parser and then exits. By default a help action is automatically added to the parser. See ArgumentParser for details of how the output is created.\\n\\n\\'version\\' - This expects a version= keyword argument in the add_argument() call, and prints version information and exits when invoked:\\n\\n>>> import argparse\\n>>> parser = argparse.ArgumentParser(prog=\\'PROG\\')\\n>>> parser.add_argument(\\'--version\\', action=\\'version\\', version=\\'%(prog)s 2.0\\')\\n>>> parser.parse_args([\\'--version\\'])\\nPROG 2.0\\n\\nYou may also specify an arbitrary action by passing an Action subclass (e.g. BooleanOptionalAction) or other object that implements the same interface. Only actions that consume command-line arguments (e.g. \\'store\\', \\'append\\', \\'extend\\', or custom actions with non-zero nargs) can be used with positional arguments.\\n\\nThe recommended way to create a custom action is to extend Action, overriding the __call__() method and optionally the __init__() and format_usage() methods. You can also register custom actions using the register() method and reference them by their registered name.\\n\\nAn example of a custom action:\\n\\n>>> class FooAction(argparse.Action):\\n... def __init__(self, option_strings, dest, nargs=None, **kwargs):\\n... if nargs is not None:\\n... raise ValueError(\"nargs not allowed\")\\n... super().__init__(option_strings, dest, **kwargs)\\n... def __call__(self, parser, namespace, values, option_string=None):\\n... print(\\'%r %r %r\\' % (namespace, values, option_string))\\n... setattr(namespace, self.dest, values)\\n...\\n>>> parser = argparse.ArgumentParser()\\n>>> parser.add_argument(\\'--foo\\', action=FooAction)\\n>>> parser.add_argument(\\'bar\\', action=FooAction)\\n>>> args = parser.parse_args(\\'1 --foo 2\\'.split())\\nNamespace(bar=None, foo=None) \\'1\\' None\\nNamespace(bar=\\'1\\', foo=None) \\'2\\' \\'--foo\\'\\n>>> args\\nNamespace(bar=\\'1\\', foo=\\'2\\')\\n\\nFor more details, see Action.\\n\\nnargs¶\\n\\nArgumentParser objects usually associate a single command-line argument with a single action to be taken. The nargs keyword argument associates a different number of command-line arguments with a single action. See also Specifying ambiguous arguments. The supported values are:\\n\\nN (an integer). N arguments from the command line will be gathered together into a list. For example:\\n\\n>>> parser = argparse.ArgumentParser()\\n>>> parser.add_argument(\\'--foo\\', nargs=2)\\n>>> parser.add_argument(\\'bar\\', nargs=1)\\n>>> parser.parse_args(\\'c --foo a b\\'.split())\\nNamespace(bar=[\\'c\\'], foo=[\\'a\\', \\'b\\'])\\n\\nNote that nargs=1 produces a list of one item. This is different from the default, in which the item is produced by itself.\\n\\n\\'?\\'. One argument will be consumed from the command line if possible, and produced as a single item. If no command-line argument is present, the value from default will be produced. Note that for optional arguments, there is an additional case - the option string is present but not followed by a command-line argument. In this case the value from const will be produced. Some examples to illustrate this:\\n\\n>>> parser = argparse.ArgumentParser()\\n>>> parser.add_argument(\\'--foo\\', nargs=\\'?\\', const=\\'c\\', default=\\'d\\')\\n>>> parser.add_argument(\\'bar\\', nargs=\\'?\\', default=\\'d\\')\\n>>> parser.parse_args([\\'XX\\', \\'--foo\\', \\'YY\\'])\\nNamespace(bar=\\'XX\\', foo=\\'YY\\')\\n>>> parser.parse_args([\\'XX\\', \\'--foo\\'])\\nNamespace(bar=\\'XX\\', foo=\\'c\\')\\n>>> parser.parse_args([])\\nNamespace(bar=\\'d\\', foo=\\'d\\')\\n\\nOne of the more common uses of nargs=\\'?\\' is to allow optional input and output files:\\n\\n>>> parser = argparse.ArgumentParser()\\n>>> parser.add_argument(\\'infile\\', nargs=\\'?\\')\\n>>> parser.add_argument(\\'outfile\\', nargs=\\'?\\')\\n>>> parser.parse_args([\\'input.txt\\', \\'output.txt\\'])\\nNamespace(infile=\\'input.txt\\', outfile=\\'output.txt\\')\\n>>> parser.parse_args([\\'input.txt\\'])\\nNamespace(infile=\\'input.txt\\', outfile=None)\\n>>> parser.parse_args([])\\nNamespace(infile=None, outfile=None)\\n\\n\\'*\\'. All command-line arguments present are gathered into a list. Note that it generally doesn’t make much sense to have more than one positional argument with nargs=\\'*\\', but multiple optional arguments with nargs=\\'*\\' is possible. For example:\\n\\n>>> parser = argparse.ArgumentParser()\\n>>> parser.add_argument(\\'--foo\\', nargs=\\'*\\')\\n>>> parser.add_argument(\\'--bar\\', nargs=\\'*\\')\\n>>> parser.add_argument(\\'baz\\', nargs=\\'*\\')\\n>>> parser.parse_args(\\'a b --foo x y --bar 1 2\\'.split())\\nNamespace(bar=[\\'1\\', \\'2\\'], baz=[\\'a\\', \\'b\\'], foo=[\\'x\\', \\'y\\'])\\n\\n\\'+\\'. Just like \\'*\\', 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:\\n\\n>>> parser = argparse.ArgumentParser(prog=\\'PROG\\')\\n>>> parser.add_argument(\\'foo\\', nargs=\\'+\\')\\n>>> parser.parse_args([\\'a\\', \\'b\\'])\\nNamespace(foo=[\\'a\\', \\'b\\'])\\n>>> parser.parse_args([])\\nusage: PROG [-h] foo [foo ...]\\nPROG: error: the following arguments are required: foo\\n\\nIf the nargs keyword argument is not provided, the number of arguments consumed is determined by the 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. \\'store_const\\') set nargs=0.\\n\\nconst¶\\n\\nThe const argument of add_argument() is used to hold constant values that are not read from the command line but are required for the various ArgumentParser actions. The two most common uses of it are:\\n\\nWhen add_argument() is called with action=\\'store_const\\' or action=\\'append_const\\'. These actions add the const value to one of the attributes of the object returned by parse_args(). See the action description for examples. If const is not provided to add_argument(), it will receive a default value of None.\\n\\nWhen add_argument() is called with option strings (like -f or --foo) and 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 const will be used. See the nargs description for examples.\\n\\nChanged in version 3.11: const=None by default, including when action=\\'append_const\\' or action=\\'store_const\\'.\\n\\ndefault¶\\n\\nAll optional arguments and some positional arguments may be omitted at the command line. The default keyword argument of add_argument(), whose value defaults to None, specifies what value should be used if the command-line argument is not present. For optional arguments, the default value is used when the option string was not present at the command line:\\n\\n>>> parser = argparse.ArgumentParser()\\n>>> parser.add_argument(\\'--foo\\', default=42)\\n>>> parser.parse_args([\\'--foo\\', \\'2\\'])\\nNamespace(foo=\\'2\\')\\n>>> parser.parse_args([])\\nNamespace(foo=42)\\n\\nIf the target namespace already has an attribute set, the action default will not overwrite it:\\n\\n>>> parser = argparse.ArgumentParser()\\n>>> parser.add_argument(\\'--foo\\', default=42)\\n>>> parser.parse_args([], namespace=argparse.Namespace(foo=101))\\nNamespace(foo=101)\\n\\nIf the default value is a string, the parser parses the value as if it were a command-line argument. In particular, the parser applies any type conversion argument, if provided, before setting the attribute on the Namespace return value. Otherwise, the parser uses the value as is:\\n\\n>>> parser = argparse.ArgumentParser()\\n>>> parser.add_argument(\\'--length\\', default=\\'10\\', type=int)\\n>>> parser.add_argument(\\'--width\\', default=10.5, type=int)\\n>>> parser.parse_args()\\nNamespace(length=10, width=10.5)\\n\\nFor positional arguments with nargs equal to ? or *, the default value is used when no command-line argument was present:\\n\\n>>> parser = argparse.ArgumentParser()\\n>>> parser.add_argument(\\'foo\\', nargs=\\'?\\', default=42)\\n>>> parser.parse_args([\\'a\\'])\\nNamespace(foo=\\'a\\')\\n>>> parser.parse_args([])\\nNamespace(foo=42)\\n\\nFor required arguments, the default value is ignored. For example, this applies to positional arguments with nargs values other than ? or *, or optional arguments marked as required=True.\\n\\nProviding default=argparse.SUPPRESS causes no attribute to be added if the command-line argument was not present:\\n\\n>>> parser = argparse.ArgumentParser()\\n>>> parser.add_argument(\\'--foo\\', default=argparse.SUPPRESS)\\n>>> parser.parse_args([])\\nNamespace()\\n>>> parser.parse_args([\\'--foo\\', \\'1\\'])\\nNamespace(foo=\\'1\\')\\n\\ntype¶\\n\\nBy default, the parser reads command-line arguments in as simple strings. However, quite often the command-line string should instead be interpreted as another type, such as a float or int. The type keyword for add_argument() allows any necessary type-checking and type conversions to be performed.\\n\\nIf the type keyword is used with the default keyword, the type converter is only applied if the default is a string.\\n\\nThe argument to type can be a callable that accepts a single string or the name of a registered type (see register()) If the function raises ArgumentTypeError, TypeError, or ValueError, the exception is caught and a nicely formatted error message is displayed. Other exception types are not handled.\\n\\nCommon built-in types and functions can be used as type converters:\\n\\nimport argparse\\nimport pathlib\\n\\nparser = argparse.ArgumentParser()\\nparser.add_argument(\\'count\\', type=int)\\nparser.add_argument(\\'distance\\', type=float)\\nparser.add_argument(\\'street\\', type=ascii)\\nparser.add_argument(\\'code_point\\', type=ord)\\nparser.add_argument(\\'datapath\\', type=pathlib.Path)\\n\\nUser defined functions can be used as well:\\n\\n>>> def hyphenated(string):\\n... return \\'-\\'.join([word[:4] for word in string.casefold().split()])\\n...\\n>>> parser = argparse.ArgumentParser()\\n>>> _ = parser.add_argument(\\'short_title\\', type=hyphenated)\\n>>> parser.parse_args([\\'\"The Tale of Two Cities\"\\'])\\nNamespace(short_title=\\'\"the-tale-of-two-citi\\')\\n\\nThe bool() function is not recommended as a type converter. All it does is convert empty strings to False and non-empty strings to True. This is usually not what is desired.\\n\\nIn general, the type keyword is a convenience that should only be used for simple conversions that can only raise one of the three supported exceptions. Anything with more interesting error-handling or resource management should be done downstream after the arguments are parsed.\\n\\nFor example, JSON or YAML conversions have complex error cases that require better reporting than can be given by the type keyword. A JSONDecodeError would not be well formatted and a FileNotFoundError exception would not be handled at all.\\n\\nEven FileType has its limitations for use with the type keyword. If one argument uses 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 with-statement to manage the files.\\n\\nFor type checkers that simply check against a fixed set of values, consider using the choices keyword instead.\\n\\nchoices¶\\n\\nSome command-line arguments should be selected from a restricted set of values. These can be handled by passing a sequence object as the choices keyword argument to add_argument(). When the command line is parsed, argument values will be checked, and an error message will be displayed if the argument was not one of the acceptable values:\\n\\n>>> parser = argparse.ArgumentParser(prog=\\'game.py\\')\\n>>> parser.add_argument(\\'move\\', choices=[\\'rock\\', \\'paper\\', \\'scissors\\'])\\n>>> parser.parse_args([\\'rock\\'])\\nNamespace(move=\\'rock\\')\\n>>> parser.parse_args([\\'fire\\'])\\nusage: game.py [-h] {rock,paper,scissors}\\ngame.py: error: argument move: invalid choice: \\'fire\\' (choose from \\'rock\\',\\n\\'paper\\', \\'scissors\\')\\n\\nAny sequence can be passed as the choices value, so list objects, tuple objects, and custom sequences are all supported.\\n\\nUse of enum.Enum is not recommended because it is difficult to control its appearance in usage, help, and error messages.\\n\\nNote that choices are checked after any type conversions have been performed, so objects in choices should match the type specified. This can make choices appear unfamiliar in usage, help, or error messages.\\n\\nTo keep choices user-friendly, consider a custom type wrapper that converts and formats values, or omit type and handle conversion in your application code.\\n\\nFormatted choices override the default metavar which is normally derived from dest. This is usually what you want because the user never sees the dest parameter. If this display isn’t desirable (perhaps because there are many choices), just specify an explicit metavar.\\n\\nrequired¶\\n\\nIn general, the argparse module assumes that flags like -f and --bar indicate optional arguments, which can always be omitted at the command line. To make an option required, True can be specified for the required= keyword argument to add_argument():\\n\\n>>> parser = argparse.ArgumentParser()\\n>>> parser.add_argument(\\'--foo\\', required=True)\\n>>> parser.parse_args([\\'--foo\\', \\'BAR\\'])\\nNamespace(foo=\\'BAR\\')\\n>>> parser.parse_args([])\\nusage: [-h] --foo FOO\\n: error: the following arguments are required: --foo\\n\\nAs the example shows, if an option is marked as required, parse_args() will report an error if that option is not present at the command line.\\n\\nNote\\n\\nRequired options are generally considered bad form because users expect options to be optional, and thus they should be avoided when possible.\\n\\nhelp¶\\n\\nThe help value is a string containing a brief description of the argument. When a user requests help (usually by using -h or --help at the command line), these help descriptions will be displayed with each argument.\\n\\nThe help strings can include various format specifiers to avoid repetition of things like the program name or the argument default. The available specifiers include the program name, %(prog)s and most keyword arguments to add_argument(), e.g. %(default)s, %(type)s, etc.:\\n\\n>>> parser = argparse.ArgumentParser(prog=\\'frobble\\')\\n>>> parser.add_argument(\\'bar\\', nargs=\\'?\\', type=int, default=42,\\n... help=\\'the bar to %(prog)s (default: %(default)s)\\')\\n>>> parser.print_help()\\nusage: frobble [-h] [bar]\\n\\npositional arguments:\\n bar the bar to frobble (default: 42)\\n\\noptions:\\n -h, --help show this help message and exit\\n\\nAs the help string supports %-formatting, if you want a literal % to appear in the help string, you must escape it as %%.\\n\\nargparse supports silencing the help entry for certain options, by setting the help value to argparse.SUPPRESS:\\n\\n>>> parser = argparse.ArgumentParser(prog=\\'frobble\\')\\n>>> parser.add_argument(\\'--foo\\', help=argparse.SUPPRESS)\\n>>> parser.print_help()\\nusage: frobble [-h]\\n\\noptions:\\n -h, --help show this help message and exit\\n\\nmetavar¶\\n\\nWhen ArgumentParser generates help messages, it needs some way to refer to each expected argument. By default, ArgumentParser objects use the dest value as the “name” of each object. By default, for positional argument actions, the dest value is used directly, and for optional argument actions, the dest value is uppercased. So, a single positional argument with dest=\\'bar\\' will be referred to as bar. A single optional argument --foo that should be followed by a single command-line argument will be referred to as FOO. An example:\\n\\n>>> parser = argparse.ArgumentParser()\\n>>> parser.add_argument(\\'--foo\\')\\n>>> parser.add_argument(\\'bar\\')\\n>>> parser.parse_args(\\'X --foo Y\\'.split())\\nNamespace(bar=\\'X\\', foo=\\'Y\\')\\n>>> parser.print_help()\\nusage: [-h] [--foo FOO] bar\\n\\npositional arguments:\\n bar\\n\\noptions:\\n -h, --help show this help message and exit\\n --foo FOO\\n\\nAn alternative name can be specified with metavar:\\n\\n>>> parser = argparse.ArgumentParser()\\n>>> parser.add_argument(\\'--foo\\', metavar=\\'YYY\\')\\n>>> parser.add_argument(\\'bar\\', metavar=\\'XXX\\')\\n>>> parser.parse_args(\\'X --foo Y\\'.split())\\nNamespace(bar=\\'X\\', foo=\\'Y\\')\\n>>> parser.print_help()\\nusage: [-h] [--foo YYY] XXX\\n\\npositional arguments:\\n XXX\\n\\noptions:\\n -h, --help show this help message and exit\\n --foo YYY\\n\\nNote that metavar only changes the displayed name - the name of the attribute on the parse_args() object is still determined by the dest value.\\n\\nDifferent values of nargs may cause the metavar to be used multiple times. Providing a tuple to metavar specifies a different display for each of the arguments:\\n\\n>>> parser = argparse.ArgumentParser(prog=\\'PROG\\')\\n>>> parser.add_argument(\\'-x\\', nargs=2)\\n>>> parser.add_argument(\\'--foo\\', nargs=2, metavar=(\\'bar\\', \\'baz\\'))\\n>>> parser.print_help()\\nusage: PROG [-h] [-x X X] [--foo bar baz]\\n\\noptions:\\n -h, --help show this help message and exit\\n -x X X\\n --foo bar baz\\n\\ndest¶\\n\\nMost ArgumentParser actions add some value as an attribute of the object returned by parse_args(). The name of this attribute is determined by the dest keyword argument of add_argument(). For positional argument actions, dest is normally supplied as the first argument to add_argument():\\n\\n>>> parser = argparse.ArgumentParser()\\n>>> parser.add_argument(\\'bar\\')\\n>>> parser.parse_args([\\'XXX\\'])\\nNamespace(bar=\\'XXX\\')\\n\\nFor optional argument actions, the value of dest is normally inferred from the option strings. ArgumentParser generates the value of dest by taking the first double-dash long option string and stripping away the initial - characters. If no double-dash long option strings were supplied, dest will be derived from the first single-dash long option string by stripping the initial - character. If no long option strings were supplied, dest will be derived from the first short option string by stripping the initial - character. Any internal - characters will be converted to _ characters to make sure the string is a valid attribute name. The examples below illustrate this behavior:\\n\\n>>> parser = argparse.ArgumentParser()\\n>>> parser.add_argument(\\'-f\\', \\'--foo-bar\\', \\'--foo\\')\\n>>> parser.add_argument(\\'-q\\', \\'-quz\\')\\n>>> parser.add_argument(\\'-x\\', \\'-y\\')\\n>>> parser.parse_args(\\'-f 1 -q 2 -x 3\\'.split())\\nNamespace(foo_bar=\\'1\\', quz=\\'2\\', x=\\'3\\')\\n>>> parser.parse_args(\\'--foo 1 -quz 2 -y 3\\'.split())\\nNamespace(foo_bar=\\'1\\', quz=\\'2\\', x=\\'2\\')\\n\\ndest allows a custom attribute name to be provided:\\n\\n>>> parser = argparse.ArgumentParser()\\n>>> parser.add_argument(\\'--foo\\', dest=\\'bar\\')\\n>>> parser.parse_args(\\'--foo XXX\\'.split())\\nNamespace(bar=\\'XXX\\')\\n\\nChanged in version 3.15: Single-dash long option now takes precedence over short options.\\n\\ndeprecated¶\\n\\nDuring 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 deprecated keyword argument of add_argument(), which defaults to False, specifies if the argument is deprecated and will be removed in the future. For arguments, if deprecated is True, then a warning will be printed to sys.stderr when the argument is used:\\n\\n>>> import argparse\\n>>> parser = argparse.ArgumentParser(prog=\\'snake.py\\')\\n>>> parser.add_argument(\\'--legs\\', default=0, type=int, deprecated=True)\\n>>> parser.parse_args([])\\nNamespace(legs=0)\\n>>> parser.parse_args([\\'--legs\\', \\'4\\'])\\nsnake.py: warning: option \\'--legs\\' is deprecated\\nNamespace(legs=4)\\n\\nAdded in version 3.13.\\n\\nAction classes¶\\n\\nAction 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 action parameter to add_argument().\\n\\nThe parse_args() method¶\\n\\nOption value syntax¶\\n\\nThe parse_args() method supports several ways of specifying the value of an option (if it takes one). In the simplest case, the option and its value are passed as two separate arguments:\\n\\n>>> parser = argparse.ArgumentParser(prog=\\'PROG\\')\\n>>> parser.add_argument(\\'-x\\')\\n>>> parser.add_argument(\\'--foo\\')\\n>>> parser.parse_args([\\'-x\\', \\'X\\'])\\nNamespace(foo=None, x=\\'X\\')\\n>>> parser.parse_args([\\'--foo\\', \\'FOO\\'])\\nNamespace(foo=\\'FOO\\', x=None)\\n\\nFor long options (options with names longer than a single character), the option and value can also be passed as a single command-line argument, using = to separate them:\\n\\n>>> parser.parse_args([\\'--foo=FOO\\'])\\nNamespace(foo=\\'FOO\\', x=None)\\n\\nFor short options (options only one character long), the option and its value can be concatenated:\\n\\n>>> parser.parse_args([\\'-xX\\'])\\nNamespace(foo=None, x=\\'X\\')\\n\\nSeveral short options can be joined together, using only a single - prefix, as long as only the last option (or none of them) requires a value:\\n\\n>>> parser = argparse.ArgumentParser(prog=\\'PROG\\')\\n>>> parser.add_argument(\\'-x\\', action=\\'store_true\\')\\n>>> parser.add_argument(\\'-y\\', action=\\'store_true\\')\\n>>> parser.add_argument(\\'-z\\')\\n>>> parser.parse_args([\\'-xyzZ\\'])\\nNamespace(x=True, y=True, z=\\'Z\\')\\n\\nInvalid arguments¶\\n\\nWhile parsing the command line, parse_args() checks for a variety of errors, including ambiguous options, invalid types, invalid options, wrong number of positional arguments, etc. When it encounters such an error, it exits and prints the error along with a usage message:\\n\\n>>> parser = argparse.ArgumentParser(prog=\\'PROG\\')\\n>>> parser.add_argument(\\'--foo\\', type=int)\\n>>> parser.add_argument(\\'bar\\', nargs=\\'?\\')\\n\\n>>> # invalid type\\n>>> parser.parse_args([\\'--foo\\', \\'spam\\'])\\nusage: PROG [-h] [--foo FOO] [bar]\\nPROG: error: argument --foo: invalid int value: \\'spam\\'\\n\\n>>> # invalid option\\n>>> parser.parse_args([\\'--bar\\'])\\nusage: PROG [-h] [--foo FOO] [bar]\\nPROG: error: no such option: --bar\\n\\n>>> # wrong number of arguments\\n>>> parser.parse_args([\\'spam\\', \\'badger\\'])\\nusage: PROG [-h] [--foo FOO] [bar]\\nPROG: error: extra arguments found: badger\\n\\nArguments containing -¶\\n\\nThe parse_args() method attempts to give errors whenever the user has clearly made a mistake, but some situations are inherently ambiguous. For example, the command-line argument -1 could either be an attempt to specify an option or an attempt to provide a positional argument. The parse_args() method is cautious here: positional arguments may only begin with - if they look like negative numbers and there are no options in the parser that look like negative numbers:\\n\\n>>> parser = argparse.ArgumentParser(prog=\\'PROG\\')\\n>>> parser.add_argument(\\'-x\\')\\n>>> parser.add_argument(\\'foo\\', nargs=\\'?\\')\\n\\n>>> # no negative number options, so -1 is a positional argument\\n>>> parser.parse_args([\\'-x\\', \\'-1\\'])\\nNamespace(foo=None, x=\\'-1\\')\\n\\n>>> # no negative number options, so -1 and -5 are positional arguments\\n>>> parser.parse_args([\\'-x\\', \\'-1\\', \\'-5\\'])\\nNamespace(foo=\\'-5\\', x=\\'-1\\')\\n\\n>>> parser = argparse.ArgumentParser(prog=\\'PROG\\')\\n>>> parser.add_argument(\\'-1\\', dest=\\'one\\')\\n>>> parser.add_argument(\\'foo\\', nargs=\\'?\\')\\n\\n>>> # negative number options present, so -1 is an option\\n>>> parser.parse_args([\\'-1\\', \\'X\\'])\\nNamespace(foo=None, one=\\'X\\')\\n\\n>>> # negative number options present, so -2 is an option\\n>>> parser.parse_args([\\'-2\\'])\\nusage: PROG [-h] [-1 ONE] [foo]\\nPROG: error: no such option: -2\\n\\n>>> # negative number options present, so both -1s are options\\n>>> parser.parse_args([\\'-1\\', \\'-1\\'])\\nusage: PROG [-h] [-1 ONE] [foo]\\nPROG: error: argument -1: expected one argument\\n\\nIf you have positional arguments that must begin with - and don’t look like negative numbers, you can insert the pseudo-argument \\'--\\' which tells parse_args() that everything after that is a positional argument:\\n\\n>>> parser.parse_args([\\'--\\', \\'-f\\'])\\nNamespace(foo=\\'-f\\', one=None)\\n\\nSee also the argparse howto on ambiguous arguments for more details.\\n\\nArgument abbreviations (prefix matching)¶\\n\\nThe parse_args() method by default allows long options to be abbreviated to a prefix, if the abbreviation is unambiguous (the prefix matches a unique option):\\n\\n>>> parser = argparse.ArgumentParser(prog=\\'PROG\\')\\n>>> parser.add_argument(\\'-bacon\\')\\n>>> parser.add_argument(\\'-badger\\')\\n>>> parser.parse_args(\\'-bac MMM\\'.split())\\nNamespace(bacon=\\'MMM\\', badger=None)\\n>>> parser.parse_args(\\'-bad WOOD\\'.split())\\nNamespace(bacon=None, badger=\\'WOOD\\')\\n>>> parser.parse_args(\\'-ba BA\\'.split())\\nusage: PROG [-h] [-bacon BACON] [-badger BADGER]\\nPROG: error: ambiguous option: -ba could match -badger, -bacon\\n\\nAn error is produced for arguments that could produce more than one options. This feature can be disabled by setting allow_abbrev to False.\\n\\nBeyond sys.argv¶\\n\\nSometimes it may be useful to have an ArgumentParser parse arguments other than those of sys.argv. This can be accomplished by passing a list of strings to parse_args(). This is useful for testing at the interactive prompt:\\n\\n>>> parser = argparse.ArgumentParser()\\n>>> parser.add_argument(\\n... \\'integers\\', metavar=\\'int\\', type=int, choices=range(10),\\n... nargs=\\'+\\', help=\\'an integer in the range 0..9\\')\\n>>> parser.add_argument(\\n... \\'--sum\\', dest=\\'accumulate\\', action=\\'store_const\\', const=sum,\\n... default=max, help=\\'sum the integers (default: find the max)\\')\\n>>> parser.parse_args([\\'1\\', \\'2\\', \\'3\\', \\'4\\'])\\nNamespace(accumulate=, integers=[1, 2, 3, 4])\\n>>> parser.parse_args([\\'1\\', \\'2\\', \\'3\\', \\'4\\', \\'--sum\\'])\\nNamespace(accumulate=, integers=[1, 2, 3, 4])\\n\\nThe Namespace object¶\\n\\nOther utilities¶\\n\\nSubcommands¶\\n\\nFileType objects¶\\n\\nArgument groups¶\\n\\nMutual exclusion¶\\n\\nParser defaults¶\\n\\nPrinting help¶\\n\\nIn most typical applications, parse_args() will take care of formatting and printing any usage or error messages. However, several formatting methods are available:\\n\\nThere are also variants of these methods that simply return a string instead of printing it:\\n\\nPartial parsing¶\\n\\nWarning\\n\\nPrefix matching rules apply to parse_known_args(). The parser may consume an option even if it’s just a prefix of one of its known options, instead of leaving it in the remaining arguments list.\\n\\nCustomizing file parsing¶\\n\\nExiting methods¶\\n\\nIntermixed parsing¶\\n\\nRegistering custom types or actions¶\\n\\nExceptions¶\\n\\nGuides and Tutorials\\n\\nArgparse Tutorial\\n\\nMigrating optparse code to argparse\\n\\nTable of Contents\\n\\nargparse — Parser for command-line options, arguments and subcommands\\n\\nArgumentParser objects\\n\\nprog\\n\\nusage\\n\\ndescription\\n\\nepilog\\n\\nparents\\n\\nformatter_class\\n\\nprefix_chars\\n\\nfromfile_prefix_chars\\n\\nargument_default\\n\\nallow_abbrev\\n\\nconflict_handler\\n\\nadd_help\\n\\nexit_on_error\\n\\nsuggest_on_error\\n\\ncolor\\n\\nThe add_argument() method\\n\\nname or flags\\n\\naction\\n\\nnargs\\n\\nconst\\n\\ndefault\\n\\ntype\\n\\nchoices\\n\\nrequired\\n\\nhelp\\n\\nmetavar\\n\\ndest\\n\\ndeprecated\\n\\nAction classes\\n\\nThe parse_args() method\\n\\nOption value syntax\\n\\nInvalid arguments\\n\\nArguments containing -\\n\\nArgument abbreviations (prefix matching)\\n\\nBeyond sys.argv\\n\\nThe Namespace object\\n\\nOther utilities\\n\\nSubcommands\\n\\nFileType objects\\n\\nArgument groups\\n\\nMutual exclusion\\n\\nParser defaults\\n\\nPrinting help\\n\\nPartial parsing\\n\\nCustomizing file parsing\\n\\nExiting methods\\n\\nIntermixed parsing\\n\\nRegistering custom types or actions\\n\\nExceptions\\n\\nPrevious topic\\n\\nCommand-line interface libraries\\n\\nNext topic\\n\\nArgparse Tutorial\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nCommand-line interface libraries »\\n\\nargparse — Parser for command-line options, arguments and subcommands\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\array.html'}, page_content=\"Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Types »\\n\\narray — Efficient arrays of numeric values\\n\\n|\\n\\narray — Efficient arrays of numeric values¶\\n\\nThis module defines an object type which can compactly represent an array of basic values: characters, integers, floating-point numbers. Arrays are mutable 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:\\n\\nType code C Type Python Type Minimum size in bytes Notes 'b' signed char int 1 'B' unsigned char int 1 'u' wchar_t Unicode character 2 (1) 'w' Py_UCS4 Unicode character 4 (2) 'h' signed short int 2 'H' unsigned short int 2 'i' signed int int 2 'I' unsigned int int 2 'l' signed long int 4 'L' unsigned long int 4 'q' signed long long int 8 'Q' unsigned long long int 8 'f' float float 4 'd' double float 8\\n\\nNotes:\\n\\nIt can be 16 bits or 32 bits depending on the platform.\\n\\nChanged in version 3.9: array('u') now uses wchar_t as C type instead of deprecated Py_UNICODE. This change doesn’t affect its behavior because Py_UNICODE is alias of wchar_t since Python 3.3.\\n\\nDeprecated since version 3.3, will be removed in version 3.16: Please migrate to 'w' typecode.\\n\\nAdded in version 3.13.\\n\\nThe actual representation of values is determined by the machine architecture (strictly speaking, by the C implementation). The actual size can be accessed through the array.itemsize attribute.\\n\\nThe module defines the following item:\\n\\nThe module defines the following type:\\n\\nThe string representation of array objects has the form array(typecode, initializer). The initializer is omitted if the array is empty, otherwise it is a Unicode string if the typecode is 'u' or '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 eval(), so long as the array class has been imported using from array import array. Variables inf and nan must also be defined if it contains corresponding floating-point values. Examples:\\n\\narray('l')\\narray('w', 'hello \\\\u2641')\\narray('l', [1, 2, 3, 4, 5])\\narray('d', [1.0, 2.0, 3.14, -inf, nan])\\n\\nSee also\\n\\nPrevious topic\\n\\nbisect — Array bisection algorithm\\n\\nNext topic\\n\\nweakref — Weak references\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Types »\\n\\narray — Efficient arrays of numeric values\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.\"), Document(metadata={'source': '..\\\\..\\\\docs\\\\ast.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Language Services »\\n\\nast — Abstract syntax trees\\n\\n|\\n\\nast — Abstract syntax trees¶\\n\\nSource code: Lib/ast.py\\n\\nThe 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.\\n\\nAn abstract syntax tree can be generated by passing ast.PyCF_ONLY_AST as a flag to the compile() built-in function, or using the parse() helper provided in this module. The result will be a tree of objects whose classes all inherit from ast.AST. An abstract syntax tree can be compiled into a Python code object using the built-in compile() function.\\n\\nAbstract grammar¶\\n\\nThe abstract grammar is currently defined as follows:\\n\\n-- ASDL\\'s 4 builtin types are:\\n-- identifier, int, string, constant\\n\\nmodule Python\\n{\\n mod = Module(stmt* body, type_ignore* type_ignores)\\n | Interactive(stmt* body)\\n | Expression(expr body)\\n | FunctionType(expr* argtypes, expr returns)\\n\\n stmt = FunctionDef(identifier name, arguments args,\\n stmt* body, expr* decorator_list, expr? returns,\\n string? type_comment, type_param* type_params)\\n | AsyncFunctionDef(identifier name, arguments args,\\n stmt* body, expr* decorator_list, expr? returns,\\n string? type_comment, type_param* type_params)\\n\\n | ClassDef(identifier name,\\n expr* bases,\\n keyword* keywords,\\n stmt* body,\\n expr* decorator_list,\\n type_param* type_params)\\n | Return(expr? value)\\n\\n | Delete(expr* targets)\\n | Assign(expr* targets, expr value, string? type_comment)\\n | TypeAlias(expr name, type_param* type_params, expr value)\\n | AugAssign(expr target, operator op, expr value)\\n -- \\'simple\\' indicates that we annotate simple name without parens\\n | AnnAssign(expr target, expr annotation, expr? value, int simple)\\n\\n -- use \\'orelse\\' because else is a keyword in target languages\\n | For(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)\\n | AsyncFor(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)\\n | While(expr test, stmt* body, stmt* orelse)\\n | If(expr test, stmt* body, stmt* orelse)\\n | With(withitem* items, stmt* body, string? type_comment)\\n | AsyncWith(withitem* items, stmt* body, string? type_comment)\\n\\n | Match(expr subject, match_case* cases)\\n\\n | Raise(expr? exc, expr? cause)\\n | Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody)\\n | TryStar(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody)\\n | Assert(expr test, expr? msg)\\n\\n | Import(alias* names, int? is_lazy)\\n | ImportFrom(identifier? module, alias* names, int? level, int? is_lazy)\\n\\n | Global(identifier* names)\\n | Nonlocal(identifier* names)\\n | Expr(expr value)\\n | Pass | Break | Continue\\n\\n -- col_offset is the byte offset in the utf8 string the parser uses\\n attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)\\n\\n -- BoolOp() can use left & right?\\n expr = BoolOp(boolop op, expr* values)\\n | NamedExpr(expr target, expr value)\\n | BinOp(expr left, operator op, expr right)\\n | UnaryOp(unaryop op, expr operand)\\n | Lambda(arguments args, expr body)\\n | IfExp(expr test, expr body, expr orelse)\\n | Dict(expr?* keys, expr* values)\\n | Set(expr* elts)\\n | ListComp(expr elt, comprehension* generators)\\n | SetComp(expr elt, comprehension* generators)\\n | DictComp(expr key, expr? value, comprehension* generators)\\n | GeneratorExp(expr elt, comprehension* generators)\\n -- the grammar constrains where yield expressions can occur\\n | Await(expr value)\\n | Yield(expr? value)\\n | YieldFrom(expr value)\\n -- need sequences for compare to distinguish between\\n -- x < 4 < 3 and (x < 4) < 3\\n | Compare(expr left, cmpop* ops, expr* comparators)\\n | Call(expr func, expr* args, keyword* keywords)\\n | FormattedValue(expr value, int conversion, expr? format_spec)\\n | Interpolation(expr value, constant str, int conversion, expr? format_spec)\\n | JoinedStr(expr* values)\\n | TemplateStr(expr* values)\\n | Constant(constant value, string? kind)\\n\\n -- the following expression can appear in assignment context\\n | Attribute(expr value, identifier attr, expr_context ctx)\\n | Subscript(expr value, expr slice, expr_context ctx)\\n | Starred(expr value, expr_context ctx)\\n | Name(identifier id, expr_context ctx)\\n | List(expr* elts, expr_context ctx)\\n | Tuple(expr* elts, expr_context ctx)\\n\\n -- can appear only in Subscript\\n | Slice(expr? lower, expr? upper, expr? step)\\n\\n -- col_offset is the byte offset in the utf8 string the parser uses\\n attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)\\n\\n expr_context = Load | Store | Del\\n\\n boolop = And | Or\\n\\n operator = Add | Sub | Mult | MatMult | Div | Mod | Pow | LShift\\n | RShift | BitOr | BitXor | BitAnd | FloorDiv\\n\\n unaryop = Invert | Not | UAdd | USub\\n\\n cmpop = Eq | NotEq | Lt | LtE | Gt | GtE | Is | IsNot | In | NotIn\\n\\n comprehension = (expr target, expr iter, expr* ifs, int is_async)\\n\\n excepthandler = ExceptHandler(expr? type, identifier? name, stmt* body)\\n attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)\\n\\n arguments = (arg* posonlyargs, arg* args, arg? vararg, arg* kwonlyargs,\\n expr?* kw_defaults, arg? kwarg, expr* defaults)\\n\\n arg = (identifier arg, expr? annotation, string? type_comment)\\n attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)\\n\\n -- keyword arguments supplied to call (NULL identifier for **kwargs)\\n keyword = (identifier? arg, expr value)\\n attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)\\n\\n -- import name with optional \\'as\\' alias.\\n alias = (identifier name, identifier? asname)\\n attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)\\n\\n withitem = (expr context_expr, expr? optional_vars)\\n\\n match_case = (pattern pattern, expr? guard, stmt* body)\\n\\n pattern = MatchValue(expr value)\\n | MatchSingleton(constant value)\\n | MatchSequence(pattern* patterns)\\n | MatchMapping(expr* keys, pattern* patterns, identifier? rest)\\n | MatchClass(expr cls, pattern* patterns, identifier* kwd_attrs, pattern* kwd_patterns)\\n\\n | MatchStar(identifier? name)\\n -- The optional \"rest\" MatchMapping parameter handles capturing extra mapping keys\\n\\n | MatchAs(pattern? pattern, identifier? name)\\n | MatchOr(pattern* patterns)\\n\\n attributes (int lineno, int col_offset, int end_lineno, int end_col_offset)\\n\\n type_ignore = TypeIgnore(int lineno, string tag)\\n\\n type_param = TypeVar(identifier name, expr? bound, expr? default_value)\\n | ParamSpec(identifier name, expr? default_value)\\n | TypeVarTuple(identifier name, expr? default_value)\\n attributes (int lineno, int col_offset, int end_lineno, int end_col_offset)\\n}\\n\\nNode classes¶\\n\\nChanged in version 3.8: Class ast.Constant is now used for all constants.\\n\\nChanged in version 3.9: Simple indices are represented by their value, extended slices are represented as tuples.\\n\\nChanged in version 3.14: The __repr__() output of AST nodes includes the values of the node fields.\\n\\nDeprecated since version 3.8, removed in version 3.14: Previous versions of Python provided the AST classes ast.Num, ast.Str, ast.Bytes, ast.NameConstant and ast.Ellipsis, which were deprecated in Python 3.8. These classes were removed in Python 3.14, and their functionality has been replaced with ast.Constant.\\n\\nDeprecated since version 3.9: Old classes ast.Index and ast.ExtSlice are still available, but they will be removed in future Python releases. In the meantime, instantiating them will return an instance of a different class.\\n\\nDeprecated since version 3.13, 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.\\n\\nNote\\n\\nThe descriptions of the specific node classes displayed here were initially adapted from the fantastic Green Tree Snakes project and all its contributors.\\n\\nRoot nodes¶\\n\\nLiterals¶\\n\\nVariables¶\\n\\nExpressions¶\\n\\nSubscripting¶\\n\\nComprehensions¶\\n\\nStatements¶\\n\\nOther statements which are only applicable inside functions or loops are described in other sections.\\n\\nImports¶\\n\\nControl flow¶\\n\\nNote\\n\\nOptional clauses such as else are stored as an empty list if they’re not present.\\n\\nPattern matching¶\\n\\nType annotations¶\\n\\nType parameters¶\\n\\nType parameters can exist on classes, functions, and type aliases.\\n\\nFunction and class definitions¶\\n\\nAsync and await¶\\n\\n>>> print(ast.dump(ast.parse(\"\"\"\\\\\\n... async def f():\\n... await other_func()\\n... \"\"\"), indent=4))\\nModule(\\n body=[\\n AsyncFunctionDef(\\n name=\\'f\\',\\n args=arguments(),\\n body=[\\n Expr(\\n value=Await(\\n value=Call(\\n func=Name(id=\\'other_func\\'))))])])\\n\\nNote\\n\\nWhen a string is parsed by ast.parse(), operator nodes (subclasses of ast.operator, ast.unaryop, ast.cmpop, ast.boolop and ast.expr_context) on the returned tree will be singletons. Changes to one will be reflected in all other occurrences of the same value (for example, ast.Add).\\n\\nast helpers¶\\n\\nApart from the node classes, the ast module defines these utility functions and classes for traversing abstract syntax trees:\\n\\nCompiler flags¶\\n\\nThe following flags may be passed to compile() in order to change effects on the compilation of a program:\\n\\nCommand-line usage¶\\n\\nAdded in version 3.9.\\n\\nThe ast module can be executed as a script from the command line. It is as simple as:\\n\\npython -m ast [-m ] [-a] [infile]\\n\\nThe following options are accepted:\\n\\nIf infile is specified its contents are parsed to AST and dumped to stdout. Otherwise, the content is read from stdin.\\n\\nSee also\\n\\nGreen Tree Snakes, an external documentation resource, has good details on working with Python ASTs.\\n\\nASTTokens annotates Python ASTs with the positions of tokens and text in the source code that generated them. This is helpful for tools that make source code transformations.\\n\\nleoAst.py unifies the token-based and parse-tree-based views of python programs by inserting two-way links between tokens and ast nodes.\\n\\nLibCST parses code as a Concrete Syntax Tree that looks like an ast tree and keeps all formatting details. It’s useful for building automated refactoring (codemod) applications and linters.\\n\\nParso 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.\\n\\nTable of Contents\\n\\nast — Abstract syntax trees\\n\\nAbstract grammar\\n\\nNode classes\\n\\nRoot nodes\\n\\nLiterals\\n\\nVariables\\n\\nExpressions\\n\\nSubscripting\\n\\nComprehensions\\n\\nStatements\\n\\nImports\\n\\nControl flow\\n\\nPattern matching\\n\\nType annotations\\n\\nType parameters\\n\\nFunction and class definitions\\n\\nAsync and await\\n\\nast helpers\\n\\nCompiler flags\\n\\nCommand-line usage\\n\\nPrevious topic\\n\\nPython Language Services\\n\\nNext topic\\n\\nsymtable — Access to the compiler’s symbol tables\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Language Services »\\n\\nast — Abstract syntax trees\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\asynchat.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nRemoved Modules »\\n\\nasynchat — Asynchronous socket command/response handler\\n\\n|\\n\\nasynchat — Asynchronous socket command/response handler¶\\n\\nDeprecated since version 3.6, removed in version 3.12.\\n\\nThis module is no longer part of the Python standard library. It was removed in Python 3.12 after being deprecated in Python 3.6. The removal was decided in PEP 594.\\n\\nApplications should use the asyncio module instead.\\n\\nThe last version of Python that provided the asynchat module was Python 3.11.\\n\\nPrevious topic\\n\\naifc — Read and write AIFF and AIFC files\\n\\nNext topic\\n\\nasyncore — Asynchronous socket handler\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nRemoved Modules »\\n\\nasynchat — Asynchronous socket command/response handler\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\asyncio-api-index.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nHigh-level API Index\\n\\n|\\n\\nHigh-level API Index¶\\n\\nThis page lists all high-level async/await enabled asyncio APIs.\\n\\nTasks¶\\n\\nUtilities to run asyncio programs, create Tasks, and await on multiple things with timeouts.\\n\\nrun() Create event loop, run a coroutine, close the loop. Runner A context manager that simplifies multiple async function calls. Task Task object. TaskGroup A context manager that holds a group of tasks. Provides\\na convenient and reliable way to wait for all tasks in the group to\\nfinish. create_task() Start an asyncio Task, then returns it. current_task() Return the current Task. all_tasks() Return all tasks that are not yet finished for an event loop. await sleep() Sleep for a number of seconds. await gather() Schedule and wait for things concurrently. await wait_for() Run with a timeout. await shield() Shield from cancellation. await wait() Monitor for completion. timeout() Run with a timeout. Useful in cases when wait_for is not suitable. to_thread() Asynchronously run a function in a separate OS thread. run_coroutine_threadsafe() Schedule a coroutine from another OS thread. for in as_completed() Monitor for completion with a for loop.\\n\\nExamples\\n\\nUsing asyncio.gather() to run things in parallel.\\n\\nUsing asyncio.wait_for() to enforce a timeout.\\n\\nCancellation.\\n\\nUsing asyncio.sleep().\\n\\nSee also the main Tasks documentation page.\\n\\nQueues¶\\n\\nQueues should be used to distribute work amongst multiple asyncio Tasks, implement connection pools, and pub/sub patterns.\\n\\nQueue A FIFO queue. PriorityQueue A priority queue. LifoQueue A LIFO queue.\\n\\nExamples\\n\\nUsing asyncio.Queue to distribute workload between several Tasks.\\n\\nSee also the Queues documentation page.\\n\\nSubprocesses¶\\n\\nUtilities to spawn subprocesses and run shell commands.\\n\\nawait create_subprocess_exec() Create a subprocess. await create_subprocess_shell() Run a shell command.\\n\\nExamples\\n\\nExecuting a shell command.\\n\\nSee also the subprocess APIs documentation.\\n\\nStreams¶\\n\\nHigh-level APIs to work with network IO.\\n\\nawait open_connection() Establish a TCP connection. await open_unix_connection() Establish a Unix socket connection. await start_server() Start a TCP server. await start_unix_server() Start a Unix socket server. StreamReader High-level async/await object to receive network data. StreamWriter High-level async/await object to send network data.\\n\\nExamples\\n\\nExample TCP client.\\n\\nSee also the streams APIs documentation.\\n\\nSynchronization¶\\n\\nThreading-like synchronization primitives that can be used in Tasks.\\n\\nLock A mutex lock. Event An event object. Condition A condition object. Semaphore A semaphore. BoundedSemaphore A bounded semaphore. Barrier A barrier object.\\n\\nExamples\\n\\nUsing asyncio.Event.\\n\\nUsing asyncio.Barrier.\\n\\nSee also the documentation of asyncio synchronization primitives.\\n\\nExceptions¶\\n\\nasyncio.CancelledError Raised when a Task is cancelled. See also Task.cancel() . asyncio.BrokenBarrierError Raised when a Barrier is broken. See also Barrier.wait() .\\n\\nExamples\\n\\nHandling CancelledError to run code on cancellation request.\\n\\nSee also the full list of asyncio-specific exceptions.\\n\\nTable of Contents\\n\\nHigh-level API Index\\n\\nTasks\\n\\nQueues\\n\\nSubprocesses\\n\\nStreams\\n\\nSynchronization\\n\\nExceptions\\n\\nPrevious topic\\n\\nExtending\\n\\nNext topic\\n\\nLow-level API Index\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nHigh-level API Index\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\asyncio-dev.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nDeveloping with asyncio\\n\\n|\\n\\nDeveloping with asyncio¶\\n\\nAsynchronous programming is different from classic “sequential” programming.\\n\\nThis page lists common mistakes and traps and explains how to avoid them.\\n\\nDebug Mode¶\\n\\nBy default asyncio runs in production mode. In order to ease the development asyncio has a debug mode.\\n\\nThere are several ways to enable asyncio debug mode:\\n\\nSetting the PYTHONASYNCIODEBUG environment variable to 1.\\n\\nUsing the Python Development Mode.\\n\\nPassing debug=True to asyncio.run().\\n\\nCalling loop.set_debug().\\n\\nIn addition to enabling the debug mode, consider also:\\n\\nsetting the log level of the asyncio logger to logging.DEBUG, for example the following snippet of code can be run at startup of the application:\\n\\nlogging.basicConfig(level=logging.DEBUG)\\n\\nconfiguring the warnings module to display ResourceWarning warnings. One way of doing that is by using the -W default command line option.\\n\\nWhen the debug mode is enabled:\\n\\nMany non-threadsafe asyncio APIs (such as loop.call_soon() and loop.call_at() methods) raise an exception if they are called from a wrong thread.\\n\\nThe execution time of the I/O selector is logged if it takes too long to perform an I/O operation.\\n\\nCallbacks taking longer than 100 milliseconds are logged. The loop.slow_callback_duration attribute can be used to set the minimum execution duration in seconds that is considered “slow”.\\n\\nConcurrency and Multithreading¶\\n\\nAn event loop runs in a thread (typically the main thread) and executes all callbacks and Tasks in its thread. While a Task is running in the event loop, no other Tasks can run in the same thread. When a Task executes an await expression, the running Task gets suspended, and the event loop executes the next Task.\\n\\nTo schedule a callback from another OS thread, the loop.call_soon_threadsafe() method should be used. Example:\\n\\nloop.call_soon_threadsafe(callback, *args)\\n\\nAlmost all asyncio objects are not thread safe, which is typically not a problem unless there is code that works with them from outside of a Task or a callback. If there’s a need for such code to call a low-level asyncio API, the loop.call_soon_threadsafe() method should be used, e.g.:\\n\\nloop.call_soon_threadsafe(fut.cancel)\\n\\nTo schedule a coroutine object from a different OS thread, the run_coroutine_threadsafe() function should be used. It returns a concurrent.futures.Future to access the result:\\n\\nasync def coro_func():\\n return await asyncio.sleep(1, 42)\\n\\n# Later in another OS thread:\\n\\nfuture = asyncio.run_coroutine_threadsafe(coro_func(), loop)\\n# Wait for the result:\\nresult = future.result()\\n\\nTo handle signals the event loop must be run in the main thread.\\n\\nThe loop.run_in_executor() method can be used with a concurrent.futures.ThreadPoolExecutor or InterpreterPoolExecutor to execute blocking code in a different OS thread without blocking the OS thread that the event loop runs in.\\n\\nThere is currently no way to schedule coroutines or callbacks directly from a different process (such as one started with multiprocessing). The Event Loop Methods section lists APIs that can read from pipes and watch file descriptors without blocking the event loop. In addition, asyncio’s Subprocess APIs provide a way to start a process and communicate with it from the event loop. Lastly, the aforementioned loop.run_in_executor() method can also be used with a concurrent.futures.ProcessPoolExecutor to execute code in a different process.\\n\\nRunning Blocking Code¶\\n\\nBlocking (CPU-bound) code should not be called directly. For example, if a function performs a CPU-intensive calculation for 1 second, all concurrent asyncio Tasks and IO operations would be delayed by 1 second.\\n\\nAn 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 loop.run_in_executor() method for more details.\\n\\nLogging¶\\n\\nasyncio uses the logging module and all logging is performed via the \"asyncio\" logger.\\n\\nThe default log level is logging.INFO, which can be easily adjusted:\\n\\nlogging.getLogger(\"asyncio\").setLevel(logging.WARNING)\\n\\nNetwork logging can block the event loop. It is recommended to use a separate thread for handling logs or use non-blocking IO. For example, see Dealing with handlers that block.\\n\\nDetect never-awaited coroutines¶\\n\\nWhen a coroutine function is called, but not awaited (e.g. coro() instead of await coro()) or the coroutine is not scheduled with asyncio.create_task(), asyncio will emit a RuntimeWarning:\\n\\nimport asyncio\\n\\nasync def test():\\n print(\"never scheduled\")\\n\\nasync def main():\\n test()\\n\\nasyncio.run(main())\\n\\nOutput:\\n\\ntest.py:7: RuntimeWarning: coroutine \\'test\\' was never awaited\\n test()\\n\\nOutput in debug mode:\\n\\ntest.py:7: RuntimeWarning: coroutine \\'test\\' was never awaited\\nCoroutine created at (most recent call last)\\n File \"../t.py\", line 9, in \\n asyncio.run(main(), debug=True)\\n\\n < .. >\\n\\n File \"../t.py\", line 7, in main\\n test()\\n test()\\n\\nThe usual fix is to either await the coroutine or call the asyncio.create_task() function:\\n\\nasync def main():\\n await test()\\n\\nDetect never-retrieved exceptions¶\\n\\nIf a Future.set_exception() is called but the Future object is never awaited on, the exception would never be propagated to the user code. In this case, asyncio would emit a log message when the Future object is garbage collected.\\n\\nExample of an unhandled exception:\\n\\nimport asyncio\\n\\nasync def bug():\\n raise Exception(\"not consumed\")\\n\\nasync def main():\\n asyncio.create_task(bug())\\n\\nasyncio.run(main())\\n\\nOutput:\\n\\nTask exception was never retrieved\\nfuture: \\n exception=Exception(\\'not consumed\\')>\\n\\nTraceback (most recent call last):\\n File \"test.py\", line 4, in bug\\n raise Exception(\"not consumed\")\\nException: not consumed\\n\\nEnable the debug mode to get the traceback where the task was created:\\n\\nasyncio.run(main(), debug=True)\\n\\nOutput in debug mode:\\n\\nTask exception was never retrieved\\nfuture: \\n exception=Exception(\\'not consumed\\') created at asyncio/tasks.py:321>\\n\\nsource_traceback: Object created at (most recent call last):\\n File \"../t.py\", line 9, in \\n asyncio.run(main(), debug=True)\\n\\n< .. >\\n\\nTraceback (most recent call last):\\n File \"../t.py\", line 4, in bug\\n raise Exception(\"not consumed\")\\nException: not consumed\\n\\nTable of Contents\\n\\nDeveloping with asyncio\\n\\nDebug Mode\\n\\nConcurrency and Multithreading\\n\\nRunning Blocking Code\\n\\nLogging\\n\\nDetect never-awaited coroutines\\n\\nDetect never-retrieved exceptions\\n\\nPrevious topic\\n\\nLow-level API Index\\n\\nNext topic\\n\\nsocket — Low-level networking interface\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nDeveloping with asyncio\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\asyncio-eventloop.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nEvent Loop\\n\\n|\\n\\nEvent Loop¶\\n\\nSource code: Lib/asyncio/events.py, Lib/asyncio/base_events.py\\n\\nPreface\\n\\nThe event loop is the core of every asyncio application. Event loops run asynchronous tasks and callbacks, perform network IO operations, and run subprocesses.\\n\\nApplication developers should typically use the high-level asyncio functions, such as asyncio.run(), and should rarely need to reference the loop object or call its methods. This section is intended mostly for authors of lower-level code, libraries, and frameworks, who need finer control over the event loop behavior.\\n\\nObtaining the Event Loop\\n\\nThe following low-level functions can be used to get, set, or create an event loop:\\n\\nNote that the behaviour of get_event_loop(), set_event_loop(), and new_event_loop() functions can be altered by setting a custom event loop policy.\\n\\nContents\\n\\nThis documentation page contains the following sections:\\n\\nThe Event Loop Methods section is the reference documentation of the event loop APIs;\\n\\nThe Callback Handles section documents the Handle and TimerHandle instances which are returned from scheduling methods such as loop.call_soon() and loop.call_later();\\n\\nThe Server Objects section documents types returned from event loop methods like loop.create_server();\\n\\nThe Event Loop Implementations section documents the SelectorEventLoop and ProactorEventLoop classes;\\n\\nThe Examples section showcases how to work with some event loop APIs.\\n\\nEvent Loop Methods¶\\n\\nEvent loops have low-level APIs for the following:\\n\\nRunning and stopping the loop¶\\n\\nScheduling callbacks¶\\n\\nNote\\n\\nMost asyncio scheduling functions don’t allow passing keyword arguments. To do that, use functools.partial():\\n\\n# will schedule \"print(\"Hello\", flush=True)\"\\nloop.call_soon(\\n functools.partial(print, \"Hello\", flush=True))\\n\\nUsing partial objects is usually more convenient than using lambdas, as asyncio can render partial objects better in debug and error messages.\\n\\nScheduling delayed callbacks¶\\n\\nEvent loop provides mechanisms to schedule callback functions to be called at some point in the future. Event loop uses monotonic clocks to track time.\\n\\nNote\\n\\nChanged in version 3.8: In Python 3.7 and earlier timeouts (relative delay or absolute when) should not exceed one day. This has been fixed in Python 3.8.\\n\\nSee also\\n\\nThe asyncio.sleep() function.\\n\\nCreating Futures and Tasks¶\\n\\nOpening network connections¶\\n\\nCreating network servers¶\\n\\nTransferring files¶\\n\\nTLS Upgrade¶\\n\\nWatching file descriptors¶\\n\\nSee also Platform Support section for some limitations of these methods.\\n\\nWorking with socket objects directly¶\\n\\nIn general, protocol implementations that use transport-based APIs such as loop.create_connection() and loop.create_server() are faster than implementations that work with sockets directly. However, there are some use cases when performance is not critical, and working with socket objects directly is more convenient.\\n\\nDNS¶\\n\\nNote\\n\\nBoth 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.\\n\\nChanged in version 3.7: Both getaddrinfo and getnameinfo methods were always documented to return a coroutine, but prior to Python 3.7 they were, in fact, returning asyncio.Future objects. Starting with Python 3.7 both methods are coroutines.\\n\\nWorking with pipes¶\\n\\nNote\\n\\nSelectorEventLoop does not support the above methods on Windows. Use ProactorEventLoop instead for Windows.\\n\\nSee also\\n\\nThe loop.subprocess_exec() and loop.subprocess_shell() methods.\\n\\nUnix signals¶\\n\\nSee also\\n\\nThe signal module.\\n\\nExecuting code in thread or process pools¶\\n\\nError Handling API¶\\n\\nAllows customizing how exceptions are handled in the event loop.\\n\\nEnabling debug mode¶\\n\\nSee also\\n\\nThe debug mode of asyncio.\\n\\nRunning Subprocesses¶\\n\\nMethods described in this subsections are low-level. In regular async/await code consider using the high-level asyncio.create_subprocess_shell() and asyncio.create_subprocess_exec() convenience functions instead.\\n\\nNote\\n\\nOn Windows, the default event loop ProactorEventLoop supports subprocesses, whereas SelectorEventLoop does not. See Subprocess Support on Windows for details.\\n\\nNote\\n\\nIt is the application’s responsibility to ensure that all whitespace and special characters are quoted appropriately to avoid shell injection vulnerabilities. The shlex.quote() function can be used to properly escape whitespace and special characters in strings that are going to be used to construct shell commands.\\n\\nCallback Handles¶\\n\\nServer Objects¶\\n\\nServer objects are created by loop.create_server(), loop.create_unix_server(), start_server(), and start_unix_server() functions.\\n\\nDo not instantiate the Server class directly.\\n\\nEvent Loop Implementations¶\\n\\nasyncio ships with two different event loop implementations: SelectorEventLoop and ProactorEventLoop.\\n\\nBy default asyncio is configured to use EventLoop.\\n\\nExamples¶\\n\\nNote that all examples in this section purposefully show how to use the low-level event loop APIs, such as loop.run_forever() and loop.call_soon(). Modern asyncio applications rarely need to be written this way; consider using the high-level functions like asyncio.run().\\n\\nHello World with call_soon()¶\\n\\nAn example using the loop.call_soon() method to schedule a callback. The callback displays \"Hello World\" and then stops the event loop:\\n\\nimport asyncio\\n\\ndef hello_world(loop):\\n \"\"\"A callback to print \\'Hello World\\' and stop the event loop\"\"\"\\n print(\\'Hello World\\')\\n loop.stop()\\n\\nloop = asyncio.new_event_loop()\\n\\n# Schedule a call to hello_world()\\nloop.call_soon(hello_world, loop)\\n\\n# Blocking call interrupted by loop.stop()\\ntry:\\n loop.run_forever()\\nfinally:\\n loop.close()\\n\\nSee also\\n\\nA similar Hello World example created with a coroutine and the run() function.\\n\\nDisplay the current date with call_later()¶\\n\\nAn example of a callback displaying the current date every second. The callback uses the loop.call_later() method to reschedule itself after 5 seconds, and then stops the event loop:\\n\\nimport asyncio\\nimport datetime\\n\\ndef display_date(end_time, loop):\\n print(datetime.datetime.now())\\n if (loop.time() + 1.0) < end_time:\\n loop.call_later(1, display_date, end_time, loop)\\n else:\\n loop.stop()\\n\\nloop = asyncio.new_event_loop()\\n\\n# Schedule the first call to display_date()\\nend_time = loop.time() + 5.0\\nloop.call_soon(display_date, end_time, loop)\\n\\n# Blocking call interrupted by loop.stop()\\ntry:\\n loop.run_forever()\\nfinally:\\n loop.close()\\n\\nSee also\\n\\nA similar current date example created with a coroutine and the run() function.\\n\\nWatch a file descriptor for read events¶\\n\\nWait until a file descriptor received some data using the loop.add_reader() method and then close the event loop:\\n\\nimport asyncio\\nfrom socket import socketpair\\n\\n# Create a pair of connected file descriptors\\nrsock, wsock = socketpair()\\n\\nloop = asyncio.new_event_loop()\\n\\ndef reader():\\n data = rsock.recv(100)\\n print(\"Received:\", data.decode())\\n\\n # We are done: unregister the file descriptor\\n loop.remove_reader(rsock)\\n\\n # Stop the event loop\\n loop.stop()\\n\\n# Register the file descriptor for read event\\nloop.add_reader(rsock, reader)\\n\\n# Simulate the reception of data from the network\\nloop.call_soon(wsock.send, \\'abc\\'.encode())\\n\\ntry:\\n # Run the event loop\\n loop.run_forever()\\nfinally:\\n # We are done. Close sockets and the event loop.\\n rsock.close()\\n wsock.close()\\n loop.close()\\n\\nSee also\\n\\nA similar example using transports, protocols, and the loop.create_connection() method.\\n\\nAnother similar example using the high-level asyncio.open_connection() function and streams.\\n\\nSet signal handlers for SIGINT and SIGTERM¶\\n\\n(This signals example only works on Unix.)\\n\\nRegister handlers for signals SIGINT and SIGTERM using the loop.add_signal_handler() method:\\n\\nimport asyncio\\nimport functools\\nimport os\\nimport signal\\n\\ndef ask_exit(signame, loop):\\n print(\"got signal %s: exit\" % signame)\\n loop.stop()\\n\\nasync def main():\\n loop = asyncio.get_running_loop()\\n\\n for signame in {\\'SIGINT\\', \\'SIGTERM\\'}:\\n loop.add_signal_handler(\\n getattr(signal, signame),\\n functools.partial(ask_exit, signame, loop))\\n\\n await asyncio.sleep(3600)\\n\\nprint(\"Event loop running for 1 hour, press Ctrl+C to interrupt.\")\\nprint(f\"pid {os.getpid()}: send SIGINT or SIGTERM to exit.\")\\n\\nasyncio.run(main())\\n\\nTable of Contents\\n\\nEvent Loop\\n\\nEvent Loop Methods\\n\\nRunning and stopping the loop\\n\\nScheduling callbacks\\n\\nScheduling delayed callbacks\\n\\nCreating Futures and Tasks\\n\\nOpening network connections\\n\\nCreating network servers\\n\\nTransferring files\\n\\nTLS Upgrade\\n\\nWatching file descriptors\\n\\nWorking with socket objects directly\\n\\nDNS\\n\\nWorking with pipes\\n\\nUnix signals\\n\\nExecuting code in thread or process pools\\n\\nError Handling API\\n\\nEnabling debug mode\\n\\nRunning Subprocesses\\n\\nCallback Handles\\n\\nServer Objects\\n\\nEvent Loop Implementations\\n\\nExamples\\n\\nHello World with call_soon()\\n\\nDisplay the current date with call_later()\\n\\nWatch a file descriptor for read events\\n\\nSet signal handlers for SIGINT and SIGTERM\\n\\nPrevious topic\\n\\nCall Graph Introspection\\n\\nNext topic\\n\\nFutures\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nEvent Loop\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\asyncio-exceptions.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nExceptions\\n\\n|\\n\\nExceptions¶\\n\\nSource code: Lib/asyncio/exceptions.py\\n\\nPrevious topic\\n\\nQueues\\n\\nNext topic\\n\\nCall Graph Introspection\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nExceptions\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\asyncio-extending.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nExtending\\n\\n|\\n\\nExtending¶\\n\\nThe main direction for asyncio extending is writing custom event loop classes. Asyncio has helpers that could be used to simplify this task.\\n\\nNote\\n\\nThird-parties should reuse existing asyncio code with caution, a new Python version is free to break backward compatibility in internal part of API.\\n\\nWriting a Custom Event Loop¶\\n\\nasyncio.AbstractEventLoop declares very many methods. Implementing all them from scratch is a tedious job.\\n\\nA loop can get many common methods implementation for free by inheriting from asyncio.BaseEventLoop.\\n\\nIn turn, the successor should implement a bunch of private methods declared but not implemented in asyncio.BaseEventLoop.\\n\\nFor example, loop.create_connection() checks arguments, resolves DNS addresses, and calls loop._make_socket_transport() that should be implemented by inherited class. The _make_socket_transport() method is not documented and is considered as an internal API.\\n\\nFuture and Task private constructors¶\\n\\nasyncio.Future and asyncio.Task should be never created directly, please use corresponding loop.create_future() and loop.create_task(), or asyncio.create_task() factories instead.\\n\\nHowever, 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.\\n\\nFor this purpose the following, private constructors are listed:\\n\\nTask lifetime support¶\\n\\nA third party task implementation should call the following functions to keep a task visible by asyncio.all_tasks() and asyncio.current_task():\\n\\nTable of Contents\\n\\nExtending\\n\\nWriting a Custom Event Loop\\n\\nFuture and Task private constructors\\n\\nTask lifetime support\\n\\nPrevious topic\\n\\nPlatform Support\\n\\nNext topic\\n\\nHigh-level API Index\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nExtending\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\asyncio-future.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nFutures\\n\\n|\\n\\nFutures¶\\n\\nSource code: Lib/asyncio/futures.py, Lib/asyncio/base_futures.py\\n\\nFuture objects are used to bridge low-level callback-based code with high-level async/await code.\\n\\nFuture Functions¶\\n\\nFuture Object¶\\n\\nThis example creates a Future object, creates and schedules an asynchronous Task to set result for the Future, and waits until the Future has a result:\\n\\nasync def set_after(fut, delay, value):\\n # Sleep for *delay* seconds.\\n await asyncio.sleep(delay)\\n\\n # Set *value* as a result of *fut* Future.\\n fut.set_result(value)\\n\\nasync def main():\\n # Get the current event loop.\\n loop = asyncio.get_running_loop()\\n\\n # Create a new Future object.\\n fut = loop.create_future()\\n\\n # Run \"set_after()\" coroutine in a parallel Task.\\n # We are using the low-level \"loop.create_task()\" API here because\\n # we already have a reference to the event loop at hand.\\n # Otherwise we could have just used \"asyncio.create_task()\".\\n loop.create_task(\\n set_after(fut, 1, \\'... world\\'))\\n\\n print(\\'hello ...\\')\\n\\n # Wait until *fut* has a result (1 second) and print it.\\n print(await fut)\\n\\nasyncio.run(main())\\n\\nImportant\\n\\nThe Future object was designed to mimic concurrent.futures.Future. Key differences include:\\n\\nunlike asyncio Futures, concurrent.futures.Future instances cannot be awaited.\\n\\nasyncio.Future.result() and asyncio.Future.exception() do not accept the timeout argument.\\n\\nasyncio.Future.result() and asyncio.Future.exception() raise an InvalidStateError exception when the Future is not done.\\n\\nCallbacks registered with asyncio.Future.add_done_callback() are not called immediately. They are scheduled with loop.call_soon() instead.\\n\\nasyncio Future is not compatible with the concurrent.futures.wait() and concurrent.futures.as_completed() functions.\\n\\nasyncio.Future.cancel() accepts an optional msg argument, but concurrent.futures.Future.cancel() does not.\\n\\nTable of Contents\\n\\nFutures\\n\\nFuture Functions\\n\\nFuture Object\\n\\nPrevious topic\\n\\nEvent Loop\\n\\nNext topic\\n\\nTransports and Protocols\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nFutures\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\asyncio-graph.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nCall Graph Introspection\\n\\n|\\n\\nCall Graph Introspection¶\\n\\nSource code: Lib/asyncio/graph.py\\n\\nasyncio 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.\\n\\nAdded in version 3.14.\\n\\nLow level utility functions¶\\n\\nTo introspect an async call graph asyncio requires cooperation from control flow structures, such as shield() or TaskGroup. Any time an intermediate Future object with low-level APIs like 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.\\n\\nTable of Contents\\n\\nCall Graph Introspection\\n\\nLow level utility functions\\n\\nPrevious topic\\n\\nExceptions\\n\\nNext topic\\n\\nEvent Loop\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nCall Graph Introspection\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\asyncio-llapi-index.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nLow-level API Index\\n\\n|\\n\\nLow-level API Index¶\\n\\nThis page lists all low-level asyncio APIs.\\n\\nObtaining the Event Loop¶\\n\\nasyncio.get_running_loop() The preferred function to get the running event loop. asyncio.get_event_loop() Get an event loop instance (running or current via the current policy). asyncio.set_event_loop() Set the event loop as current via the current policy. asyncio.new_event_loop() Create a new event loop.\\n\\nExamples\\n\\nUsing asyncio.get_running_loop().\\n\\nEvent Loop Methods¶\\n\\nSee also the main documentation section about the Event Loop Methods.\\n\\nLifecycle\\n\\nloop.run_until_complete() Run a Future/Task/awaitable until complete. loop.run_forever() Run the event loop forever. loop.stop() Stop the event loop. loop.close() Close the event loop. loop.is_running() Return True if the event loop is running. loop.is_closed() Return True if the event loop is closed. await loop.shutdown_asyncgens() Close asynchronous generators.\\n\\nDebugging\\n\\nloop.set_debug() Enable or disable the debug mode. loop.get_debug() Get the current debug mode.\\n\\nScheduling Callbacks\\n\\nloop.call_soon() Invoke a callback soon. loop.call_soon_threadsafe() A thread-safe variant of loop.call_soon() . loop.call_later() Invoke a callback after the given time. loop.call_at() Invoke a callback at the given time.\\n\\nThread/Interpreter/Process Pool\\n\\nawait loop.run_in_executor() Run a CPU-bound or other blocking function in\\na concurrent.futures executor. loop.set_default_executor() Set the default executor for loop.run_in_executor() .\\n\\nTasks and Futures\\n\\nloop.create_future() Create a Future object. loop.create_task() Schedule coroutine as a Task . loop.set_task_factory() Set a factory used by loop.create_task() to\\ncreate Tasks . loop.get_task_factory() Get the factory loop.create_task() uses\\nto create Tasks .\\n\\nDNS\\n\\nawait loop.getaddrinfo() Asynchronous version of socket.getaddrinfo() . await loop.getnameinfo() Asynchronous version of socket.getnameinfo() .\\n\\nNetworking and IPC\\n\\nawait loop.create_connection() Open a TCP connection. await loop.create_server() Create a TCP server. await loop.create_unix_connection() Open a Unix socket connection. await loop.create_unix_server() Create a Unix socket server. await loop.connect_accepted_socket() Wrap a socket into a (transport, protocol) pair. await loop.create_datagram_endpoint() Open a datagram (UDP) connection. await loop.sendfile() Send a file over a transport. await loop.start_tls() Upgrade an existing connection to TLS. await loop.connect_read_pipe() Wrap a read end of a pipe into a (transport, protocol) pair. await loop.connect_write_pipe() Wrap a write end of a pipe into a (transport, protocol) pair.\\n\\nSockets\\n\\nawait loop.sock_recv() Receive data from the socket . await loop.sock_recv_into() Receive data from the socket into a buffer. await loop.sock_recvfrom() Receive a datagram from the socket . await loop.sock_recvfrom_into() Receive a datagram from the socket into a buffer. await loop.sock_sendall() Send data to the socket . await loop.sock_sendto() Send a datagram via the socket to the given address. await loop.sock_connect() Connect the socket . await loop.sock_accept() Accept a socket connection. await loop.sock_sendfile() Send a file over the socket . loop.add_reader() Start watching a file descriptor for read availability. loop.remove_reader() Stop watching a file descriptor for read availability. loop.add_writer() Start watching a file descriptor for write availability. loop.remove_writer() Stop watching a file descriptor for write availability.\\n\\nUnix Signals\\n\\nloop.add_signal_handler() Add a handler for a signal . loop.remove_signal_handler() Remove a handler for a signal .\\n\\nSubprocesses\\n\\nloop.subprocess_exec() Spawn a subprocess. loop.subprocess_shell() Spawn a subprocess from a shell command.\\n\\nError Handling\\n\\nloop.call_exception_handler() Call the exception handler. loop.set_exception_handler() Set a new exception handler. loop.get_exception_handler() Get the current exception handler. loop.default_exception_handler() The default exception handler implementation.\\n\\nExamples\\n\\nUsing asyncio.new_event_loop() and loop.run_forever().\\n\\nUsing loop.call_later().\\n\\nUsing loop.create_connection() to implement an echo-client.\\n\\nUsing loop.create_connection() to connect a socket.\\n\\nUsing add_reader() to watch an FD for read events.\\n\\nUsing loop.add_signal_handler().\\n\\nUsing loop.subprocess_exec().\\n\\nTransports¶\\n\\nAll transports implement the following methods:\\n\\ntransport.close() Close the transport. transport.is_closing() Return True if the transport is closing or is closed. transport.get_extra_info() Request for information about the transport. transport.set_protocol() Set a new protocol. transport.get_protocol() Return the current protocol.\\n\\nTransports that can receive data (TCP and Unix connections, pipes, etc). Returned from methods like loop.create_connection(), loop.create_unix_connection(), loop.connect_read_pipe(), etc:\\n\\nRead Transports\\n\\ntransport.is_reading() Return True if the transport is receiving. transport.pause_reading() Pause receiving. transport.resume_reading() Resume receiving.\\n\\nTransports that can Send data (TCP and Unix connections, pipes, etc). Returned from methods like loop.create_connection(), loop.create_unix_connection(), loop.connect_write_pipe(), etc:\\n\\nWrite Transports\\n\\ntransport.write() Write data to the transport. transport.writelines() Write buffers to the transport. transport.can_write_eof() Return True if the transport supports sending EOF. transport.write_eof() Close and send EOF after flushing buffered data. transport.abort() Close the transport immediately. transport.get_write_buffer_size() Return the current size of the output buffer. transport.get_write_buffer_limits() Return high and low water marks for write flow control. transport.set_write_buffer_limits() Set new high and low water marks for write flow control.\\n\\nTransports returned by loop.create_datagram_endpoint():\\n\\nDatagram Transports\\n\\ntransport.sendto() Send data to the remote peer. transport.abort() Close the transport immediately.\\n\\nLow-level transport abstraction over subprocesses. Returned by loop.subprocess_exec() and loop.subprocess_shell():\\n\\nSubprocess Transports\\n\\ntransport.get_pid() Return the subprocess process id. transport.get_pipe_transport() Return the transport for the requested communication pipe\\n( stdin , stdout , or stderr ). transport.get_returncode() Return the subprocess return code. transport.kill() Kill the subprocess. transport.send_signal() Send a signal to the subprocess. transport.terminate() Stop the subprocess. transport.close() Kill the subprocess and close all pipes.\\n\\nProtocols¶\\n\\nProtocol classes can implement the following callback methods:\\n\\ncallback connection_made() Called when a connection is made. callback connection_lost() Called when the connection is lost or closed. callback pause_writing() Called when the transport’s buffer goes over the high water mark. callback resume_writing() Called when the transport’s buffer drains below the low water mark.\\n\\nStreaming Protocols (TCP, Unix Sockets, Pipes)\\n\\ncallback data_received() Called when some data is received. callback eof_received() Called when an EOF is received.\\n\\nBuffered Streaming Protocols\\n\\ncallback get_buffer() Called to allocate a new receive buffer. callback buffer_updated() Called when the buffer was updated with the received data. callback eof_received() Called when an EOF is received.\\n\\nDatagram Protocols\\n\\ncallback datagram_received() Called when a datagram is received. callback error_received() Called when a previous send or receive operation raises an OSError .\\n\\nSubprocess Protocols\\n\\ncallback pipe_data_received() Called when the child process writes data into its stdout or stderr pipe. callback pipe_connection_lost() Called when one of the pipes communicating with\\nthe child process is closed. callback process_exited() Called when the child process has exited. It can be called before pipe_data_received() and pipe_connection_lost() methods.\\n\\nEvent Loop Policies¶\\n\\nPolicies is a low-level mechanism to alter the behavior of functions like asyncio.get_event_loop(). See also the main policies section for more details.\\n\\nAccessing Policies\\n\\nasyncio.get_event_loop_policy() Return the current process-wide policy. asyncio.set_event_loop_policy() Set a new process-wide policy. AbstractEventLoopPolicy Base class for policy objects.\\n\\nTable of Contents\\n\\nLow-level API Index\\n\\nObtaining the Event Loop\\n\\nEvent Loop Methods\\n\\nTransports\\n\\nProtocols\\n\\nEvent Loop Policies\\n\\nPrevious topic\\n\\nHigh-level API Index\\n\\nNext topic\\n\\nDeveloping with asyncio\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nLow-level API Index\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\asyncio-platforms.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nPlatform Support\\n\\n|\\n\\nPlatform Support¶\\n\\nThe asyncio module is designed to be portable, but some platforms have subtle differences and limitations due to the platforms’ underlying architecture and capabilities.\\n\\nAll Platforms¶\\n\\nloop.add_reader() and loop.add_writer() cannot be used to monitor file I/O.\\n\\nWindows¶\\n\\nSource code: Lib/asyncio/proactor_events.py, Lib/asyncio/windows_events.py, Lib/asyncio/windows_utils.py\\n\\nChanged in version 3.8: On Windows, ProactorEventLoop is now the default event loop.\\n\\nAll event loops on Windows do not support the following methods:\\n\\nloop.create_unix_connection() and loop.create_unix_server() are not supported. The socket.AF_UNIX socket family is specific to Unix.\\n\\nloop.add_signal_handler() and loop.remove_signal_handler() are not supported.\\n\\nSelectorEventLoop has the following limitations:\\n\\nSelectSelector is used to wait on socket events: it supports sockets and is limited to 512 sockets.\\n\\nloop.add_reader() and loop.add_writer() only accept socket handles (e.g. pipe file descriptors are not supported).\\n\\nPipes are not supported, so the loop.connect_read_pipe() and loop.connect_write_pipe() methods are not implemented.\\n\\nSubprocesses are not supported, i.e. loop.subprocess_exec() and loop.subprocess_shell() methods are not implemented.\\n\\nProactorEventLoop has the following limitations:\\n\\nThe loop.add_reader() and loop.add_writer() methods are not supported.\\n\\nThe resolution of the monotonic clock on Windows is usually around 15.6 milliseconds. The best resolution is 0.5 milliseconds. The resolution depends on the hardware (availability of HPET) and on the Windows configuration.\\n\\nSubprocess Support on Windows¶\\n\\nOn Windows, the default event loop ProactorEventLoop supports subprocesses, whereas SelectorEventLoop does not.\\n\\nmacOS¶\\n\\nModern macOS versions are fully supported.\\n\\nmacOS <= 10.8\\n\\nOn macOS 10.6, 10.7 and 10.8, the default event loop uses selectors.KqueueSelector, which does not support character devices on these versions. The SelectorEventLoop can be manually configured to use SelectSelector or PollSelector to support character devices on these older versions of macOS. Example:\\n\\nimport asyncio\\nimport selectors\\n\\nselector = selectors.SelectSelector()\\nloop = asyncio.SelectorEventLoop(selector)\\nasyncio.set_event_loop(loop)\\n\\nTable of Contents\\n\\nPlatform Support\\n\\nAll Platforms\\n\\nWindows\\n\\nSubprocess Support on Windows\\n\\nmacOS\\n\\nPrevious topic\\n\\nPolicies\\n\\nNext topic\\n\\nExtending\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nPlatform Support\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\asyncio-policy.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nPolicies\\n\\n|\\n\\nPolicies¶\\n\\nWarning\\n\\nPolicies are deprecated and will be removed in Python 3.16. Users are encouraged to use the asyncio.run() function or the asyncio.Runner with loop_factory to use the desired loop implementation.\\n\\nAn event loop policy is a global object used to get and set the current event loop, as well as create new event loops. The default policy can be replaced with built-in alternatives to use different event loop implementations, or substituted by a custom policy that can override these behaviors.\\n\\nThe policy object gets and sets a separate event loop per context. This is per-thread by default, though custom policies could define context differently.\\n\\nCustom event loop policies can control the behavior of get_event_loop(), set_event_loop(), and new_event_loop().\\n\\nPolicy objects should implement the APIs defined in the AbstractEventLoopPolicy abstract base class.\\n\\nGetting and Setting the Policy¶\\n\\nThe following functions can be used to get and set the policy for the current process:\\n\\nPolicy Objects¶\\n\\nThe abstract event loop policy base class is defined as follows:\\n\\nasyncio ships with the following built-in policies:\\n\\nCustom Policies¶\\n\\nTo implement a new event loop policy, it is recommended to subclass DefaultEventLoopPolicy and override the methods for which custom behavior is wanted, e.g.:\\n\\nclass MyEventLoopPolicy(asyncio.DefaultEventLoopPolicy):\\n\\n def get_event_loop(self):\\n \"\"\"Get the event loop.\\n\\n This may be None or an instance of EventLoop.\\n \"\"\"\\n loop = super().get_event_loop()\\n # Do something with loop ...\\n return loop\\n\\nasyncio.set_event_loop_policy(MyEventLoopPolicy())\\n\\nTable of Contents\\n\\nPolicies\\n\\nGetting and Setting the Policy\\n\\nPolicy Objects\\n\\nCustom Policies\\n\\nPrevious topic\\n\\nTransports and Protocols\\n\\nNext topic\\n\\nPlatform Support\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nPolicies\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\asyncio-protocol.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nTransports and Protocols\\n\\n|\\n\\nTransports and Protocols¶\\n\\nPreface\\n\\nTransports and Protocols are used by the low-level event loop APIs such as loop.create_connection(). They use callback-based programming style and enable high-performance implementations of network or IPC protocols (e.g. HTTP).\\n\\nEssentially, transports and protocols should only be used in libraries and frameworks and never in high-level asyncio applications.\\n\\nThis documentation page covers both Transports and Protocols.\\n\\nIntroduction\\n\\nAt the highest level, the transport is concerned with how bytes are transmitted, while the protocol determines which bytes to transmit (and to some extent when).\\n\\nA different way of saying the same thing: a transport is an abstraction for a socket (or similar I/O endpoint) while a protocol is an abstraction for an application, from the transport’s point of view.\\n\\nYet another view is the transport and protocol interfaces together define an abstract interface for using network I/O and interprocess I/O.\\n\\nThere is always a 1:1 relationship between transport and protocol objects: the protocol calls transport methods to send data, while the transport calls protocol methods to pass it data that has been received.\\n\\nMost of connection oriented event loop methods (such as loop.create_connection()) usually accept a protocol_factory argument used to create a Protocol object for an accepted connection, represented by a Transport object. Such methods usually return a tuple of (transport, protocol).\\n\\nContents\\n\\nThis documentation page contains the following sections:\\n\\nThe Transports section documents asyncio BaseTransport, ReadTransport, WriteTransport, Transport, DatagramTransport, and SubprocessTransport classes.\\n\\nThe Protocols section documents asyncio BaseProtocol, Protocol, BufferedProtocol, DatagramProtocol, and SubprocessProtocol classes.\\n\\nThe Examples section showcases how to work with transports, protocols, and low-level event loop APIs.\\n\\nTransports¶\\n\\nSource code: Lib/asyncio/transports.py\\n\\nTransports are classes provided by asyncio in order to abstract various kinds of communication channels.\\n\\nTransport objects are always instantiated by an asyncio event loop.\\n\\nasyncio implements transports for TCP, UDP, SSL, and subprocess pipes. The methods available on a transport depend on the transport’s kind.\\n\\nThe transport classes are not thread safe.\\n\\nTransports Hierarchy¶\\n\\nBase Transport¶\\n\\nRead-only Transports¶\\n\\nWrite-only Transports¶\\n\\nDatagram Transports¶\\n\\nSubprocess Transports¶\\n\\nProtocols¶\\n\\nSource code: Lib/asyncio/protocols.py\\n\\nasyncio provides a set of abstract base classes that should be used to implement network protocols. Those classes are meant to be used together with transports.\\n\\nSubclasses of abstract base protocol classes may implement some or all methods. All these methods are callbacks: they are called by transports on certain events, for example when some data is received. A base protocol method should be called by the corresponding transport.\\n\\nBase Protocols¶\\n\\nBase Protocol¶\\n\\nAll asyncio protocols can implement Base Protocol callbacks.\\n\\nConnection Callbacks\\n\\nConnection callbacks are called on all protocols, exactly once per a successful connection. All other protocol callbacks can only be called between those two methods.\\n\\nFlow Control Callbacks\\n\\nFlow control callbacks can be called by transports to pause or resume writing performed by the protocol.\\n\\nSee the documentation of the set_write_buffer_limits() method for more details.\\n\\nIf the buffer size equals the high watermark, pause_writing() is not called: the buffer size must go strictly over.\\n\\nConversely, resume_writing() is called when the buffer size is equal or lower than the low watermark. These end conditions are important to ensure that things go as expected when either mark is zero.\\n\\nStreaming Protocols¶\\n\\nEvent methods, such as loop.create_server(), loop.create_unix_server(), loop.create_connection(), loop.create_unix_connection(), loop.connect_accepted_socket(), loop.connect_read_pipe(), and loop.connect_write_pipe() accept factories that return streaming protocols.\\n\\nState machine:\\n\\nstart -> connection_made\\n [-> data_received]*\\n [-> eof_received]?\\n-> connection_lost -> end\\n\\nBuffered Streaming Protocols¶\\n\\nAdded in version 3.7.\\n\\nBuffered Protocols can be used with any event loop method that supports Streaming Protocols.\\n\\nBufferedProtocol implementations allow explicit manual allocation and control of the receive buffer. Event loops can then use the buffer provided by the protocol to avoid unnecessary data copies. This can result in noticeable performance improvement for protocols that receive big amounts of data. Sophisticated protocol implementations can significantly reduce the number of buffer allocations.\\n\\nThe following callbacks are called on BufferedProtocol instances:\\n\\nget_buffer() can be called an arbitrary number of times during a connection. However, protocol.eof_received() is called at most once and, if called, get_buffer() and buffer_updated() won’t be called after it.\\n\\nState machine:\\n\\nstart -> connection_made\\n [-> get_buffer\\n [-> buffer_updated]?\\n ]*\\n [-> eof_received]?\\n-> connection_lost -> end\\n\\nDatagram Protocols¶\\n\\nDatagram Protocol instances should be constructed by protocol factories passed to the loop.create_datagram_endpoint() method.\\n\\nNote\\n\\nOn BSD systems (macOS, FreeBSD, etc.) flow control is not supported for datagram protocols, because there is no reliable way to detect send failures caused by writing too many packets.\\n\\nThe socket always appears ‘ready’ and excess packets are dropped. An OSError with errno set to errno.ENOBUFS may or may not be raised; if it is raised, it will be reported to DatagramProtocol.error_received() but otherwise ignored.\\n\\nSubprocess Protocols¶\\n\\nSubprocess Protocol instances should be constructed by protocol factories passed to the loop.subprocess_exec() and loop.subprocess_shell() methods.\\n\\nExamples¶\\n\\nTCP Echo Server¶\\n\\nCreate a TCP echo server using the loop.create_server() method, send back received data, and close the connection:\\n\\nimport asyncio\\n\\n\\nclass EchoServerProtocol(asyncio.Protocol):\\n def connection_made(self, transport):\\n peername = transport.get_extra_info(\\'peername\\')\\n print(\\'Connection from {}\\'.format(peername))\\n self.transport = transport\\n\\n def data_received(self, data):\\n message = data.decode()\\n print(\\'Data received: {!r}\\'.format(message))\\n\\n print(\\'Send: {!r}\\'.format(message))\\n self.transport.write(data)\\n\\n print(\\'Close the client socket\\')\\n self.transport.close()\\n\\n\\nasync def main():\\n # Get a reference to the event loop as we plan to use\\n # low-level APIs.\\n loop = asyncio.get_running_loop()\\n\\n server = await loop.create_server(\\n EchoServerProtocol,\\n \\'127.0.0.1\\', 8888)\\n\\n async with server:\\n await server.serve_forever()\\n\\n\\nasyncio.run(main())\\n\\nSee also\\n\\nThe TCP echo server using streams example uses the high-level asyncio.start_server() function.\\n\\nTCP Echo Client¶\\n\\nA TCP echo client using the loop.create_connection() method, sends data, and waits until the connection is closed:\\n\\nimport asyncio\\n\\n\\nclass EchoClientProtocol(asyncio.Protocol):\\n def __init__(self, message, on_con_lost):\\n self.message = message\\n self.on_con_lost = on_con_lost\\n\\n def connection_made(self, transport):\\n transport.write(self.message.encode())\\n print(\\'Data sent: {!r}\\'.format(self.message))\\n\\n def data_received(self, data):\\n print(\\'Data received: {!r}\\'.format(data.decode()))\\n\\n def connection_lost(self, exc):\\n print(\\'The server closed the connection\\')\\n self.on_con_lost.set_result(True)\\n\\n\\nasync def main():\\n # Get a reference to the event loop as we plan to use\\n # low-level APIs.\\n loop = asyncio.get_running_loop()\\n\\n on_con_lost = loop.create_future()\\n message = \\'Hello World!\\'\\n\\n transport, protocol = await loop.create_connection(\\n lambda: EchoClientProtocol(message, on_con_lost),\\n \\'127.0.0.1\\', 8888)\\n\\n # Wait until the protocol signals that the connection\\n # is lost and close the transport.\\n try:\\n await on_con_lost\\n finally:\\n transport.close()\\n\\n\\nasyncio.run(main())\\n\\nSee also\\n\\nThe TCP echo client using streams example uses the high-level asyncio.open_connection() function.\\n\\nUDP Echo Server¶\\n\\nA UDP echo server, using the loop.create_datagram_endpoint() method, sends back received data:\\n\\nimport asyncio\\n\\n\\nclass EchoServerProtocol:\\n def connection_made(self, transport):\\n self.transport = transport\\n\\n def datagram_received(self, data, addr):\\n message = data.decode()\\n print(\\'Received %r from %s\\' % (message, addr))\\n print(\\'Send %r to %s\\' % (message, addr))\\n self.transport.sendto(data, addr)\\n\\n\\nasync def main():\\n print(\"Starting UDP server\")\\n\\n # Get a reference to the event loop as we plan to use\\n # low-level APIs.\\n loop = asyncio.get_running_loop()\\n\\n # One protocol instance will be created to serve all\\n # client requests.\\n transport, protocol = await loop.create_datagram_endpoint(\\n EchoServerProtocol,\\n local_addr=(\\'127.0.0.1\\', 9999))\\n\\n try:\\n await asyncio.sleep(3600) # Serve for 1 hour.\\n finally:\\n transport.close()\\n\\n\\nasyncio.run(main())\\n\\nUDP Echo Client¶\\n\\nA UDP echo client, using the loop.create_datagram_endpoint() method, sends data and closes the transport when it receives the answer:\\n\\nimport asyncio\\n\\n\\nclass EchoClientProtocol:\\n def __init__(self, message, on_con_lost):\\n self.message = message\\n self.on_con_lost = on_con_lost\\n self.transport = None\\n\\n def connection_made(self, transport):\\n self.transport = transport\\n print(\\'Send:\\', self.message)\\n self.transport.sendto(self.message.encode())\\n\\n def datagram_received(self, data, addr):\\n print(\"Received:\", data.decode())\\n\\n print(\"Close the socket\")\\n self.transport.close()\\n\\n def error_received(self, exc):\\n print(\\'Error received:\\', exc)\\n\\n def connection_lost(self, exc):\\n print(\"Connection closed\")\\n self.on_con_lost.set_result(True)\\n\\n\\nasync def main():\\n # Get a reference to the event loop as we plan to use\\n # low-level APIs.\\n loop = asyncio.get_running_loop()\\n\\n on_con_lost = loop.create_future()\\n message = \"Hello World!\"\\n\\n transport, protocol = await loop.create_datagram_endpoint(\\n lambda: EchoClientProtocol(message, on_con_lost),\\n remote_addr=(\\'127.0.0.1\\', 9999))\\n\\n try:\\n await on_con_lost\\n finally:\\n transport.close()\\n\\n\\nasyncio.run(main())\\n\\nConnecting Existing Sockets¶\\n\\nWait until a socket receives data using the loop.create_connection() method with a protocol:\\n\\nimport asyncio\\nimport socket\\n\\n\\nclass MyProtocol(asyncio.Protocol):\\n\\n def __init__(self, on_con_lost):\\n self.transport = None\\n self.on_con_lost = on_con_lost\\n\\n def connection_made(self, transport):\\n self.transport = transport\\n\\n def data_received(self, data):\\n print(\"Received:\", data.decode())\\n\\n # We are done: close the transport;\\n # connection_lost() will be called automatically.\\n self.transport.close()\\n\\n def connection_lost(self, exc):\\n # The socket has been closed\\n self.on_con_lost.set_result(True)\\n\\n\\nasync def main():\\n # Get a reference to the event loop as we plan to use\\n # low-level APIs.\\n loop = asyncio.get_running_loop()\\n on_con_lost = loop.create_future()\\n\\n # Create a pair of connected sockets\\n rsock, wsock = socket.socketpair()\\n\\n # Register the socket to wait for data.\\n transport, protocol = await loop.create_connection(\\n lambda: MyProtocol(on_con_lost), sock=rsock)\\n\\n # Simulate the reception of data from the network.\\n loop.call_soon(wsock.send, \\'abc\\'.encode())\\n\\n try:\\n await protocol.on_con_lost\\n finally:\\n transport.close()\\n wsock.close()\\n\\nasyncio.run(main())\\n\\nSee also\\n\\nThe watch a file descriptor for read events example uses the low-level loop.add_reader() method to register an FD.\\n\\nThe register an open socket to wait for data using streams example uses high-level streams created by the open_connection() function in a coroutine.\\n\\nloop.subprocess_exec() and SubprocessProtocol¶\\n\\nAn example of a subprocess protocol used to get the output of a subprocess and to wait for the subprocess exit.\\n\\nThe subprocess is created by the loop.subprocess_exec() method:\\n\\nimport asyncio\\nimport sys\\n\\nclass DateProtocol(asyncio.SubprocessProtocol):\\n def __init__(self, exit_future):\\n self.exit_future = exit_future\\n self.output = bytearray()\\n self.pipe_closed = False\\n self.exited = False\\n\\n def pipe_connection_lost(self, fd, exc):\\n self.pipe_closed = True\\n self.check_for_exit()\\n\\n def pipe_data_received(self, fd, data):\\n self.output.extend(data)\\n\\n def process_exited(self):\\n self.exited = True\\n # process_exited() method can be called before\\n # pipe_connection_lost() method: wait until both methods are\\n # called.\\n self.check_for_exit()\\n\\n def check_for_exit(self):\\n if self.pipe_closed and self.exited:\\n self.exit_future.set_result(True)\\n\\nasync def get_date():\\n # Get a reference to the event loop as we plan to use\\n # low-level APIs.\\n loop = asyncio.get_running_loop()\\n\\n code = \\'import datetime; print(datetime.datetime.now())\\'\\n exit_future = asyncio.Future(loop=loop)\\n\\n # Create the subprocess controlled by DateProtocol;\\n # redirect the standard output into a pipe.\\n transport, protocol = await loop.subprocess_exec(\\n lambda: DateProtocol(exit_future),\\n sys.executable, \\'-c\\', code,\\n stdin=None, stderr=None)\\n\\n # Wait for the subprocess exit using the process_exited()\\n # method of the protocol.\\n await exit_future\\n\\n # Close the stdout pipe.\\n transport.close()\\n\\n # Read the output which was collected by the\\n # pipe_data_received() method of the protocol.\\n data = bytes(protocol.output)\\n return data.decode(\\'ascii\\').rstrip()\\n\\ndate = asyncio.run(get_date())\\nprint(f\"Current date: {date}\")\\n\\nSee also the same example written using high-level APIs.\\n\\nTable of Contents\\n\\nTransports and Protocols\\n\\nTransports\\n\\nTransports Hierarchy\\n\\nBase Transport\\n\\nRead-only Transports\\n\\nWrite-only Transports\\n\\nDatagram Transports\\n\\nSubprocess Transports\\n\\nProtocols\\n\\nBase Protocols\\n\\nBase Protocol\\n\\nStreaming Protocols\\n\\nBuffered Streaming Protocols\\n\\nDatagram Protocols\\n\\nSubprocess Protocols\\n\\nExamples\\n\\nTCP Echo Server\\n\\nTCP Echo Client\\n\\nUDP Echo Server\\n\\nUDP Echo Client\\n\\nConnecting Existing Sockets\\n\\nloop.subprocess_exec() and SubprocessProtocol\\n\\nPrevious topic\\n\\nFutures\\n\\nNext topic\\n\\nPolicies\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nTransports and Protocols\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\asyncio-queue.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nQueues\\n\\n|\\n\\nQueues¶\\n\\nSource code: Lib/asyncio/queues.py\\n\\nasyncio queues are designed to be similar to classes of the queue module. Although asyncio queues are not thread-safe, they are designed to be used specifically in async/await code.\\n\\nNote that methods of asyncio queues don’t have a timeout parameter; use asyncio.wait_for() function to do queue operations with a timeout.\\n\\nSee also the Examples section below.\\n\\nQueue¶\\n\\nPriority Queue¶\\n\\nLIFO Queue¶\\n\\nExceptions¶\\n\\nExamples¶\\n\\nQueues can be used to distribute workload between several concurrent tasks:\\n\\nimport asyncio\\nimport random\\nimport time\\n\\n\\nasync def worker(name, queue):\\n while True:\\n # Get a \"work item\" out of the queue.\\n sleep_for = await queue.get()\\n\\n # Sleep for the \"sleep_for\" seconds.\\n await asyncio.sleep(sleep_for)\\n\\n # Notify the queue that the \"work item\" has been processed.\\n queue.task_done()\\n\\n print(f\\'{name} has slept for {sleep_for:.2f} seconds\\')\\n\\n\\nasync def main():\\n # Create a queue that we will use to store our \"workload\".\\n queue = asyncio.Queue()\\n\\n # Generate random timings and put them into the queue.\\n total_sleep_time = 0\\n for _ in range(20):\\n sleep_for = random.uniform(0.05, 1.0)\\n total_sleep_time += sleep_for\\n queue.put_nowait(sleep_for)\\n\\n # Create three worker tasks to process the queue concurrently.\\n tasks = []\\n for i in range(3):\\n task = asyncio.create_task(worker(f\\'worker-{i}\\', queue))\\n tasks.append(task)\\n\\n # Wait until the queue is fully processed.\\n started_at = time.monotonic()\\n await queue.join()\\n total_slept_for = time.monotonic() - started_at\\n\\n # Cancel our worker tasks.\\n for task in tasks:\\n task.cancel()\\n # Wait until all worker tasks are cancelled.\\n await asyncio.gather(*tasks, return_exceptions=True)\\n\\n print(\\'====\\')\\n print(f\\'3 workers slept in parallel for {total_slept_for:.2f} seconds\\')\\n print(f\\'total expected sleep time: {total_sleep_time:.2f} seconds\\')\\n\\n\\nasyncio.run(main())\\n\\nTable of Contents\\n\\nQueues\\n\\nQueue\\n\\nPriority Queue\\n\\nLIFO Queue\\n\\nExceptions\\n\\nExamples\\n\\nPrevious topic\\n\\nSubprocesses\\n\\nNext topic\\n\\nExceptions\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nQueues\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\asyncio-runner.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nRunners\\n\\n|\\n\\nRunners¶\\n\\nSource code: Lib/asyncio/runners.py\\n\\nThis section outlines high-level asyncio primitives to run asyncio code.\\n\\nThey are built on top of an event loop with the aim to simplify async code usage for common wide-spread scenarios.\\n\\nRunning an asyncio Program¶\\n\\nRunner context manager¶\\n\\nHandling Keyboard Interruption¶\\n\\nAdded in version 3.11.\\n\\nWhen signal.SIGINT is raised by Ctrl-C, KeyboardInterrupt exception is raised in the main thread by default. However this doesn’t work with asyncio because it can interrupt asyncio internals and can hang the program from exiting.\\n\\nTo mitigate this issue, asyncio handles signal.SIGINT as follows:\\n\\nasyncio.Runner.run() installs a custom signal.SIGINT handler before any user code is executed and removes it when exiting from the function.\\n\\nThe Runner creates the main task for the passed coroutine for its execution.\\n\\nWhen signal.SIGINT is raised by Ctrl-C, the custom signal handler cancels the main task by calling asyncio.Task.cancel() which raises asyncio.CancelledError inside the main task. This causes the Python stack to unwind, try/except and try/finally blocks can be used for resource cleanup. After the main task is cancelled, asyncio.Runner.run() raises KeyboardInterrupt.\\n\\nA user could write a tight loop which cannot be interrupted by asyncio.Task.cancel(), in which case the second following Ctrl-C immediately raises the KeyboardInterrupt without cancelling the main task.\\n\\nTable of Contents\\n\\nRunners\\n\\nRunning an asyncio Program\\n\\nRunner context manager\\n\\nHandling Keyboard Interruption\\n\\nPrevious topic\\n\\nasyncio — Asynchronous I/O\\n\\nNext topic\\n\\nCoroutines and Tasks\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nRunners\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\asyncio-stream.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nStreams\\n\\n|\\n\\nStreams¶\\n\\nSource code: Lib/asyncio/streams.py\\n\\nStreams are high-level async/await-ready primitives to work with network connections. Streams allow sending and receiving data without using callbacks or low-level protocols and transports.\\n\\nHere is an example of a TCP echo client written using asyncio streams:\\n\\nimport asyncio\\n\\nasync def tcp_echo_client(message):\\n reader, writer = await asyncio.open_connection(\\n \\'127.0.0.1\\', 8888)\\n\\n print(f\\'Send: {message!r}\\')\\n writer.write(message.encode())\\n await writer.drain()\\n\\n data = await reader.read(100)\\n print(f\\'Received: {data.decode()!r}\\')\\n\\n print(\\'Close the connection\\')\\n writer.close()\\n await writer.wait_closed()\\n\\nasyncio.run(tcp_echo_client(\\'Hello World!\\'))\\n\\nSee also the Examples section below.\\n\\nStream Functions\\n\\nThe following top-level asyncio functions can be used to create and work with streams:\\n\\nUnix Sockets\\n\\nStreamReader¶\\n\\nStreamWriter¶\\n\\nExamples¶\\n\\nTCP echo client using streams¶\\n\\nTCP echo client using the asyncio.open_connection() function:\\n\\nimport asyncio\\n\\nasync def tcp_echo_client(message):\\n reader, writer = await asyncio.open_connection(\\n \\'127.0.0.1\\', 8888)\\n\\n print(f\\'Send: {message!r}\\')\\n writer.write(message.encode())\\n await writer.drain()\\n\\n data = await reader.read(100)\\n print(f\\'Received: {data.decode()!r}\\')\\n\\n print(\\'Close the connection\\')\\n writer.close()\\n await writer.wait_closed()\\n\\nasyncio.run(tcp_echo_client(\\'Hello World!\\'))\\n\\nSee also\\n\\nThe TCP echo client protocol example uses the low-level loop.create_connection() method.\\n\\nTCP echo server using streams¶\\n\\nTCP echo server using the asyncio.start_server() function:\\n\\nimport asyncio\\n\\nasync def handle_echo(reader, writer):\\n data = await reader.read(100)\\n message = data.decode()\\n addr = writer.get_extra_info(\\'peername\\')\\n\\n print(f\"Received {message!r} from {addr!r}\")\\n\\n print(f\"Send: {message!r}\")\\n writer.write(data)\\n await writer.drain()\\n\\n print(\"Close the connection\")\\n writer.close()\\n await writer.wait_closed()\\n\\nasync def main():\\n server = await asyncio.start_server(\\n handle_echo, \\'127.0.0.1\\', 8888)\\n\\n addrs = \\', \\'.join(str(sock.getsockname()) for sock in server.sockets)\\n print(f\\'Serving on {addrs}\\')\\n\\n async with server:\\n await server.serve_forever()\\n\\nasyncio.run(main())\\n\\nSee also\\n\\nThe TCP echo server protocol example uses the loop.create_server() method.\\n\\nGet HTTP headers¶\\n\\nSimple example querying HTTP headers of the URL passed on the command line:\\n\\nimport asyncio\\nimport urllib.parse\\nimport sys\\n\\nasync def print_http_headers(url):\\n url = urllib.parse.urlsplit(url)\\n if url.scheme == \\'https\\':\\n reader, writer = await asyncio.open_connection(\\n url.hostname, 443, ssl=True)\\n else:\\n reader, writer = await asyncio.open_connection(\\n url.hostname, 80)\\n\\n query = (\\n f\"HEAD {url.path or \\'/\\'} HTTP/1.0\\\\r\\\\n\"\\n f\"Host: {url.hostname}\\\\r\\\\n\"\\n f\"\\\\r\\\\n\"\\n )\\n\\n writer.write(query.encode(\\'latin-1\\'))\\n while True:\\n line = await reader.readline()\\n if not line:\\n break\\n\\n line = line.decode(\\'latin1\\').rstrip()\\n if line:\\n print(f\\'HTTP header> {line}\\')\\n\\n # Ignore the body, close the socket\\n writer.close()\\n await writer.wait_closed()\\n\\nurl = sys.argv[1]\\nasyncio.run(print_http_headers(url))\\n\\nUsage:\\n\\npython example.py http://example.com/path/page.html\\n\\nor with HTTPS:\\n\\npython example.py https://example.com/path/page.html\\n\\nRegister an open socket to wait for data using streams¶\\n\\nCoroutine waiting until a socket receives data using the open_connection() function:\\n\\nimport asyncio\\nimport socket\\n\\nasync def wait_for_data():\\n # Get a reference to the current event loop because\\n # we want to access low-level APIs.\\n loop = asyncio.get_running_loop()\\n\\n # Create a pair of connected sockets.\\n rsock, wsock = socket.socketpair()\\n\\n # Register the open socket to wait for data.\\n reader, writer = await asyncio.open_connection(sock=rsock)\\n\\n # Simulate the reception of data from the network\\n loop.call_soon(wsock.send, \\'abc\\'.encode())\\n\\n # Wait for data\\n data = await reader.read(100)\\n\\n # Got data, we are done: close the socket\\n print(\"Received:\", data.decode())\\n writer.close()\\n await writer.wait_closed()\\n\\n # Close the second socket\\n wsock.close()\\n\\nasyncio.run(wait_for_data())\\n\\nSee also\\n\\nThe register an open socket to wait for data using a protocol example uses a low-level protocol and the loop.create_connection() method.\\n\\nThe watch a file descriptor for read events example uses the low-level loop.add_reader() method to watch a file descriptor.\\n\\nTable of Contents\\n\\nStreams\\n\\nStreamReader\\n\\nStreamWriter\\n\\nExamples\\n\\nTCP echo client using streams\\n\\nTCP echo server using streams\\n\\nGet HTTP headers\\n\\nRegister an open socket to wait for data using streams\\n\\nPrevious topic\\n\\nCoroutines and Tasks\\n\\nNext topic\\n\\nSynchronization Primitives\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nStreams\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\asyncio-subprocess.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nSubprocesses\\n\\n|\\n\\nSubprocesses¶\\n\\nSource code: Lib/asyncio/subprocess.py, Lib/asyncio/base_subprocess.py\\n\\nThis section describes high-level async/await asyncio APIs to create and manage subprocesses.\\n\\nHere’s an example of how asyncio can run a shell command and obtain its result:\\n\\nimport asyncio\\n\\nasync def run(cmd):\\n proc = await asyncio.create_subprocess_shell(\\n cmd,\\n stdout=asyncio.subprocess.PIPE,\\n stderr=asyncio.subprocess.PIPE)\\n\\n stdout, stderr = await proc.communicate()\\n\\n print(f\\'[{cmd!r} exited with {proc.returncode}]\\')\\n if stdout:\\n print(f\\'[stdout]\\\\n{stdout.decode()}\\')\\n if stderr:\\n print(f\\'[stderr]\\\\n{stderr.decode()}\\')\\n\\nasyncio.run(run(\\'ls /zzz\\'))\\n\\nwill print:\\n\\n[\\'ls /zzz\\' exited with 1]\\n[stderr]\\nls: /zzz: No such file or directory\\n\\nBecause all asyncio subprocess functions are asynchronous and asyncio provides many tools to work with such functions, it is easy to execute and monitor multiple subprocesses in parallel. It is indeed trivial to modify the above example to run several commands simultaneously:\\n\\nasync def main():\\n await asyncio.gather(\\n run(\\'ls /zzz\\'),\\n run(\\'sleep 1; echo \"hello\"\\'))\\n\\nasyncio.run(main())\\n\\nSee also the Examples subsection.\\n\\nCreating Subprocesses¶\\n\\nNote\\n\\nSubprocesses are available for Windows if a ProactorEventLoop is used. See Subprocess Support on Windows for details.\\n\\nSee also\\n\\nasyncio also has the following low-level APIs to work with subprocesses: loop.subprocess_exec(), loop.subprocess_shell(), loop.connect_read_pipe(), loop.connect_write_pipe(), as well as the Subprocess Transports and Subprocess Protocols.\\n\\nConstants¶\\n\\nInteracting with Subprocesses¶\\n\\nBoth create_subprocess_exec() and create_subprocess_shell() functions return instances of the Process class. Process is a high-level wrapper that allows communicating with subprocesses and watching for their completion.\\n\\nSubprocess and Threads¶\\n\\nStandard asyncio event loop supports running subprocesses from different threads by default.\\n\\nOn Windows subprocesses are provided by ProactorEventLoop only (default), SelectorEventLoop has no subprocess support.\\n\\nNote that alternative event loop implementations might have own limitations; please refer to their documentation.\\n\\nSee also\\n\\nThe Concurrency and multithreading in asyncio section.\\n\\nExamples¶\\n\\nAn example using the Process class to control a subprocess and the StreamReader class to read from its standard output.\\n\\nThe subprocess is created by the create_subprocess_exec() function:\\n\\nimport asyncio\\nimport sys\\n\\nasync def get_date():\\n code = \\'import datetime; print(datetime.datetime.now())\\'\\n\\n # Create the subprocess; redirect the standard output\\n # into a pipe.\\n proc = await asyncio.create_subprocess_exec(\\n sys.executable, \\'-c\\', code,\\n stdout=asyncio.subprocess.PIPE)\\n\\n # Read one line of output.\\n data = await proc.stdout.readline()\\n line = data.decode(\\'ascii\\').rstrip()\\n\\n # Wait for the subprocess exit.\\n await proc.wait()\\n return line\\n\\ndate = asyncio.run(get_date())\\nprint(f\"Current date: {date}\")\\n\\nSee also the same example written using low-level APIs.\\n\\nTable of Contents\\n\\nSubprocesses\\n\\nCreating Subprocesses\\n\\nConstants\\n\\nInteracting with Subprocesses\\n\\nSubprocess and Threads\\n\\nExamples\\n\\nPrevious topic\\n\\nSynchronization Primitives\\n\\nNext topic\\n\\nQueues\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nSubprocesses\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\asyncio-sync.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nSynchronization Primitives\\n\\n|\\n\\nSynchronization Primitives¶\\n\\nSource code: Lib/asyncio/locks.py\\n\\nasyncio synchronization primitives are designed to be similar to those of the threading module with two important caveats:\\n\\nasyncio primitives are not thread-safe, therefore they should not be used for OS thread synchronization (use threading for that);\\n\\nmethods of these synchronization primitives do not accept the timeout argument; use the asyncio.wait_for() function to perform operations with timeouts.\\n\\nasyncio has the following basic synchronization primitives:\\n\\nLock\\n\\nEvent\\n\\nCondition\\n\\nSemaphore\\n\\nBoundedSemaphore\\n\\nBarrier\\n\\nLock¶\\n\\nEvent¶\\n\\nCondition¶\\n\\nSemaphore¶\\n\\nBoundedSemaphore¶\\n\\nBarrier¶\\n\\nChanged in version 3.9: Acquiring a lock using await lock or yield from lock and/or with statement (with await lock, with (yield from lock)) was removed. Use async with lock instead.\\n\\nTable of Contents\\n\\nSynchronization Primitives\\n\\nLock\\n\\nEvent\\n\\nCondition\\n\\nSemaphore\\n\\nBoundedSemaphore\\n\\nBarrier\\n\\nPrevious topic\\n\\nStreams\\n\\nNext topic\\n\\nSubprocesses\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nSynchronization Primitives\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\asyncio-task.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nCoroutines and Tasks\\n\\n|\\n\\nCoroutines and Tasks¶\\n\\nThis section outlines high-level asyncio APIs to work with coroutines and Tasks.\\n\\nCoroutines¶\\n\\nSource code: Lib/asyncio/coroutines.py\\n\\nCoroutines declared with the async/await syntax is the preferred way of writing asyncio applications. For example, the following snippet of code prints “hello”, waits 1 second, and then prints “world”:\\n\\n>>> import asyncio\\n\\n>>> async def main():\\n... print(\\'hello\\')\\n... await asyncio.sleep(1)\\n... print(\\'world\\')\\n\\n>>> asyncio.run(main())\\nhello\\nworld\\n\\nNote that simply calling a coroutine will not schedule it to be executed:\\n\\n>>> main()\\n\\n\\nTo actually run a coroutine, asyncio provides the following mechanisms:\\n\\nThe asyncio.run() function to run the top-level entry point “main()” function (see the above example.)\\n\\nAwaiting on a coroutine. The following snippet of code will print “hello” after waiting for 1 second, and then print “world” after waiting for another 2 seconds:\\n\\nimport asyncio\\nimport time\\n\\nasync def say_after(delay, what):\\n await asyncio.sleep(delay)\\n print(what)\\n\\nasync def main():\\n print(f\"started at {time.strftime(\\'%X\\')}\")\\n\\n await say_after(1, \\'hello\\')\\n await say_after(2, \\'world\\')\\n\\n print(f\"finished at {time.strftime(\\'%X\\')}\")\\n\\nasyncio.run(main())\\n\\nExpected output:\\n\\nstarted at 17:13:52\\nhello\\nworld\\nfinished at 17:13:55\\n\\nThe asyncio.create_task() function to run coroutines concurrently as asyncio Tasks.\\n\\nLet’s modify the above example and run two say_after coroutines concurrently:\\n\\nasync def main():\\n task1 = asyncio.create_task(\\n say_after(1, \\'hello\\'))\\n\\n task2 = asyncio.create_task(\\n say_after(2, \\'world\\'))\\n\\n print(f\"started at {time.strftime(\\'%X\\')}\")\\n\\n # Wait until both tasks are completed (should take\\n # around 2 seconds.)\\n await task1\\n await task2\\n\\n print(f\"finished at {time.strftime(\\'%X\\')}\")\\n\\nNote that expected output now shows that the snippet runs 1 second faster than before:\\n\\nstarted at 17:14:32\\nhello\\nworld\\nfinished at 17:14:34\\n\\nThe asyncio.TaskGroup class provides a more modern alternative to create_task(). Using this API, the last example becomes:\\n\\nasync def main():\\n async with asyncio.TaskGroup() as tg:\\n task1 = tg.create_task(\\n say_after(1, \\'hello\\'))\\n\\n task2 = tg.create_task(\\n say_after(2, \\'world\\'))\\n\\n print(f\"started at {time.strftime(\\'%X\\')}\")\\n\\n # The await is implicit when the context manager exits.\\n\\n print(f\"finished at {time.strftime(\\'%X\\')}\")\\n\\nThe timing and output should be the same as for the previous version.\\n\\nAdded in version 3.11: asyncio.TaskGroup.\\n\\nAwaitables¶\\n\\nWe say that an object is an awaitable object if it can be used in an await expression. Many asyncio APIs are designed to accept awaitables.\\n\\nThere are three main types of awaitable objects: coroutines, Tasks, and Futures.\\n\\nCoroutines\\n\\nPython coroutines are awaitables and therefore can be awaited from other coroutines:\\n\\nimport asyncio\\n\\nasync def nested():\\n return 42\\n\\nasync def main():\\n # Nothing happens if we just call \"nested()\".\\n # A coroutine object is created but not awaited,\\n # so it *won\\'t run at all*.\\n nested() # will raise a \"RuntimeWarning\".\\n\\n # Let\\'s do it differently now and await it:\\n print(await nested()) # will print \"42\".\\n\\nasyncio.run(main())\\n\\nImportant\\n\\nIn this documentation the term “coroutine” can be used for two closely related concepts:\\n\\na coroutine function: an async def function;\\n\\na coroutine object: an object returned by calling a coroutine function.\\n\\nTasks\\n\\nTasks are used to schedule coroutines concurrently.\\n\\nWhen a coroutine is wrapped into a Task with functions like asyncio.create_task() the coroutine is automatically scheduled to run soon:\\n\\nimport asyncio\\n\\nasync def nested():\\n return 42\\n\\nasync def main():\\n # Schedule nested() to run soon concurrently\\n # with \"main()\".\\n task = asyncio.create_task(nested())\\n\\n # \"task\" can now be used to cancel \"nested()\", or\\n # can simply be awaited to wait until it is complete:\\n await task\\n\\nasyncio.run(main())\\n\\nFutures\\n\\nA Future is a special low-level awaitable object that represents an eventual result of an asynchronous operation.\\n\\nWhen a Future object is awaited it means that the coroutine will wait until the Future is resolved in some other place.\\n\\nFuture objects in asyncio are needed to allow callback-based code to be used with async/await.\\n\\nNormally there is no need to create Future objects at the application level code.\\n\\nFuture objects, sometimes exposed by libraries and some asyncio APIs, can be awaited:\\n\\nasync def main():\\n await function_that_returns_a_future_object()\\n\\n # this is also valid:\\n await asyncio.gather(\\n function_that_returns_a_future_object(),\\n some_python_coroutine()\\n )\\n\\nA good example of a low-level function that returns a Future object is loop.run_in_executor().\\n\\nCreating Tasks¶\\n\\nSource code: Lib/asyncio/tasks.py\\n\\nTask Cancellation¶\\n\\nTasks can easily and safely be cancelled. When a task is cancelled, asyncio.CancelledError will be raised in the task at the next opportunity.\\n\\nIt is recommended that coroutines use try/finally blocks to robustly perform clean-up logic. In case asyncio.CancelledError is explicitly caught, it should generally be propagated when clean-up is complete. asyncio.CancelledError directly subclasses BaseException so most code will not need to be aware of it.\\n\\nThe asyncio components that enable structured concurrency, like asyncio.TaskGroup and asyncio.timeout(), are implemented using cancellation internally and might misbehave if a coroutine swallows asyncio.CancelledError. Similarly, user code should not generally call uncancel. However, in cases when suppressing asyncio.CancelledError is truly desired, it is necessary to also call uncancel() to completely remove the cancellation state.\\n\\nTask Groups¶\\n\\nTask groups combine a task creation API with a convenient and reliable way to wait for all tasks in the group to finish.\\n\\nExample:\\n\\nasync def main():\\n async with asyncio.TaskGroup() as tg:\\n task1 = tg.create_task(some_coro(...))\\n task2 = tg.create_task(another_coro(...))\\n print(f\"Both tasks have completed now: {task1.result()}, {task2.result()}\")\\n\\nThe 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 tg into one of the coroutines and calling tg.create_task() in that coroutine). Once the last task has finished and the async with block is exited, no new tasks may be added to the group.\\n\\nThe first time any of the tasks belonging to the group fails with an exception other than 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 async with statement is still active (i.e., __aexit__() hasn’t been called yet), the task directly containing the async with statement is also cancelled. The resulting asyncio.CancelledError will interrupt an await, but it will not bubble out of the containing async with statement.\\n\\nOnce all tasks have finished, if any tasks have failed with an exception other than asyncio.CancelledError, those exceptions are combined in an ExceptionGroup or BaseExceptionGroup (as appropriate; see their documentation) which is then raised.\\n\\nTwo base exceptions are treated specially: If any task fails with KeyboardInterrupt or SystemExit, the task group still cancels the remaining tasks and waits for them, but then the initial KeyboardInterrupt or SystemExit is re-raised instead of ExceptionGroup or BaseExceptionGroup.\\n\\nIf the body of the async with statement exits with an exception (so __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 __aexit__(), unless it is asyncio.CancelledError, is also included in the exception group. The same special case is made for KeyboardInterrupt and SystemExit as in the previous paragraph.\\n\\nTask groups are careful not to mix up the internal cancellation used to “wake up” their __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.\\n\\nIn the case where a task group is cancelled externally and also must raise an ExceptionGroup, it will call the parent task’s cancel() method. This ensures that a asyncio.CancelledError will be raised at the next await, so the cancellation is not lost.\\n\\nTask groups preserve the cancellation count reported by asyncio.Task.cancelling().\\n\\nChanged in version 3.13: Improved handling of simultaneous internal and external cancellations and correct preservation of cancellation counts.\\n\\nTerminating a Task Group¶\\n\\nWhile 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:\\n\\nimport asyncio\\nfrom asyncio import TaskGroup\\n\\nclass TerminateTaskGroup(Exception):\\n \"\"\"Exception raised to terminate a task group.\"\"\"\\n\\nasync def force_terminate_task_group():\\n \"\"\"Used to force termination of a task group.\"\"\"\\n raise TerminateTaskGroup()\\n\\nasync def job(task_id, sleep_time):\\n print(f\\'Task {task_id}: start\\')\\n await asyncio.sleep(sleep_time)\\n print(f\\'Task {task_id}: done\\')\\n\\nasync def main():\\n try:\\n async with TaskGroup() as group:\\n # spawn some tasks\\n group.create_task(job(1, 0.5))\\n group.create_task(job(2, 1.5))\\n # sleep for 1 second\\n await asyncio.sleep(1)\\n # add an exception-raising task to force the group to terminate\\n group.create_task(force_terminate_task_group())\\n except* TerminateTaskGroup:\\n pass\\n\\nasyncio.run(main())\\n\\nExpected output:\\n\\nTask 1: start\\nTask 2: start\\nTask 1: done\\n\\nSleeping¶\\n\\nRunning Tasks Concurrently¶\\n\\nEager Task Factory¶\\n\\nShielding From Cancellation¶\\n\\nTimeouts¶\\n\\nWaiting Primitives¶\\n\\nRunning in Threads¶\\n\\nScheduling From Other Threads¶\\n\\nIntrospection¶\\n\\nTask Object¶\\n\\nTable of Contents\\n\\nCoroutines and Tasks\\n\\nCoroutines\\n\\nAwaitables\\n\\nCreating Tasks\\n\\nTask Cancellation\\n\\nTask Groups\\n\\nTerminating a Task Group\\n\\nSleeping\\n\\nRunning Tasks Concurrently\\n\\nEager Task Factory\\n\\nShielding From Cancellation\\n\\nTimeouts\\n\\nWaiting Primitives\\n\\nRunning in Threads\\n\\nScheduling From Other Threads\\n\\nIntrospection\\n\\nTask Object\\n\\nPrevious topic\\n\\nRunners\\n\\nNext topic\\n\\nStreams\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O »\\n\\nCoroutines and Tasks\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\asyncio.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O\\n\\n|\\n\\nasyncio — Asynchronous I/O¶\\n\\nHello World!\\n\\nimport asyncio\\n\\nasync def main():\\n print(\\'Hello ...\\')\\n await asyncio.sleep(1)\\n print(\\'... World!\\')\\n\\nasyncio.run(main())\\n\\nasyncio is a library to write concurrent code using the async/await syntax.\\n\\nasyncio is used as a foundation for multiple Python asynchronous frameworks that provide high-performance network and web-servers, database connection libraries, distributed task queues, etc.\\n\\nasyncio is often a perfect fit for IO-bound and high-level structured network code.\\n\\nSee also\\n\\nasyncio provides a set of high-level APIs to:\\n\\nrun Python coroutines concurrently and have full control over their execution;\\n\\nperform network IO and IPC;\\n\\ncontrol subprocesses;\\n\\ndistribute tasks via queues;\\n\\nsynchronize concurrent code;\\n\\nAdditionally, there are low-level APIs for library and framework developers to:\\n\\ncreate and manage event loops, which provide asynchronous APIs for networking, running subprocesses, handling OS signals, etc;\\n\\nimplement efficient protocols using transports;\\n\\nbridge callback-based libraries and code with async/await syntax.\\n\\nAvailability: not WASI.\\n\\nThis module does not work or is not available on WebAssembly. See WebAssembly platforms for more information.\\n\\nasyncio REPL\\n\\nYou can experiment with an asyncio concurrent context in the REPL:\\n\\n$ python -m asyncio\\nasyncio REPL ...\\nUse \"await\" directly instead of \"asyncio.run()\".\\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\\n>>> import asyncio\\n>>> await asyncio.sleep(10, result=\\'hello\\')\\n\\'hello\\'\\n\\nThis REPL provides limited compatibility with PYTHON_BASIC_REPL. It is recommended that the default REPL is used for full functionality and the latest features.\\n\\nRaises an auditing event cpython.run_stdin with no arguments.\\n\\nChanged in version 3.12.5: (also 3.11.10, 3.10.15, 3.9.20, and 3.8.20) Emits audit events.\\n\\nChanged in version 3.13: Uses PyREPL if possible, in which case PYTHONSTARTUP is also executed. Emits audit events.\\n\\nReference\\n\\nHigh-level APIs\\n\\nRunners\\n\\nCoroutines and Tasks\\n\\nStreams\\n\\nSynchronization Primitives\\n\\nSubprocesses\\n\\nQueues\\n\\nExceptions\\n\\nCall Graph Introspection\\n\\nLow-level APIs\\n\\nEvent Loop\\n\\nFutures\\n\\nTransports and Protocols\\n\\nPolicies\\n\\nPlatform Support\\n\\nExtending\\n\\nGuides and Tutorials\\n\\nHigh-level API Index\\n\\nLow-level API Index\\n\\nDeveloping with asyncio\\n\\nNote\\n\\nThe source code for asyncio can be found in Lib/asyncio/.\\n\\nPrevious topic\\n\\nNetworking and Interprocess Communication\\n\\nNext topic\\n\\nRunners\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nasyncio — Asynchronous I/O\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\asyncore.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nRemoved Modules »\\n\\nasyncore — Asynchronous socket handler\\n\\n|\\n\\nasyncore — Asynchronous socket handler¶\\n\\nDeprecated since version 3.6, removed in version 3.12.\\n\\nThis module is no longer part of the Python standard library. It was removed in Python 3.12 after being deprecated in Python 3.6. The removal was decided in PEP 594.\\n\\nApplications should use the asyncio module instead.\\n\\nThe last version of Python that provided the asyncore module was Python 3.11.\\n\\nPrevious topic\\n\\nasynchat — Asynchronous socket command/response handler\\n\\nNext topic\\n\\naudioop — Manipulate raw audio data\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nRemoved Modules »\\n\\nasyncore — Asynchronous socket handler\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\atexit.html'}, page_content=\"Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Runtime Services »\\n\\natexit — Exit handlers\\n\\n|\\n\\natexit — Exit handlers¶\\n\\nThe atexit module defines functions to register and unregister cleanup functions. Functions thus registered are automatically executed upon normal interpreter termination. atexit runs these functions in the reverse order in which they were registered; if you register A, B, and C, at interpreter termination time they will be run in the order C, B, A.\\n\\nNote: The functions registered via this module are not called when the program is killed by a signal not handled by Python, when a Python fatal internal error is detected, or when os._exit() is called.\\n\\nNote: The effect of registering or unregistering functions from within a cleanup function is undefined.\\n\\nChanged in version 3.7: When used with C-API subinterpreters, registered functions are local to the interpreter they were registered in.\\n\\nSee also\\n\\natexit Example¶\\n\\nThe following simple example demonstrates how a module can initialize a counter from a file when it is imported and save the counter’s updated value automatically when the program terminates without relying on the application making an explicit call into this module at termination.\\n\\ntry:\\n with open('counterfile') as infile:\\n _count = int(infile.read())\\nexcept FileNotFoundError:\\n _count = 0\\n\\ndef incrcounter(n):\\n global _count\\n _count = _count + n\\n\\ndef savecounter():\\n with open('counterfile', 'w') as outfile:\\n outfile.write('%d' % _count)\\n\\nimport atexit\\n\\natexit.register(savecounter)\\n\\nPositional and keyword arguments may also be passed to register() to be passed along to the registered function when it is called:\\n\\ndef goodbye(name, adjective):\\n print('Goodbye %s, it was %s to meet you.' % (name, adjective))\\n\\nimport atexit\\n\\natexit.register(goodbye, 'Donny', 'nice')\\n# or:\\natexit.register(goodbye, adjective='nice', name='Donny')\\n\\nUsage as a decorator:\\n\\nimport atexit\\n\\n@atexit.register\\ndef goodbye():\\n print('You are now leaving the Python sector.')\\n\\nThis only works with functions that can be called without arguments.\\n\\nTable of Contents\\n\\natexit — Exit handlers\\n\\natexit Example\\n\\nPrevious topic\\n\\nabc — Abstract Base Classes\\n\\nNext topic\\n\\ntraceback — Print or retrieve a stack traceback\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Runtime Services »\\n\\natexit — Exit handlers\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.\"), Document(metadata={'source': '..\\\\..\\\\docs\\\\audioop.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nRemoved Modules »\\n\\naudioop — Manipulate raw audio data\\n\\n|\\n\\naudioop — Manipulate raw audio data¶\\n\\nDeprecated since version 3.11, removed in version 3.13.\\n\\nThis module is no longer part of the Python standard library. It was removed in Python 3.13 after being deprecated in Python 3.11. The removal was decided in PEP 594.\\n\\nThe last version of Python that provided the audioop module was Python 3.12.\\n\\nPrevious topic\\n\\nasyncore — Asynchronous socket handler\\n\\nNext topic\\n\\ncgi — Common Gateway Interface support\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nRemoved Modules »\\n\\naudioop — Manipulate raw audio data\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\audit_events.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nDebugging and profiling »\\n\\nAudit events table\\n\\n|\\n\\nAudit events table¶\\n\\nThis table contains all events raised by sys.audit() or PySys_Audit() calls throughout the CPython runtime and the standard library. These calls were added in 3.8 or later (see PEP 578).\\n\\nSee sys.addaudithook() and PySys_AddAuditHook() for information on handling these events.\\n\\nCPython implementation detail: This table is generated from the CPython documentation, and may not represent events raised by other implementations. See your runtime specific documentation for actual events raised.\\n\\nAudit event Arguments References _thread.start_new_thread function , args , kwargs [1] array.__new__ typecode , initializer [1] builtins.breakpoint breakpointhook [1] builtins.id id [1] builtins.input prompt [1] builtins.input/result result [1] code.__new__ code , filename , name , argcount , posonlyargcount , kwonlyargcount , nlocals , stacksize , flags [1] compile source , filename [1] cpython.PyConfig_Set name , value [1] cpython.PyInterpreterState_Clear [1] cpython.PyInterpreterState_New [1] cpython._PySys_ClearAuditHooks [1] cpython.remote_debugger_script script_path [1] cpython.run_command command [1] cpython.run_file filename [1] cpython.run_interactivehook hook [1] cpython.run_module module-name [1] cpython.run_startup filename [1] cpython.run_stdin [1] [2] [3] ctypes.addressof obj [1] ctypes.call_function func_pointer , arguments [1] ctypes.cdata address [1] ctypes.cdata/buffer pointer , size , offset [1] [2] ctypes.create_string_buffer init , size [1] ctypes.create_unicode_buffer init , size [1] ctypes.dlopen name [1] ctypes.dlsym library , name [1] ctypes.dlsym/handle handle , name [1] ctypes.get_errno [1] ctypes.get_last_error [1] ctypes.memoryview_at address , size , readonly [1] ctypes.set_errno errno [1] ctypes.set_exception code [1] ctypes.set_last_error error [1] ctypes.string_at ptr , size [1] ctypes.wstring_at ptr , size [1] ensurepip.bootstrap root [1] exec code_object [1] [2] fcntl.fcntl fd , cmd , arg [1] fcntl.flock fd , operation [1] fcntl.ioctl fd , request , arg [1] fcntl.lockf fd , cmd , len , start , whence [1] ftplib.connect self , host , port [1] ftplib.sendcmd self , cmd [1] [2] function.__new__ code [1] gc.get_objects generation [1] gc.get_referents objs [1] gc.get_referrers objs [1] glob.glob pathname , recursive [1] [2] glob.glob/2 pathname , recursive , root_dir , dir_fd [1] [2] http.client.connect self , host , port [1] http.client.send self , data [1] imaplib.open self , host , port [1] imaplib.send self , data [1] import module , filename , sys.path , sys.meta_path , sys.path_hooks [1] marshal.dumps value , version [1] marshal.load [1] marshal.loads bytes [1] mmap.__new__ fileno , length , access , offset [1] msvcrt.get_osfhandle fd [1] msvcrt.locking fd , mode , nbytes [1] msvcrt.open_osfhandle handle , flags [1] object.__delattr__ obj , name [1] object.__getattr__ obj , name [1] object.__setattr__ obj , name , value [1] open path , mode , flags [1] [2] [3] os.add_dll_directory path [1] os.chdir path [1] [2] os.chflags path , flags [1] [2] os.chmod path , mode , dir_fd [1] [2] [3] os.chown path , uid , gid , dir_fd [1] [2] [3] os.exec path , args , env [1] os.fork [1] os.forkpty [1] os.fwalk top , topdown , onerror , follow_symlinks , dir_fd [1] os.getxattr path , attribute [1] os.kill pid , sig [1] os.killpg pgid , sig [1] os.link src , dst , src_dir_fd , dst_dir_fd [1] os.listdir path [1] os.listdrives [1] os.listmounts volume [1] os.listvolumes [1] os.listxattr path [1] os.lockf fd , cmd , len [1] os.mkdir path , mode , dir_fd [1] [2] os.posix_spawn path , argv , env [1] [2] os.putenv key , value [1] os.remove path , dir_fd [1] [2] [3] os.removexattr path , attribute [1] os.rename src , dst , src_dir_fd , dst_dir_fd [1] [2] [3] os.rmdir path , dir_fd [1] os.scandir path [1] os.setxattr path , attribute , value , flags [1] os.spawn mode , path , args , env [1] os.startfile path , operation [1] os.startfile/2 path , operation , arguments , cwd , show_cmd [1] os.symlink src , dst , dir_fd [1] os.system command [1] os.truncate fd , length [1] [2] os.unsetenv key [1] os.utime path , times , ns , dir_fd [1] os.walk top , topdown , onerror , followlinks [1] pathlib.Path.glob self , pattern [1] pathlib.Path.rglob self , pattern [1] pdb.Pdb [1] pickle.find_class module , name [1] poplib.connect self , host , port [1] [2] poplib.putline self , line [1] [2] pty.spawn argv [1] resource.prlimit pid , resource , limits [1] resource.setrlimit resource , limits [1] setopencodehook [1] shutil.chown path , user , group [1] shutil.copyfile src , dst [1] [2] [3] shutil.copymode src , dst [1] [2] shutil.copystat src , dst [1] [2] shutil.copytree src , dst [1] shutil.make_archive base_name , format , root_dir , base_dir [1] shutil.move src , dst [1] shutil.rmtree path , dir_fd [1] shutil.unpack_archive filename , extract_dir , format [1] signal.pthread_kill thread_id , signalnum [1] smtplib.connect self , host , port [1] smtplib.send self , data [1] socket.__new__ self , family , type , protocol [1] socket.bind self , address [1] socket.connect self , address [1] [2] socket.getaddrinfo host , port , family , type , protocol [1] socket.gethostbyaddr ip_address [1] socket.gethostbyname hostname [1] [2] socket.gethostname [1] socket.getnameinfo sockaddr [1] socket.getservbyname servicename , protocolname [1] socket.getservbyport port , protocolname [1] socket.sendmsg self , address [1] socket.sendto self , address [1] socket.sethostname name [1] sqlite3.connect database [1] sqlite3.connect/handle connection_handle [1] sqlite3.enable_load_extension connection , enabled [1] sqlite3.load_extension connection , path [1] subprocess.Popen executable , args , cwd , env [1] sys._current_exceptions [1] sys._current_frames [1] sys._getframe frame [1] sys._getframemodulename depth [1] sys.addaudithook [1] [2] sys.excepthook hook , type , value , traceback [1] sys.monitoring.register_callback func [1] sys.remote_exec pid [1] sys.set_asyncgen_hooks_finalizer [1] sys.set_asyncgen_hooks_firstiter [1] sys.setprofile [1] sys.settrace [1] sys.unraisablehook hook , unraisable [1] syslog.closelog [1] syslog.openlog ident , logoption , facility [1] syslog.setlogmask maskpri [1] syslog.syslog priority , message [1] tempfile.mkdtemp fullpath [1] [2] tempfile.mkstemp fullpath [1] [2] [3] time.sleep secs [1] urllib.Request fullurl , data , headers , method [1] webbrowser.open url [1] winreg.ConnectRegistry computer_name , key [1] winreg.CreateKey key , sub_key , access [1] [2] winreg.DeleteKey key , sub_key , access [1] [2] winreg.DeleteTree key , sub_key [1] winreg.DeleteValue key , value [1] winreg.DisableReflectionKey key [1] winreg.EnableReflectionKey key [1] winreg.EnumKey key , index [1] winreg.EnumValue key , index [1] winreg.ExpandEnvironmentStrings str [1] winreg.LoadKey key , sub_key , file_name [1] winreg.OpenKey key , sub_key , access [1] winreg.OpenKey/result key [1] [2] [3] winreg.PyHKEY.Detach key [1] winreg.QueryInfoKey key [1] winreg.QueryReflectionKey key [1] winreg.QueryValue key , sub_key , value_name [1] [2] winreg.SaveKey key , file_name [1] winreg.SetValue key , sub_key , type , value [1] [2]\\n\\nThe following events are raised internally and do not correspond to any public API of CPython:\\n\\nAudit event Arguments _winapi.CreateFile file_name , desired_access , share_mode , creation_disposition , flags_and_attributes _winapi.CreateJunction src_path , dst_path _winapi.CreateNamedPipe name , open_mode , pipe_mode _winapi.CreatePipe _winapi.CreateProcess application_name , command_line , current_directory _winapi.OpenProcess process_id , desired_access _winapi.TerminateProcess handle , exit_code _posixsubprocess.fork_exec exec_list , args , env ctypes.PyObj_FromPtr obj\\n\\nAdded in version 3.14: The _posixsubprocess.fork_exec internal audit event.\\n\\nPrevious topic\\n\\nDebugging and profiling\\n\\nNext topic\\n\\nbdb — Debugger framework\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nDebugging and profiling »\\n\\nAudit events table\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\base64.html'}, page_content=\"Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nbase64 — Base16, Base32, Base64, Base85 Data Encodings\\n\\n|\\n\\nbase64 — Base16, Base32, Base64, Base85 Data Encodings¶\\n\\nSource code: Lib/base64.py\\n\\nThis module provides functions for encoding binary data to printable ASCII characters and decoding such encodings back to binary data. This includes the encodings specified in RFC 4648 (Base64, Base32 and Base16) and the non-standard Base85 encodings.\\n\\nThere are two interfaces provided by this module. The modern interface supports encoding bytes-like objects to ASCII bytes, and decoding bytes-like objects or strings containing ASCII to bytes. Both base-64 alphabets defined in RFC 4648 (normal, and URL- and filesystem-safe) are supported.\\n\\nThe legacy interface does not support decoding from strings, but it does provide functions for encoding and decoding to and from file objects. It only supports the Base64 standard alphabet, and it adds newlines every 76 characters as per RFC 2045. Note that if you are looking for RFC 2045 support you probably want to be looking at the email package instead.\\n\\nChanged in version 3.3: ASCII-only Unicode strings are now accepted by the decoding functions of the modern interface.\\n\\nChanged in version 3.4: Any bytes-like objects are now accepted by all encoding and decoding functions in this module. Ascii85/Base85 support added.\\n\\nRFC 4648 Encodings¶\\n\\nThe RFC 4648 encodings are suitable for encoding binary data so that it can be safely sent by email, used as parts of URLs, or included as part of an HTTP POST request.\\n\\nBase85 Encodings¶\\n\\nBase85 encoding is not formally specified but rather a de facto standard, thus different systems perform the encoding differently.\\n\\nThe a85encode() and 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.\\n\\nThe two functions present in this module differ in how they handle the following:\\n\\nWhether to include enclosing <~ and ~> markers\\n\\nWhether to include newline characters\\n\\nThe set of ASCII characters used for encoding\\n\\nHandling of null bytes\\n\\nRefer to the documentation of the individual functions for more information.\\n\\nLegacy Interface¶\\n\\nAn example usage of the module:\\n\\n>>> import base64\\n>>> encoded = base64.b64encode(b'data to be encoded')\\n>>> encoded\\nb'ZGF0YSB0byBiZSBlbmNvZGVk'\\n>>> data = base64.b64decode(encoded)\\n>>> data\\nb'data to be encoded'\\n\\nSecurity Considerations¶\\n\\nA new security considerations section was added to RFC 4648 (section 12); it’s recommended to review the security section for any code deployed to production.\\n\\nSee also\\n\\nTable of Contents\\n\\nbase64 — Base16, Base32, Base64, Base85 Data Encodings\\n\\nRFC 4648 Encodings\\n\\nBase85 Encodings\\n\\nLegacy Interface\\n\\nSecurity Considerations\\n\\nPrevious topic\\n\\nmimetypes — Map filenames to MIME types\\n\\nNext topic\\n\\nbinascii — Convert between binary and ASCII\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nbase64 — Base16, Base32, Base64, Base85 Data Encodings\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.\"), Document(metadata={'source': '..\\\\..\\\\docs\\\\bdb.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nDebugging and profiling »\\n\\nbdb — Debugger framework\\n\\n|\\n\\nbdb — Debugger framework¶\\n\\nSource code: Lib/bdb.py\\n\\nThe bdb module handles basic debugger functions, like setting breakpoints or managing execution via the debugger.\\n\\nThe following exception is defined:\\n\\nThe bdb module also defines two classes:\\n\\nFinally, the module defines the following functions:\\n\\nPrevious topic\\n\\nAudit events table\\n\\nNext topic\\n\\nfaulthandler — Dump the Python traceback\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nDebugging and profiling »\\n\\nbdb — Debugger framework\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\binary.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nBinary Data Services\\n\\n|\\n\\nBinary Data Services¶\\n\\nThe modules described in this chapter provide some basic services operations for manipulation of binary data. Other operations on binary data, specifically in relation to file formats and network protocols, are described in the relevant sections.\\n\\nSome libraries described under Text Processing Services also work with either ASCII-compatible binary formats (for example, re) or all binary data (for example, difflib).\\n\\nIn addition, see the documentation for Python’s built-in binary data types in Binary Sequence Types — bytes, bytearray, memoryview.\\n\\nstruct — Interpret bytes as packed binary data\\n\\nFunctions and Exceptions\\n\\nFormat Strings\\n\\nByte Order, Size, and Alignment\\n\\nFormat Characters\\n\\nExamples\\n\\nApplications\\n\\nNative Formats\\n\\nStandard Formats\\n\\nClasses\\n\\ncodecs — Codec registry and base classes\\n\\nCodec Base Classes\\n\\nError Handlers\\n\\nStateless Encoding and Decoding\\n\\nIncremental Encoding and Decoding\\n\\nIncrementalEncoder Objects\\n\\nIncrementalDecoder Objects\\n\\nStream Encoding and Decoding\\n\\nStreamWriter Objects\\n\\nStreamReader Objects\\n\\nStreamReaderWriter Objects\\n\\nStreamRecoder Objects\\n\\nEncodings and Unicode\\n\\nStandard Encodings\\n\\nPython Specific Encodings\\n\\nText Encodings\\n\\nBinary Transforms\\n\\nStandalone Codec Functions\\n\\nText Transforms\\n\\nencodings — Encodings package\\n\\nencodings.idna — Internationalized Domain Names in Applications\\n\\nencodings.mbcs — Windows ANSI codepage\\n\\nencodings.utf_8_sig — UTF-8 codec with BOM signature\\n\\nPrevious topic\\n\\nrlcompleter — Completion function for GNU readline\\n\\nNext topic\\n\\nstruct — Interpret bytes as packed binary data\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nBinary Data Services\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\binascii.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nbinascii — Convert between binary and ASCII\\n\\n|\\n\\nbinascii — Convert between binary and ASCII¶\\n\\nThe 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 base64 instead. The binascii module contains low-level functions written in C for greater speed that are used by the higher-level modules.\\n\\nNote\\n\\na2b_* functions accept Unicode strings containing only ASCII characters. Other functions only accept bytes-like objects (such as bytes, bytearray and other objects that support the buffer protocol).\\n\\nChanged in version 3.3: ASCII-only unicode strings are now accepted by the a2b_* functions.\\n\\nThe binascii module defines the following functions:\\n\\nSee also\\n\\nPrevious topic\\n\\nbase64 — Base16, Base32, Base64, Base85 Data Encodings\\n\\nNext topic\\n\\nquopri — Encode and decode MIME quoted-printable data\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nbinascii — Convert between binary and ASCII\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\bisect.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Types »\\n\\nbisect — Array bisection algorithm\\n\\n|\\n\\nbisect — Array bisection algorithm¶\\n\\nSource code: Lib/bisect.py\\n\\nThis module provides support for maintaining a list in sorted order without having to sort the list after each insertion. For long lists of items with expensive comparison operations, this can be an improvement over linear searches or frequent resorting.\\n\\nThe module is called 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 __eq__() method to determine whether a value has been found. Instead, the functions only call the __lt__() method and will return an insertion point between values in an array.\\n\\nNote\\n\\nThe functions in this module are not thread-safe. If multiple threads concurrently use 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 bisect function is operating on it, the result is undefined. For example, using insort_left() on the same list from multiple threads may result in the list becoming unsorted.\\n\\nThe following functions are provided:\\n\\nPerformance Notes¶\\n\\nWhen writing time sensitive code using bisect() and insort(), keep these thoughts in mind:\\n\\nBisection is effective for searching ranges of values. For locating specific values, dictionaries are more performant.\\n\\nThe insort() functions are O(n) because the logarithmic search step is dominated by the linear time insertion step.\\n\\nThe 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 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).\\n\\nSee also\\n\\nSorted Collections is a high performance module that uses bisect to managed sorted collections of data.\\n\\nThe SortedCollection recipe uses bisect to build a full-featured collection class with straight-forward search methods and support for a key-function. The keys are precomputed to save unnecessary calls to the key function during searches.\\n\\nSearching Sorted Lists¶\\n\\nThe above bisect functions are useful for finding insertion points but can be tricky or awkward to use for common searching tasks. The following five functions show how to transform them into the standard lookups for sorted lists:\\n\\ndef index(a, x):\\n \\'Locate the leftmost value exactly equal to x\\'\\n i = bisect_left(a, x)\\n if i != len(a) and a[i] == x:\\n return i\\n raise ValueError\\n\\ndef find_lt(a, x):\\n \\'Find rightmost value less than x\\'\\n i = bisect_left(a, x)\\n if i:\\n return a[i-1]\\n raise ValueError\\n\\ndef find_le(a, x):\\n \\'Find rightmost value less than or equal to x\\'\\n i = bisect_right(a, x)\\n if i:\\n return a[i-1]\\n raise ValueError\\n\\ndef find_gt(a, x):\\n \\'Find leftmost value greater than x\\'\\n i = bisect_right(a, x)\\n if i != len(a):\\n return a[i]\\n raise ValueError\\n\\ndef find_ge(a, x):\\n \\'Find leftmost item greater than or equal to x\\'\\n i = bisect_left(a, x)\\n if i != len(a):\\n return a[i]\\n raise ValueError\\n\\nExamples¶\\n\\nThe bisect() function can be useful for numeric table lookups. This example uses bisect() to look up a letter grade for an exam score (say) based on a set of ordered numeric breakpoints: 90 and up is an ‘A’, 80 to 89 is a ‘B’, and so on:\\n\\n>>> def grade(score)\\n... i = bisect([60, 70, 80, 90], score)\\n... return \"FDCBA\"[i]\\n...\\n>>> [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]]\\n[\\'F\\', \\'A\\', \\'C\\', \\'C\\', \\'B\\', \\'A\\', \\'A\\']\\n\\nThe bisect() and insort() functions also work with lists of tuples. The key argument can serve to extract the field used for ordering records in a table:\\n\\n>>> from collections import namedtuple\\n>>> from operator import attrgetter\\n>>> from bisect import bisect, insort\\n>>> from pprint import pprint\\n\\n>>> Movie = namedtuple(\\'Movie\\', (\\'name\\', \\'released\\', \\'director\\'))\\n\\n>>> movies = [\\n... Movie(\\'Jaws\\', 1975, \\'Spielberg\\'),\\n... Movie(\\'Titanic\\', 1997, \\'Cameron\\'),\\n... Movie(\\'The Birds\\', 1963, \\'Hitchcock\\'),\\n... Movie(\\'Aliens\\', 1986, \\'Cameron\\')\\n... ]\\n\\n>>> # Find the first movie released after 1960\\n>>> by_year = attrgetter(\\'released\\')\\n>>> movies.sort(key=by_year)\\n>>> movies[bisect(movies, 1960, key=by_year)]\\nMovie(name=\\'The Birds\\', released=1963, director=\\'Hitchcock\\')\\n\\n>>> # Insert a movie while maintaining sort order\\n>>> romance = Movie(\\'Love Story\\', 1970, \\'Hiller\\')\\n>>> insort(movies, romance, key=by_year)\\n>>> pprint(movies)\\n[Movie(name=\\'The Birds\\', released=1963, director=\\'Hitchcock\\'),\\n Movie(name=\\'Love Story\\', released=1970, director=\\'Hiller\\'),\\n Movie(name=\\'Jaws\\', released=1975, director=\\'Spielberg\\'),\\n Movie(name=\\'Aliens\\', released=1986, director=\\'Cameron\\'),\\n Movie(name=\\'Titanic\\', released=1997, director=\\'Cameron\\')]\\n\\nIf the key function is expensive, it is possible to avoid repeated function calls by searching a list of precomputed keys to find the index of a record:\\n\\n>>> data = [(\\'red\\', 5), (\\'blue\\', 1), (\\'yellow\\', 8), (\\'black\\', 0)]\\n>>> data.sort(key=lambda r: r[1]) # Or use operator.itemgetter(1).\\n>>> keys = [r[1] for r in data] # Precompute a list of keys.\\n>>> data[bisect_left(keys, 0)]\\n(\\'black\\', 0)\\n>>> data[bisect_left(keys, 1)]\\n(\\'blue\\', 1)\\n>>> data[bisect_left(keys, 5)]\\n(\\'red\\', 5)\\n>>> data[bisect_left(keys, 8)]\\n(\\'yellow\\', 8)\\n\\nTable of Contents\\n\\nbisect — Array bisection algorithm\\n\\nPerformance Notes\\n\\nSearching Sorted Lists\\n\\nExamples\\n\\nPrevious topic\\n\\nheapq — Heap queue algorithm\\n\\nNext topic\\n\\narray — Efficient arrays of numeric values\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Types »\\n\\nbisect — Array bisection algorithm\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\builtins.html'}, page_content=\"Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Runtime Services »\\n\\nbuiltins — Built-in objects\\n\\n|\\n\\nbuiltins — Built-in objects¶\\n\\nThis module provides direct access to all ‘built-in’ identifiers of Python; for example, builtins.open is the full name for the built-in function open().\\n\\nThis module is not normally accessed explicitly by most applications, but can be useful in modules that provide objects with the same name as a built-in value, but in which the built-in of that name is also needed. For example, in a module that wants to implement an open() function that wraps the built-in open(), this module can be used directly:\\n\\nimport builtins\\n\\ndef open(path):\\n f = builtins.open(path, 'r')\\n return UpperCaser(f)\\n\\nclass UpperCaser:\\n '''Wrapper around a file that converts output to uppercase.'''\\n\\n def __init__(self, f):\\n self._f = f\\n\\n def read(self, count=-1):\\n return self._f.read(count).upper()\\n\\n # ...\\n\\nAs an implementation detail, most modules have the name __builtins__ made available as part of their globals. The value of __builtins__ is normally either this module or the value of this module’s __dict__ attribute. Since this is an implementation detail, it may not be used by alternate implementations of Python.\\n\\nSee also\\n\\nBuilt-in Constants\\n\\nBuilt-in Exceptions\\n\\nBuilt-in Functions\\n\\nBuilt-in Types\\n\\nPrevious topic\\n\\nsysconfig — Provide access to Python’s configuration information\\n\\nNext topic\\n\\n__main__ — Top-level code environment\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Runtime Services »\\n\\nbuiltins — Built-in objects\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.\"), Document(metadata={'source': '..\\\\..\\\\docs\\\\bz2.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Compression and Archiving »\\n\\nbz2 — Support for bzip2 compression\\n\\n|\\n\\nbz2 — Support for bzip2 compression¶\\n\\nSource code: Lib/bz2.py\\n\\nThis module provides a comprehensive interface for compressing and decompressing data using the bzip2 compression algorithm.\\n\\nThe bz2 module contains:\\n\\nThe open() function and BZ2File class for reading and writing compressed files.\\n\\nThe BZ2Compressor and BZ2Decompressor classes for incremental (de)compression.\\n\\nThe compress() and decompress() functions for one-shot (de)compression.\\n\\nThis is an 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 Requirements for optional modules.\\n\\n(De)compression of files¶\\n\\nIncremental (de)compression¶\\n\\nOne-shot (de)compression¶\\n\\nExamples of usage¶\\n\\nBelow are some examples of typical usage of the bz2 module.\\n\\nUsing compress() and decompress() to demonstrate round-trip compression:\\n\\n>>> import bz2\\n>>> data = b\"\"\"\\\\\\n... Donec rhoncus quis sapien sit amet molestie. Fusce scelerisque vel augue\\n... nec ullamcorper. Nam rutrum pretium placerat. Aliquam vel tristique lorem,\\n... sit amet cursus ante. In interdum laoreet mi, sit amet ultrices purus\\n... pulvinar a. Nam gravida euismod magna, non varius justo tincidunt feugiat.\\n... Aliquam pharetra lacus non risus vehicula rutrum. Maecenas aliquam leo\\n... felis. Pellentesque semper nunc sit amet nibh ullamcorper, ac elementum\\n... dolor luctus. Curabitur lacinia mi ornare consectetur vestibulum.\"\"\"\\n>>> c = bz2.compress(data)\\n>>> len(data) / len(c) # Data compression ratio\\n1.513595166163142\\n>>> d = bz2.decompress(c)\\n>>> data == d # Check equality to original object after round-trip\\nTrue\\n\\nUsing BZ2Compressor for incremental compression:\\n\\n>>> import bz2\\n>>> def gen_data(chunks=10, chunksize=1000):\\n... \"\"\"Yield incremental blocks of chunksize bytes.\"\"\"\\n... for _ in range(chunks):\\n... yield b\"z\" * chunksize\\n...\\n>>> comp = bz2.BZ2Compressor()\\n>>> out = b\"\"\\n>>> for chunk in gen_data():\\n... # Provide data to the compressor object\\n... out = out + comp.compress(chunk)\\n...\\n>>> # Finish the compression process. Call this once you have\\n>>> # finished providing data to the compressor.\\n>>> out = out + comp.flush()\\n\\nThe example above uses a very “nonrandom” stream of data (a stream of b\"z\" chunks). Random data tends to compress poorly, while ordered, repetitive data usually yields a high compression ratio.\\n\\nWriting and reading a bzip2-compressed file in binary mode:\\n\\n>>> import bz2\\n>>> data = b\"\"\"\\\\\\n... Donec rhoncus quis sapien sit amet molestie. Fusce scelerisque vel augue\\n... nec ullamcorper. Nam rutrum pretium placerat. Aliquam vel tristique lorem,\\n... sit amet cursus ante. In interdum laoreet mi, sit amet ultrices purus\\n... pulvinar a. Nam gravida euismod magna, non varius justo tincidunt feugiat.\\n... Aliquam pharetra lacus non risus vehicula rutrum. Maecenas aliquam leo\\n... felis. Pellentesque semper nunc sit amet nibh ullamcorper, ac elementum\\n... dolor luctus. Curabitur lacinia mi ornare consectetur vestibulum.\"\"\"\\n>>> with bz2.open(\"myfile.bz2\", \"wb\") as f:\\n... # Write compressed data to file\\n... unused = f.write(data)\\n...\\n>>> with bz2.open(\"myfile.bz2\", \"rb\") as f:\\n... # Decompress data from file\\n... content = f.read()\\n...\\n>>> content == data # Check equality to original object after round-trip\\nTrue\\n\\nTable of Contents\\n\\nbz2 — Support for bzip2 compression\\n\\n(De)compression of files\\n\\nIncremental (de)compression\\n\\nOne-shot (de)compression\\n\\nExamples of usage\\n\\nPrevious topic\\n\\ngzip — Support for gzip files\\n\\nNext topic\\n\\nlzma — Compression using the LZMA algorithm\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Compression and Archiving »\\n\\nbz2 — Support for bzip2 compression\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\calendar.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Types »\\n\\ncalendar — General calendar-related functions\\n\\n|\\n\\ncalendar — General calendar-related functions¶\\n\\nSource code: Lib/calendar.py\\n\\nThis module allows you to output calendars like the Unix cal program, and provides additional useful functions related to the calendar. By default, these calendars have Monday as the first day of the week, and Sunday as the last (the European convention). Use setfirstweekday() to set the first day of the week to Sunday (6) or to any other weekday. Parameters that specify dates are given as integers. For related functionality, see also the datetime and time modules.\\n\\nThe functions and classes defined in this module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. This matches the definition of the “proleptic Gregorian” calendar in Dershowitz and Reingold’s book “Calendrical Calculations”, where it’s the base calendar for all computations. Zero and negative years are interpreted as prescribed by the ISO 8601 standard. Year 0 is 1 BC, year -1 is 2 BC, and so on.\\n\\nNote\\n\\nThe constructor, formatweekday() and formatmonthname() methods of these two classes temporarily change the LC_TIME locale to the given locale. Because the current locale is a process-wide setting, they are not thread-safe.\\n\\nFor simple text calendars this module provides the following functions.\\n\\nThe calendar module exports the following data attributes:\\n\\nThe calendar module defines the following exceptions:\\n\\nSee also\\n\\nCommand-line usage¶\\n\\nAdded in version 2.5.\\n\\nThe calendar module can be executed as a script from the command line to interactively print a calendar.\\n\\npython -m calendar [-h] [-L LOCALE] [-e ENCODING] [-t {text,html}]\\n [-w WIDTH] [-l LINES] [-s SPACING] [-m MONTHS] [-c CSS]\\n [-f FIRST_WEEKDAY] [year] [month]\\n\\nFor example, to print a calendar for the year 2000:\\n\\n$ python -m calendar 2000\\n 2000\\n\\n January February March\\nMo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\\n 1 2 1 2 3 4 5 6 1 2 3 4 5\\n 3 4 5 6 7 8 9 7 8 9 10 11 12 13 6 7 8 9 10 11 12\\n10 11 12 13 14 15 16 14 15 16 17 18 19 20 13 14 15 16 17 18 19\\n17 18 19 20 21 22 23 21 22 23 24 25 26 27 20 21 22 23 24 25 26\\n24 25 26 27 28 29 30 28 29 27 28 29 30 31\\n31\\n\\n April May June\\nMo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\\n 1 2 1 2 3 4 5 6 7 1 2 3 4\\n 3 4 5 6 7 8 9 8 9 10 11 12 13 14 5 6 7 8 9 10 11\\n10 11 12 13 14 15 16 15 16 17 18 19 20 21 12 13 14 15 16 17 18\\n17 18 19 20 21 22 23 22 23 24 25 26 27 28 19 20 21 22 23 24 25\\n24 25 26 27 28 29 30 29 30 31 26 27 28 29 30\\n\\n July August September\\nMo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\\n 1 2 1 2 3 4 5 6 1 2 3\\n 3 4 5 6 7 8 9 7 8 9 10 11 12 13 4 5 6 7 8 9 10\\n10 11 12 13 14 15 16 14 15 16 17 18 19 20 11 12 13 14 15 16 17\\n17 18 19 20 21 22 23 21 22 23 24 25 26 27 18 19 20 21 22 23 24\\n24 25 26 27 28 29 30 28 29 30 31 25 26 27 28 29 30\\n31\\n\\n October November December\\nMo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\\n 1 1 2 3 4 5 1 2 3\\n 2 3 4 5 6 7 8 6 7 8 9 10 11 12 4 5 6 7 8 9 10\\n 9 10 11 12 13 14 15 13 14 15 16 17 18 19 11 12 13 14 15 16 17\\n16 17 18 19 20 21 22 20 21 22 23 24 25 26 18 19 20 21 22 23 24\\n23 24 25 26 27 28 29 27 28 29 30 25 26 27 28 29 30 31\\n30 31\\n\\nThe following options are accepted:\\n\\nText-mode options:\\n\\nChanged in version 3.14: By default, today’s date is highlighted in color and can be controlled using environment variables.\\n\\nHTML-mode options:\\n\\nTable of Contents\\n\\ncalendar — General calendar-related functions\\n\\nCommand-line usage\\n\\nPrevious topic\\n\\nzoneinfo — IANA time zone support\\n\\nNext topic\\n\\ncollections — Container datatypes\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Types »\\n\\ncalendar — General calendar-related functions\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\cgi.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nRemoved Modules »\\n\\ncgi — Common Gateway Interface support\\n\\n|\\n\\ncgi — Common Gateway Interface support¶\\n\\nDeprecated since version 3.11, removed in version 3.13.\\n\\nThis module is no longer part of the Python standard library. It was removed in Python 3.13 after being deprecated in Python 3.11. The removal was decided in PEP 594.\\n\\nA fork of the module on PyPI can be used instead: legacy-cgi. This is a copy of the cgi module, no longer maintained or supported by the core Python team.\\n\\nThe last version of Python that provided the cgi module was Python 3.12.\\n\\nPrevious topic\\n\\naudioop — Manipulate raw audio data\\n\\nNext topic\\n\\ncgitb — Traceback manager for CGI scripts\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nRemoved Modules »\\n\\ncgi — Common Gateway Interface support\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\cgitb.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nRemoved Modules »\\n\\ncgitb — Traceback manager for CGI scripts\\n\\n|\\n\\ncgitb — Traceback manager for CGI scripts¶\\n\\nDeprecated since version 3.11, removed in version 3.13.\\n\\nThis module is no longer part of the Python standard library. It was removed in Python 3.13 after being deprecated in Python 3.11. The removal was decided in PEP 594.\\n\\nA fork of the module on PyPI can now be used instead: legacy-cgi. This is a copy of the cgi module, no longer maintained or supported by the core Python team.\\n\\nThe last version of Python that provided the cgitb module was Python 3.12.\\n\\nPrevious topic\\n\\ncgi — Common Gateway Interface support\\n\\nNext topic\\n\\nchunk — Read IFF chunked data\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nRemoved Modules »\\n\\ncgitb — Traceback manager for CGI scripts\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\chunk.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nRemoved Modules »\\n\\nchunk — Read IFF chunked data\\n\\n|\\n\\nchunk — Read IFF chunked data¶\\n\\nDeprecated since version 3.11, removed in version 3.13.\\n\\nThis module is no longer part of the Python standard library. It was removed in Python 3.13 after being deprecated in Python 3.11. The removal was decided in PEP 594.\\n\\nThe last version of Python that provided the chunk module was Python 3.12.\\n\\nPrevious topic\\n\\ncgitb — Traceback manager for CGI scripts\\n\\nNext topic\\n\\ncrypt — Function to check Unix passwords\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nRemoved Modules »\\n\\nchunk — Read IFF chunked data\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\cmath.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNumeric and Mathematical Modules »\\n\\ncmath — Mathematical functions for complex numbers\\n\\n|\\n\\ncmath — Mathematical functions for complex numbers¶\\n\\nThis module provides access to mathematical functions for complex numbers. The functions in this module accept integers, floating-point numbers or complex numbers as arguments. They will also accept any Python object that has either a __complex__() or a __float__() method: these methods are used to convert the object to a complex or floating-point number, respectively, and the function is then applied to the result of the conversion.\\n\\nNote\\n\\nFor 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.\\n\\nFor example, the cmath.sqrt() function has a branch cut along the negative real axis. An argument of -2-0j is treated as though it lies below the branch cut, and so gives a result on the negative imaginary axis:\\n\\n>>> cmath.sqrt(-2-0j)\\n-1.4142135623730951j\\n\\nBut an argument of -2+0j is treated as though it lies above the branch cut:\\n\\n>>> cmath.sqrt(-2+0j)\\n1.4142135623730951j\\n\\nConversions to and from polar coordinates phase(z) Return the phase of z polar(z) Return the representation of z in polar coordinates rect(r, phi) Return the complex number z with polar coordinates r and phi Power and logarithmic functions exp(z) Return e raised to the power z log(z[, base]) Return the logarithm of z to the given base ( e by default) log10(z) Return the base-10 logarithm of z sqrt(z) Return the square root of z Trigonometric functions acos(z) Return the arc cosine of z asin(z) Return the arc sine of z atan(z) Return the arc tangent of z cos(z) Return the cosine of z sin(z) Return the sine of z tan(z) Return the tangent of z Hyperbolic functions acosh(z) Return the inverse hyperbolic cosine of z asinh(z) Return the inverse hyperbolic sine of z atanh(z) Return the inverse hyperbolic tangent of z cosh(z) Return the hyperbolic cosine of z sinh(z) Return the hyperbolic sine of z tanh(z) Return the hyperbolic tangent of z Classification functions isfinite(z) Check if all components of z are finite isinf(z) Check if any component of z is infinite isnan(z) Check if any component of z is a NaN isclose(a, b, *, rel_tol, abs_tol) Check if the values a and b are close to each other Constants pi π = 3.141592… e e = 2.718281… tau τ = 2 π = 6.283185… inf Positive infinity infj Pure imaginary infinity nan “Not a number” (NaN) nanj Pure imaginary NaN\\n\\nConversions to and from polar coordinates¶\\n\\nA Python complex number z is stored internally using rectangular or Cartesian coordinates. It is completely determined by its real part z.real and its imaginary part z.imag.\\n\\nPolar coordinates give an alternative way to represent a complex number. In polar coordinates, a complex number z is defined by the modulus r and the phase angle phi. The modulus r is the distance from z to the origin, while the phase phi is the counterclockwise angle, measured in radians, from the positive x-axis to the line segment that joins the origin to z.\\n\\nThe following functions can be used to convert from the native rectangular coordinates to polar coordinates and back.\\n\\nNote\\n\\nThe modulus (absolute value) of a complex number z can be computed using the built-in abs() function. There is no separate cmath module function for this operation.\\n\\nPower and logarithmic functions¶\\n\\nTrigonometric functions¶\\n\\nHyperbolic functions¶\\n\\nClassification functions¶\\n\\nConstants¶\\n\\nNote that the selection of functions is similar, but not identical, to that in module 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 math.sqrt(-1) raise an exception than return a complex number. Also note that the functions defined in 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).\\n\\nA note on branch cuts: They are curves along which the given function fails to be continuous. They are a necessary feature of many complex functions. It is assumed that if you need to compute with complex functions, you will understand about branch cuts. Consult almost any (not too elementary) book on complex variables for enlightenment. For information of the proper choice of branch cuts for numerical purposes, a good reference should be the following:\\n\\nSee also\\n\\nKahan, W: Branch cuts for complex elementary functions; or, Much ado about nothing’s sign bit. In Iserles, A., and Powell, M. (eds.), The state of the art in numerical analysis. Clarendon Press (1987) pp165–211.\\n\\nTable of Contents\\n\\ncmath — Mathematical functions for complex numbers\\n\\nConversions to and from polar coordinates\\n\\nPower and logarithmic functions\\n\\nTrigonometric functions\\n\\nHyperbolic functions\\n\\nClassification functions\\n\\nConstants\\n\\nPrevious topic\\n\\nmath.integer — integer-specific mathematics functions\\n\\nNext topic\\n\\ndecimal — Decimal fixed-point and floating-point arithmetic\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNumeric and Mathematical Modules »\\n\\ncmath — Mathematical functions for complex numbers\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\cmd.html'}, page_content=\"Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nCommand-line interface libraries »\\n\\ncmd — Support for line-oriented command interpreters\\n\\n|\\n\\ncmd — Support for line-oriented command interpreters¶\\n\\nSource code: Lib/cmd.py\\n\\nThe Cmd class provides a simple framework for writing line-oriented command interpreters. These are often useful for test harnesses, administrative tools, and prototypes that will later be wrapped in a more sophisticated interface.\\n\\nCmd Objects¶\\n\\nA Cmd instance has the following methods:\\n\\nInstances of Cmd subclasses have some public instance variables:\\n\\nCmd Example¶\\n\\nThe cmd module is mainly useful for building custom shells that let a user work with a program interactively.\\n\\nThis section presents a simple example of how to build a shell around a few of the commands in the turtle module.\\n\\nBasic turtle commands such as forward() are added to a Cmd subclass with method named 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.\\n\\nThe example also includes a basic record and playback facility implemented with the precmd() method which is responsible for converting the input to lowercase and writing the commands to a file. The do_playback() method reads the file and adds the recorded commands to the cmdqueue for immediate playback:\\n\\nimport cmd, sys\\nfrom turtle import *\\n\\nclass TurtleShell(cmd.Cmd):\\n intro = 'Welcome to the turtle shell. Type help or ? to list commands.\\\\n'\\n prompt = '(turtle) '\\n file = None\\n\\n # ----- basic turtle commands -----\\n def do_forward(self, arg):\\n 'Move the turtle forward by the specified distance: FORWARD 10'\\n forward(*parse(arg))\\n def do_right(self, arg):\\n 'Turn turtle right by given number of degrees: RIGHT 20'\\n right(*parse(arg))\\n def do_left(self, arg):\\n 'Turn turtle left by given number of degrees: LEFT 90'\\n left(*parse(arg))\\n def do_goto(self, arg):\\n 'Move turtle to an absolute position with changing orientation. GOTO 100 200'\\n goto(*parse(arg))\\n def do_home(self, arg):\\n 'Return turtle to the home position: HOME'\\n home()\\n def do_circle(self, arg):\\n 'Draw circle with given radius an options extent and steps: CIRCLE 50'\\n circle(*parse(arg))\\n def do_position(self, arg):\\n 'Print the current turtle position: POSITION'\\n print('Current position is %d %d\\\\n' % position())\\n def do_heading(self, arg):\\n 'Print the current turtle heading in degrees: HEADING'\\n print('Current heading is %d\\\\n' % (heading(),))\\n def do_color(self, arg):\\n 'Set the color: COLOR BLUE'\\n color(arg.lower())\\n def do_undo(self, arg):\\n 'Undo (repeatedly) the last turtle action(s): UNDO'\\n def do_reset(self, arg):\\n 'Clear the screen and return turtle to center: RESET'\\n reset()\\n def do_bye(self, arg):\\n 'Stop recording, close the turtle window, and exit: BYE'\\n print('Thank you for using Turtle')\\n self.close()\\n bye()\\n return True\\n\\n # ----- record and playback -----\\n def do_record(self, arg):\\n 'Save future commands to filename: RECORD rose.cmd'\\n self.file = open(arg, 'w')\\n def do_playback(self, arg):\\n 'Playback commands from a file: PLAYBACK rose.cmd'\\n self.close()\\n with open(arg) as f:\\n self.cmdqueue.extend(f.read().splitlines())\\n def precmd(self, line):\\n line = line.lower()\\n if self.file and 'playback' not in line:\\n print(line, file=self.file)\\n return line\\n def close(self):\\n if self.file:\\n self.file.close()\\n self.file = None\\n\\ndef parse(arg):\\n 'Convert a series of zero or more numbers to an argument tuple'\\n return tuple(map(int, arg.split()))\\n\\nif __name__ == '__main__':\\n TurtleShell().cmdloop()\\n\\nHere is a sample session with the turtle shell showing the help functions, using blank lines to repeat commands, and the simple record and playback facility:\\n\\nWelcome to the turtle shell. Type help or ? to list commands.\\n\\n(turtle) ?\\n\\nDocumented commands (type help ):\\n========================================\\nbye color goto home playback record right\\ncircle forward heading left position reset undo\\n\\n(turtle) help forward\\nMove the turtle forward by the specified distance: FORWARD 10\\n(turtle) record spiral.cmd\\n(turtle) position\\nCurrent position is 0 0\\n\\n(turtle) heading\\nCurrent heading is 0\\n\\n(turtle) reset\\n(turtle) circle 20\\n(turtle) right 30\\n(turtle) circle 40\\n(turtle) right 30\\n(turtle) circle 60\\n(turtle) right 30\\n(turtle) circle 80\\n(turtle) right 30\\n(turtle) circle 100\\n(turtle) right 30\\n(turtle) circle 120\\n(turtle) right 30\\n(turtle) circle 120\\n(turtle) heading\\nCurrent heading is 180\\n\\n(turtle) forward 100\\n(turtle)\\n(turtle) right 90\\n(turtle) forward 100\\n(turtle)\\n(turtle) right 90\\n(turtle) forward 400\\n(turtle) right 90\\n(turtle) forward 500\\n(turtle) right 90\\n(turtle) forward 400\\n(turtle) right 90\\n(turtle) forward 300\\n(turtle) playback spiral.cmd\\nCurrent position is 0 0\\n\\nCurrent heading is 0\\n\\nCurrent heading is 180\\n\\n(turtle) bye\\nThank you for using Turtle\\n\\nTable of Contents\\n\\ncmd — Support for line-oriented command interpreters\\n\\nCmd Objects\\n\\nCmd Example\\n\\nPrevious topic\\n\\ncurses.panel — A panel stack extension for curses\\n\\nNext topic\\n\\nConcurrent Execution\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nCommand-line interface libraries »\\n\\ncmd — Support for line-oriented command interpreters\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.\"), Document(metadata={'source': '..\\\\..\\\\docs\\\\cmdline.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nModules command-line interface (CLI)\\n\\n|\\n\\nModules command-line interface (CLI)¶\\n\\nThe following modules have a command-line interface.\\n\\nast\\n\\nasyncio\\n\\nbase64\\n\\ncalendar\\n\\ncode\\n\\ncompileall\\n\\ncProfile: see profiling.tracing\\n\\ndis\\n\\ndoctest\\n\\nencodings.rot_13\\n\\nensurepip\\n\\nfilecmp\\n\\nfileinput\\n\\nftplib\\n\\ngzip\\n\\nhttp.server\\n\\nidlelib\\n\\ninspect\\n\\njson\\n\\nmimetypes\\n\\npdb\\n\\npickle\\n\\npickletools\\n\\nplatform\\n\\npoplib\\n\\nprofiling.sampling\\n\\nprofiling.tracing\\n\\npstats\\n\\npy_compile\\n\\npyclbr\\n\\npydoc\\n\\nquopri\\n\\nrandom\\n\\nrunpy\\n\\nsite\\n\\nsqlite3\\n\\nsymtable\\n\\nsysconfig\\n\\ntabnanny\\n\\ntarfile\\n\\nthis\\n\\ntimeit\\n\\ntokenize\\n\\ntrace\\n\\nturtledemo\\n\\nunittest\\n\\nuuid\\n\\nvenv\\n\\nwebbrowser\\n\\nzipapp\\n\\nzipfile\\n\\nSee also the Python command-line interface.\\n\\nPrevious topic\\n\\nsyslog — Unix syslog library routines\\n\\nNext topic\\n\\nSuperseded modules\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nModules command-line interface (CLI)\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\cmdlinelibs.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nCommand-line interface libraries\\n\\n|\\n\\nCommand-line interface libraries¶\\n\\nThe modules described in this chapter assist with implementing command line and terminal interfaces for applications.\\n\\nHere’s an overview:\\n\\nargparse — Parser for command-line options, arguments and subcommands\\n\\noptparse — Parser for command line options\\n\\ngetpass — Portable password input\\n\\nfileinput — Iterate over lines from multiple input streams\\n\\ncurses — Terminal handling for character-cell displays\\n\\ncurses.textpad — Text input widget for curses programs\\n\\ncurses.ascii — Utilities for ASCII characters\\n\\ncurses.panel — A panel stack extension for curses\\n\\ncmd — Support for line-oriented command interpreters\\n\\nPrevious topic\\n\\nctypes — A foreign function library for Python\\n\\nNext topic\\n\\nargparse — Parser for command-line options, arguments and subcommands\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nCommand-line interface libraries\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\code.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nCustom Python Interpreters »\\n\\ncode — Interpreter base classes\\n\\n|\\n\\ncode — Interpreter base classes¶\\n\\nSource code: Lib/code.py\\n\\nThe code module provides facilities to implement read-eval-print loops in Python. Two classes and convenience functions are included which can be used to build applications which provide an interactive interpreter prompt.\\n\\nInteractive Interpreter Objects¶\\n\\nInteractive Console Objects¶\\n\\nThe InteractiveConsole class is a subclass of InteractiveInterpreter, and so offers all the methods of the interpreter objects as well as the following additions.\\n\\nTable of Contents\\n\\ncode — Interpreter base classes\\n\\nInteractive Interpreter Objects\\n\\nInteractive Console Objects\\n\\nPrevious topic\\n\\nCustom Python Interpreters\\n\\nNext topic\\n\\ncodeop — Compile Python code\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nCustom Python Interpreters »\\n\\ncode — Interpreter base classes\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\codecs.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nBinary Data Services »\\n\\ncodecs — Codec registry and base classes\\n\\n|\\n\\ncodecs — Codec registry and base classes¶\\n\\nSource code: Lib/codecs.py\\n\\nThis module defines base classes for standard Python codecs (encoders and decoders) and provides access to the internal Python codec registry, which manages the codec and error handling lookup process. Most standard codecs are text encodings, which encode text to bytes (and decode bytes to text), but there are also codecs provided that encode text to text, and bytes to bytes. Custom codecs may encode and decode between arbitrary types, but some module features are restricted to be used specifically with text encodings or with codecs that encode to bytes.\\n\\nThe module defines the following functions for encoding and decoding with any codec:\\n\\nThe full details for each codec can also be looked up directly:\\n\\nTo simplify access to the various codec components, the module provides these additional functions which use lookup() for the codec lookup:\\n\\nCustom codecs are made available by registering a suitable codec search function:\\n\\nWhile the builtin open() and the associated io module are the recommended approach for working with encoded text files, this module provides additional utility functions and classes that allow the use of a wider range of codecs when working with binary files:\\n\\nThe module also provides the following constants which are useful for reading and writing to platform dependent files:\\n\\nCodec Base Classes¶\\n\\nThe 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.\\n\\nEach codec has to define four interfaces to make it usable as codec in Python: stateless encoder, stateless decoder, stream reader and stream writer. The stream reader and writers typically reuse the stateless encoder/decoder to implement the file protocols. Codec authors also need to define how the codec will handle encoding and decoding errors.\\n\\nError Handlers¶\\n\\nTo simplify and standardize error handling, codecs may implement different error handling schemes by accepting the errors string argument:\\n\\n>>> \\'German ß, ♬\\'.encode(encoding=\\'ascii\\', errors=\\'backslashreplace\\')\\nb\\'German \\\\\\\\xdf, \\\\\\\\u266c\\'\\n>>> \\'German ß, ♬\\'.encode(encoding=\\'ascii\\', errors=\\'xmlcharrefreplace\\')\\nb\\'German ß, ♬\\'\\n\\nThe following error handlers can be used with all Python Standard Encodings codecs:\\n\\nValue Meaning \\'strict\\' Raise UnicodeError (or a subclass),\\nthis is the default. Implemented in strict_errors() . \\'ignore\\' Ignore the malformed data and continue without\\nfurther notice. Implemented in ignore_errors() . \\'replace\\' Replace with a replacement marker. On\\nencoding, use ? (ASCII character). On\\ndecoding, use � (U+FFFD, the official\\nREPLACEMENT CHARACTER). Implemented in replace_errors() . \\'backslashreplace\\' Replace with backslashed escape sequences.\\nOn encoding, use hexadecimal form of Unicode\\ncode point with formats \\\\x hh \\\\u xxxx \\\\U xxxxxxxx .\\nOn decoding, use hexadecimal form of byte\\nvalue with format \\\\x hh .\\nImplemented in backslashreplace_errors() . \\'surrogateescape\\' On decoding, replace byte with individual\\nsurrogate code ranging from U+DC80 to U+DCFF . This code will then be turned\\nback into the same byte when the \\'surrogateescape\\' error handler is used\\nwhen encoding the data. (See PEP 383 for\\nmore.)\\n\\nThe following error handlers are only applicable to encoding (within text encodings):\\n\\nValue Meaning \\'xmlcharrefreplace\\' Replace with XML/HTML numeric character\\nreference, which is a decimal form of Unicode\\ncode point with format &# num ; .\\nImplemented in xmlcharrefreplace_errors() . \\'namereplace\\' Replace with \\\\N{...} escape sequences,\\nwhat appears in the braces is the Name\\nproperty from Unicode Character Database.\\nImplemented in namereplace_errors() .\\n\\nIn addition, the following error handler is specific to the given codecs:\\n\\nValue Codecs Meaning \\'surrogatepass\\' utf-8, utf-16, utf-32,\\nutf-16-be, utf-16-le,\\nutf-32-be, utf-32-le Allow encoding and decoding surrogate code\\npoint ( U+D800 - U+DFFF ) as normal\\ncode point. Otherwise these codecs treat\\nthe presence of surrogate code point in str as an error.\\n\\nAdded in version 3.1: The \\'surrogateescape\\' and \\'surrogatepass\\' error handlers.\\n\\nChanged in version 3.4: The \\'surrogatepass\\' error handler now works with utf-16* and utf-32* codecs.\\n\\nAdded in version 3.5: The \\'namereplace\\' error handler.\\n\\nChanged in version 3.5: The \\'backslashreplace\\' error handler now works with decoding and translating.\\n\\nThe set of allowed values can be extended by registering a new named error handler:\\n\\nPreviously registered error handlers (including the standard error handlers) can be looked up by name:\\n\\nThe following standard error handlers are also made available as module level functions:\\n\\nStateless Encoding and Decoding¶\\n\\nThe base Codec class defines these methods which also define the function interfaces of the stateless encoder and decoder:\\n\\nIncremental Encoding and Decoding¶\\n\\nThe IncrementalEncoder and IncrementalDecoder classes provide the basic interface for incremental encoding and decoding. Encoding/decoding the input isn’t done with one call to the stateless encoder/decoder function, but with multiple calls to the encode()/decode() method of the incremental encoder/decoder. The incremental encoder/decoder keeps track of the encoding/decoding process during method calls.\\n\\nThe joined output of calls to the encode()/decode() method is the same as if all the single inputs were joined into one, and this input was encoded/decoded with the stateless encoder/decoder.\\n\\nIncrementalEncoder Objects¶\\n\\nThe IncrementalEncoder class is used for encoding an input in multiple steps. It defines the following methods which every incremental encoder must define in order to be compatible with the Python codec registry.\\n\\nIncrementalDecoder Objects¶\\n\\nThe IncrementalDecoder class is used for decoding an input in multiple steps. It defines the following methods which every incremental decoder must define in order to be compatible with the Python codec registry.\\n\\nStream Encoding and Decoding¶\\n\\nThe StreamWriter and StreamReader classes provide generic working interfaces which can be used to implement new encoding submodules very easily. See encodings.utf_8 for an example of how this is done.\\n\\nStreamWriter Objects¶\\n\\nThe StreamWriter class is a subclass of Codec and defines the following methods which every stream writer must define in order to be compatible with the Python codec registry.\\n\\nIn addition to the above methods, the StreamWriter must also inherit all other methods and attributes from the underlying stream.\\n\\nStreamReader Objects¶\\n\\nThe StreamReader class is a subclass of Codec and defines the following methods which every stream reader must define in order to be compatible with the Python codec registry.\\n\\nIn addition to the above methods, the StreamReader must also inherit all other methods and attributes from the underlying stream.\\n\\nStreamReaderWriter Objects¶\\n\\nThe StreamReaderWriter is a convenience class that allows wrapping streams which work in both read and write modes.\\n\\nThe design is such that one can use the factory functions returned by the lookup() function to construct the instance.\\n\\nStreamReaderWriter instances define the combined interfaces of StreamReader and StreamWriter classes. They inherit all other methods and attributes from the underlying stream.\\n\\nStreamRecoder Objects¶\\n\\nThe StreamRecoder translates data from one encoding to another, which is sometimes useful when dealing with different encoding environments.\\n\\nThe design is such that one can use the factory functions returned by the lookup() function to construct the instance.\\n\\nStreamRecoder instances define the combined interfaces of StreamReader and StreamWriter classes. They inherit all other methods and attributes from the underlying stream.\\n\\nEncodings and Unicode¶\\n\\nStrings are stored internally as sequences of code points in range U+0000–U+10FFFF. (See PEP 393 for more details about the implementation.) Once a string object is used outside of CPU and memory, endianness and how these arrays are stored as bytes become an issue. As with other codecs, serialising 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 serialisation codecs, which are collectivity referred to as text encodings.\\n\\nThe simplest text encoding (called \\'latin-1\\' or \\'iso-8859-1\\') maps the code points 0–255 to the bytes 0x0–0xff, which means that a string object that contains code points above U+00FF can’t be encoded with this codec. Doing so will raise a UnicodeEncodeError that looks like the following (although the details of the error message may differ): UnicodeEncodeError: \\'latin-1\\' codec can\\'t encode character \\'\\\\u1234\\' in position 3: ordinal not in range(256).\\n\\nThere’s another group of encodings (the so called charmap encodings) that choose a different subset of all Unicode code points and how these code points are mapped to the bytes 0x0–0xff. To see how this is done simply open e.g. encodings/cp1252.py (which is an encoding that is used primarily on Windows). There’s a string constant with 256 characters that shows you which character is mapped to which byte value.\\n\\nAll 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 UTF-32-BE and UTF-32-LE respectively. Their disadvantage is that if, for example, you use UTF-32-BE on a little endian machine you will always have to swap bytes on encoding and decoding. Python’s UTF-16 and 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 UTF-16 or UTF-32 byte sequence, a BOM (“Byte Order Mark”) is used. This is the Unicode character U+FEFF. This character can be prepended to every UTF-16 or UTF-32 byte sequence. The byte swapped version of this character (0xFFFE) is an illegal character that may not appear in a Unicode text. When the first character of a UTF-16 or UTF-32 byte sequence is U+FFFE, the bytes have to be swapped on decoding.\\n\\nUnfortunately the character U+FEFF had a second purpose as a 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 U+FEFF as a ZERO WIDTH NO-BREAK SPACE has been deprecated (with U+2060 (WORD JOINER) assuming this role). Nevertheless Unicode software still must be able to handle 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 ZERO WIDTH NO-BREAK SPACE it’s a normal character that will be decoded like any other.\\n\\nThere’s another encoding that is able to encode the full range of Unicode characters: UTF-8. UTF-8 is an 8-bit encoding, which means there are no issues with byte order in UTF-8. Each byte in a UTF-8 byte sequence consists of two parts: marker bits (the most significant bits) and payload bits. The marker bits are a sequence of zero to four 1 bits followed by a 0 bit. Unicode characters are encoded like this (with x being payload bits, which when concatenated give the Unicode character):\\n\\nRange Encoding U-00000000 … U-0000007F 0xxxxxxx U-00000080 … U-000007FF 110xxxxx 10xxxxxx U-00000800 … U-0000FFFF 1110xxxx 10xxxxxx 10xxxxxx U-00010000 … U-0010FFFF 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\\n\\nThe least significant bit of the Unicode character is the rightmost x bit.\\n\\nAs UTF-8 is an 8-bit encoding no BOM is required and any U+FEFF character in the decoded string (even if it’s the first character) is treated as a ZERO WIDTH NO-BREAK SPACE.\\n\\nWithout external information it’s impossible to reliably determine which encoding was used for encoding a string. Each charmap encoding can decode any random byte sequence. However that’s not possible with UTF-8, as UTF-8 byte sequences have a structure that doesn’t allow arbitrary byte sequences. To increase the reliability with which a UTF-8 encoding can be detected, Microsoft invented a variant of UTF-8 (that Python calls \"utf-8-sig\") for its Notepad program: Before any of the Unicode characters is written to the file, a UTF-8 encoded BOM (which looks like this as a byte sequence: 0xef, 0xbb, 0xbf) is written. As it’s rather improbable that any charmap encoded file starts with these byte values (which would e.g. map to\\n\\nLATIN SMALL LETTER I WITH DIAERESIS\\n\\nRIGHT-POINTING DOUBLE ANGLE QUOTATION MARK\\n\\nINVERTED QUESTION MARK\\n\\nin iso-8859-1), this increases the probability that a utf-8-sig encoding can be correctly guessed from the byte sequence. So here the BOM is not used to be able to determine the byte order used for generating the byte sequence, but as a signature that helps in guessing the encoding. On encoding the utf-8-sig codec will write 0xef, 0xbb, 0xbf as the first three bytes to the file. On decoding utf-8-sig will skip those three bytes if they appear as the first three bytes in the file. In UTF-8, the use of the BOM is discouraged and should generally be avoided.\\n\\nStandard Encodings¶\\n\\nPython 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 space or a hyphen instead of an underscore are also valid aliases because they are equivalent when normalized by normalize_encoding(). For example, \\'utf-8\\' is a valid alias for the \\'utf_8\\' codec.\\n\\nNote\\n\\nThe below table lists the most common aliases, for a complete list refer to the source aliases.py file.\\n\\nOn Windows, cpXXX codecs are available for all code pages. But only codecs listed in the following table are guaranteed to exist on other platforms.\\n\\nCPython implementation detail: Some common encodings can bypass the codecs lookup machinery to improve performance. These optimization opportunities are only recognized by CPython for a limited set of (case insensitive) aliases: utf-8, utf8, latin-1, latin1, iso-8859-1, iso8859-1, mbcs (Windows only), ascii, us-ascii, utf-16, utf16, utf-32, utf32, and the same using underscores instead of dashes. Using alternative aliases for these encodings may result in slower execution.\\n\\nChanged in version 3.6: Optimization opportunity recognized for us-ascii.\\n\\nMany of the character sets support the same languages. They vary in individual characters (e.g. whether the EURO SIGN is supported or not), and in the assignment of characters to code positions. For the European languages in particular, the following variants typically exist:\\n\\nan ISO 8859 codeset\\n\\na Microsoft Windows code page, which is typically derived from an 8859 codeset, but replaces control characters with additional graphic characters\\n\\nan IBM EBCDIC code page\\n\\nan IBM PC code page, which is ASCII compatible\\n\\nCodec Aliases Languages ascii 646, us-ascii English big5 big5-tw, csbig5 Traditional Chinese big5hkscs big5-hkscs, hkscs Traditional Chinese cp037 IBM037, IBM039 English cp273 273, IBM273, csIBM273 German Added in version 3.4. cp424 EBCDIC-CP-HE, IBM424 Hebrew cp437 437, IBM437 English cp500 EBCDIC-CP-BE, EBCDIC-CP-CH,\\nIBM500 Western Europe cp720 Arabic cp737 Greek cp775 IBM775 Baltic languages cp850 850, IBM850 Western Europe cp852 852, IBM852 Central and Eastern Europe cp855 855, IBM855 Belarusian, Bulgarian,\\nMacedonian, Russian, Serbian cp856 Hebrew cp857 857, IBM857 Turkish cp858 858, IBM858 Western Europe cp860 860, IBM860 Portuguese cp861 861, CP-IS, IBM861 Icelandic cp862 862, IBM862 Hebrew cp863 863, IBM863 Canadian cp864 IBM864 Arabic cp865 865, IBM865 Danish, Norwegian cp866 866, IBM866 Russian cp869 869, CP-GR, IBM869 Greek cp874 Thai cp875 Greek cp932 932, ms932, mskanji, ms-kanji,\\nwindows-31j Japanese cp949 949, ms949, uhc Korean cp950 950, ms950 Traditional Chinese cp1006 Urdu cp1026 ibm1026 Turkish cp1125 1125, ibm1125, cp866u, ruscii Ukrainian Added in version 3.4. cp1140 ibm1140 Western Europe cp1250 windows-1250 Central and Eastern Europe cp1251 windows-1251 Belarusian, Bulgarian,\\nMacedonian, Russian, Serbian cp1252 windows-1252 Western Europe cp1253 windows-1253 Greek cp1254 windows-1254 Turkish cp1255 windows-1255 Hebrew cp1256 windows-1256 Arabic cp1257 windows-1257 Baltic languages cp1258 windows-1258 Vietnamese euc_jp eucjp, ujis, u-jis Japanese euc_jis_2004 jisx0213, eucjis2004 Japanese euc_jisx0213 eucjisx0213 Japanese euc_kr euckr, korean, ksc5601,\\nks_c-5601, ks_c-5601-1987,\\nksx1001, ks_x-1001 Korean gb2312 chinese, csiso58gb231280,\\neuc-cn, euccn, eucgb2312-cn,\\ngb2312-1980, gb2312-80,\\niso-ir-58 Simplified Chinese gbk 936, cp936, ms936 Unified Chinese gb18030 gb18030-2000 Unified Chinese hz hzgb, hz-gb, hz-gb-2312 Simplified Chinese iso2022_jp csiso2022jp, iso2022jp,\\niso-2022-jp Japanese iso2022_jp_1 iso2022jp-1, iso-2022-jp-1 Japanese iso2022_jp_2 iso2022jp-2, iso-2022-jp-2 Japanese, Korean, Simplified\\nChinese, Western Europe, Greek iso2022_jp_2004 iso2022jp-2004,\\niso-2022-jp-2004 Japanese iso2022_jp_3 iso2022jp-3, iso-2022-jp-3 Japanese iso2022_jp_ext iso2022jp-ext, iso-2022-jp-ext Japanese iso2022_kr csiso2022kr, iso2022kr,\\niso-2022-kr Korean latin_1 iso-8859-1, iso8859-1, 8859,\\ncp819, latin, latin1, L1 Western Europe iso8859_2 iso-8859-2, latin2, L2 Central and Eastern Europe iso8859_3 iso-8859-3, latin3, L3 Esperanto, Maltese iso8859_4 iso-8859-4, latin4, L4 Northern Europe iso8859_5 iso-8859-5, cyrillic Belarusian, Bulgarian,\\nMacedonian, Russian, Serbian iso8859_6 iso-8859-6, arabic Arabic iso8859_7 iso-8859-7, greek, greek8 Greek iso8859_8 iso-8859-8, hebrew Hebrew iso8859_9 iso-8859-9, latin5, L5 Turkish iso8859_10 iso-8859-10, latin6, L6 Nordic languages iso8859_11 iso-8859-11, thai Thai languages iso8859_13 iso-8859-13, latin7, L7 Baltic languages iso8859_14 iso-8859-14, latin8, L8 Celtic languages iso8859_15 iso-8859-15, latin9, L9 Western Europe iso8859_16 iso-8859-16, latin10, L10 South-Eastern Europe johab cp1361, ms1361 Korean koi8_r Russian koi8_t Tajik Added in version 3.5. koi8_u Ukrainian kz1048 kz_1048, strk1048_2002, rk1048 Kazakh Added in version 3.5. mac_cyrillic maccyrillic Belarusian, Bulgarian,\\nMacedonian, Russian, Serbian mac_greek macgreek Greek mac_iceland maciceland Icelandic mac_latin2 maclatin2, maccentraleurope,\\nmac_centeuro Central and Eastern Europe mac_roman macroman, macintosh Western Europe mac_turkish macturkish Turkish ptcp154 csptcp154, pt154, cp154,\\ncyrillic-asian Kazakh shift_jis csshiftjis, shiftjis, sjis,\\ns_jis Japanese shift_jis_2004 shiftjis2004, sjis_2004,\\nsjis2004 Japanese shift_jisx0213 shiftjisx0213, sjisx0213,\\ns_jisx0213 Japanese utf_32 U32, utf32 all languages utf_32_be UTF-32BE all languages utf_32_le UTF-32LE all languages utf_16 U16, utf16 all languages utf_16_be UTF-16BE all languages utf_16_le UTF-16LE all languages utf_7 U7, unicode-1-1-utf-7 all languages utf_8 U8, UTF, utf8, cp65001 all languages utf_8_sig utf8-sig all languages\\n\\nChanged in version 3.4: The utf-16* and utf-32* encoders no longer allow surrogate code points (U+D800–U+DFFF) to be encoded. The utf-32* decoders no longer decode byte sequences that correspond to surrogate code points.\\n\\nChanged in version 3.8: cp65001 is now an alias to utf_8.\\n\\nChanged in version 3.14: On Windows, cpXXX codecs are now available for all code pages.\\n\\nPython Specific Encodings¶\\n\\nA number of predefined codecs are specific to Python, so their codec names have no meaning outside Python. These are listed in the tables below based on the expected input and output types (note that while text encodings are the most common use case for codecs, the underlying codec infrastructure supports arbitrary data transforms rather than just text encodings). For asymmetric codecs, the stated meaning describes the encoding direction.\\n\\nText Encodings¶\\n\\nThe following codecs provide str to bytes encoding and bytes-like object to str decoding, similar to the Unicode text encodings.\\n\\nCodec Aliases Meaning idna Implement RFC 3490 ,\\nsee also encodings.idna .\\nOnly errors=\\'strict\\' is supported. mbcs ansi,\\ndbcs Windows only: Encode the\\noperand according to the\\nANSI codepage (CP_ACP). oem Windows only: Encode the\\noperand according to the\\nOEM codepage (CP_OEMCP). Added in version 3.6. palmos Encoding of PalmOS 3.5. punycode Implement RFC 3492 .\\nStateful codecs are not\\nsupported. raw_unicode_escape Latin-1 encoding with \\\\u XXXX and \\\\U XXXXXXXX for other code points.\\nExisting\\nbackslashes are not\\nescaped in any way.\\nIt is used in the Python\\npickle protocol. undefined This Codec should only\\nbe used for testing\\npurposes. Raise an exception for\\nall conversions, even\\nempty strings. The error\\nhandler is ignored. unicode_escape Encoding suitable as the\\ncontents of a Unicode\\nliteral in ASCII-encoded\\nPython source code,\\nexcept that quotes are\\nnot escaped. Decode\\nfrom Latin-1 source code.\\nBeware that Python source\\ncode actually uses UTF-8\\nby default.\\n\\nChanged in version 3.8: “unicode_internal” codec is removed.\\n\\nBinary Transforms¶\\n\\nThe following codecs provide binary transforms: bytes-like object to bytes mappings. They are not supported by bytes.decode() (which only produces str output).\\n\\nCodec Aliases Meaning Encoder / decoder base64_codec [ 1 ] base64, base_64 Convert the operand to\\nmultiline MIME base64 (the\\nresult always includes a\\ntrailing \\'\\\\n\\' ). Changed in version 3.4: accepts any bytes-like object as input for encoding and\\ndecoding base64.encodebytes() / base64.decodebytes() bz2_codec bz2 Compress the operand using\\nbz2. bz2.compress() / bz2.decompress() hex_codec hex Convert the operand to\\nhexadecimal\\nrepresentation, with two\\ndigits per byte. binascii.b2a_hex() / binascii.a2b_hex() quopri_codec quopri,\\nquotedprintable,\\nquoted_printable Convert the operand to MIME\\nquoted printable. quopri.encode() with quotetabs=True / quopri.decode() uu_codec uu Convert the operand using\\nuuencode. zlib_codec zip, zlib Compress the operand using\\ngzip. zlib.compress() / zlib.decompress()\\n\\n[1]\\n\\nIn addition to bytes-like objects, \\'base64_codec\\' also accepts ASCII-only instances of str for decoding\\n\\nAdded in version 3.2: Restoration of the binary transforms.\\n\\nChanged in version 3.4: Restoration of the aliases for the binary transforms.\\n\\nStandalone Codec Functions¶\\n\\nThe following functions provide encoding and decoding functionality similar to codecs, but are not available as named codecs through codecs.encode() or codecs.decode(). They are used internally (for example, by pickle) and behave similarly to the string_escape codec that was removed in Python 3.\\n\\nText Transforms¶\\n\\nThe following codec provides a text transform: a str to str mapping. It is not supported by str.encode() (which only produces bytes output).\\n\\nCodec Aliases Meaning rot_13 rot13 Return the Caesar-cypher\\nencryption of the\\noperand.\\n\\nAdded in version 3.2: Restoration of the rot_13 text transform.\\n\\nChanged in version 3.4: Restoration of the rot13 alias.\\n\\nencodings — Encodings package¶\\n\\nThis module implements the following functions:\\n\\nNote\\n\\nThe following functions should not be used directly, except for testing purposes; codecs.lookup() should be used instead.\\n\\nThis module implements the following exception:\\n\\nencodings.idna — Internationalized Domain Names in Applications¶\\n\\nThis module implements RFC 3490 (Internationalized Domain Names in Applications) and RFC 3492 (Nameprep: A Stringprep Profile for Internationalized Domain Names (IDN)). It builds upon the punycode encoding and stringprep.\\n\\nIf you need the IDNA 2008 standard from RFC 5891 and RFC 5895, use the third-party idna module.\\n\\nThese RFCs together define a protocol to support non-ASCII characters in domain names. A domain name containing non-ASCII characters (such as www.Alliancefrançaise.nu) is converted into an ASCII-compatible encoding (ACE, such as www.xn--alliancefranaise-npb.nu). The ACE form of the domain name is then used in all places where arbitrary characters are not allowed by the protocol, such as DNS queries, HTTP Host fields, and so on. This conversion is carried out in the application; if possible invisible to the user: The application should transparently convert Unicode domain labels to IDNA on the wire, and convert back ACE labels to Unicode before presenting them to the user.\\n\\nPython supports this conversion in several ways: the idna codec performs conversion between Unicode and ACE, separating an input string into labels based on the separator characters defined in section 3.1 of RFC 3490 and converting each label to ACE as required, and conversely separating an input byte string into labels based on the . separator and converting any ACE labels found into unicode. Furthermore, the socket module transparently converts Unicode host names to ACE, so that applications need not be concerned about converting host names themselves when they pass them to the socket module. On top of that, modules that have host names as function parameters, such as http.client and ftplib, accept Unicode host names (http.client then also transparently sends an IDNA hostname in the Host field if it sends that field at all).\\n\\nWhen receiving host names from the wire (such as in reverse name lookup), no automatic conversion to Unicode is performed: applications wishing to present such host names to the user should decode them to Unicode.\\n\\nThe module 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.\\n\\nencodings.mbcs — Windows ANSI codepage¶\\n\\nThis module implements the ANSI codepage (CP_ACP).\\n\\nAvailability: Windows.\\n\\nChanged in version 3.2: Before 3.2, the errors argument was ignored; \\'replace\\' was always used to encode, and \\'ignore\\' to decode.\\n\\nChanged in version 3.3: Support any error handler.\\n\\nencodings.utf_8_sig — UTF-8 codec with BOM signature¶\\n\\nThis module implements a variant of the UTF-8 codec. On encoding, a UTF-8 encoded BOM will be prepended to the UTF-8 encoded bytes. For the stateful encoder this is only done once (on the first write to the byte stream). On decoding, an optional UTF-8 encoded BOM at the start of the data will be skipped.\\n\\nTable of Contents\\n\\ncodecs — Codec registry and base classes\\n\\nCodec Base Classes\\n\\nError Handlers\\n\\nStateless Encoding and Decoding\\n\\nIncremental Encoding and Decoding\\n\\nIncrementalEncoder Objects\\n\\nIncrementalDecoder Objects\\n\\nStream Encoding and Decoding\\n\\nStreamWriter Objects\\n\\nStreamReader Objects\\n\\nStreamReaderWriter Objects\\n\\nStreamRecoder Objects\\n\\nEncodings and Unicode\\n\\nStandard Encodings\\n\\nPython Specific Encodings\\n\\nText Encodings\\n\\nBinary Transforms\\n\\nStandalone Codec Functions\\n\\nText Transforms\\n\\nencodings — Encodings package\\n\\nencodings.idna — Internationalized Domain Names in Applications\\n\\nencodings.mbcs — Windows ANSI codepage\\n\\nencodings.utf_8_sig — UTF-8 codec with BOM signature\\n\\nPrevious topic\\n\\nstruct — Interpret bytes as packed binary data\\n\\nNext topic\\n\\nData Types\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nBinary Data Services »\\n\\ncodecs — Codec registry and base classes\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\codeop.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nCustom Python Interpreters »\\n\\ncodeop — Compile Python code\\n\\n|\\n\\ncodeop — Compile Python code¶\\n\\nSource code: Lib/codeop.py\\n\\nThe codeop module provides utilities upon which the Python read-eval-print loop can be emulated, as is done in the 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 code module instead.\\n\\nThere are two parts to this job:\\n\\nBeing able to tell if a line of input completes a Python statement: in short, telling whether to print ‘>>>’ or ‘...’ next.\\n\\nRemembering which future statements the user has entered, so subsequent input can be compiled with these in effect.\\n\\nThe codeop module provides a way of doing each of these things, and a way of doing them both.\\n\\nTo do just the former:\\n\\nPrevious topic\\n\\ncode — Interpreter base classes\\n\\nNext topic\\n\\nImporting Modules\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nCustom Python Interpreters »\\n\\ncodeop — Compile Python code\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\collections.abc.html'}, page_content=\"Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Types »\\n\\ncollections.abc — Abstract Base Classes for Containers\\n\\n|\\n\\ncollections.abc — Abstract Base Classes for Containers¶\\n\\nAdded in version 3.3: Formerly, this module was part of the collections module.\\n\\nSource code: Lib/_collections_abc.py\\n\\nThis module provides abstract base classes that can be used to test whether a class provides a particular interface; for example, whether it is hashable or whether it is a mapping.\\n\\nAn issubclass() or isinstance() test for an interface works in one of three ways.\\n\\nA 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:\\n\\nclass C(Sequence): # Direct inheritance\\n def __init__(self): ... # Extra method not required by the ABC\\n def __getitem__(self, index): ... # Required abstract method\\n def __len__(self): ... # Required abstract method\\n def count(self, value): ... # Optionally override a mixin method\\n\\n>>> issubclass(C, Sequence)\\nTrue\\n>>> isinstance(C(), Sequence)\\nTrue\\n\\nExisting 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 issubclass() or 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:\\n\\nclass D: # No inheritance\\n def __init__(self): ... # Extra method not required by the ABC\\n def __getitem__(self, index): ... # Abstract method\\n def __len__(self): ... # Abstract method\\n def count(self, value): ... # Mixin method\\n def index(self, value): ... # Mixin method\\n\\nSequence.register(D) # Register instead of inherit\\n\\n>>> issubclass(D, Sequence)\\nTrue\\n>>> isinstance(D(), Sequence)\\nTrue\\n\\nIn this example, class D does not need to define __contains__, __iter__, and __reversed__ because the in-operator, the iteration logic, and the reversed() function automatically fall back to using __getitem__ and __len__.\\n\\nSome simple interfaces are directly recognizable by the presence of the required methods (unless those methods have been set to None):\\n\\nclass E:\\n def __iter__(self): ...\\n def __next__(self): ...\\n\\n>>> issubclass(E, Iterable)\\nTrue\\n>>> isinstance(E(), Iterable)\\nTrue\\n\\nComplex interfaces do not support this last technique because an interface is more than just the presence of method names. Interfaces specify semantics and relationships between methods that cannot be inferred solely from the presence of specific method names. For example, knowing that a class supplies __getitem__, __len__, and __iter__ is insufficient for distinguishing a Sequence from a Mapping.\\n\\nAdded in version 3.9: These abstract classes now support []. See Generic Alias Type and PEP 585.\\n\\nCollections Abstract Base Classes¶\\n\\nThe collections module offers the following ABCs:\\n\\nABC Inherits from Abstract Methods Mixin Methods Container [ 1 ] __contains__ Hashable [ 1 ] __hash__ Iterable [ 1 ] [ 2 ] __iter__ Iterator [ 1 ] Iterable __next__ __iter__ Reversible [ 1 ] Iterable __reversed__ Generator [ 1 ] Iterator send , throw close , __iter__ , __next__ Sized [ 1 ] __len__ Callable [ 1 ] __call__ Collection [ 1 ] Sized , Iterable , Container __contains__ , __iter__ , __len__ Sequence Reversible , Collection __getitem__ , __len__ __contains__ , __iter__ , __reversed__ , index , and count MutableSequence Sequence __getitem__ , __setitem__ , __delitem__ , __len__ , insert Inherited Sequence methods and append , clear , reverse , extend , pop , remove , and __iadd__ ByteString Sequence __getitem__ , __len__ Inherited Sequence methods Set Collection __contains__ , __iter__ , __len__ __le__ , __lt__ , __eq__ , __ne__ , __gt__ , __ge__ , __and__ , __or__ , __sub__ , __rsub__ , __xor__ , __rxor__ and isdisjoint MutableSet Set __contains__ , __iter__ , __len__ , add , discard Inherited Set methods and clear , pop , remove , __ior__ , __iand__ , __ixor__ , and __isub__ Mapping Collection __getitem__ , __iter__ , __len__ __contains__ , keys , items , values , get , __eq__ , and __ne__ MutableMapping Mapping __getitem__ , __setitem__ , __delitem__ , __iter__ , __len__ Inherited Mapping methods and pop , popitem , clear , update ,\\nand setdefault MappingView Sized __init__ , __len__ and __repr__ ItemsView MappingView , Set __contains__ , __iter__ KeysView MappingView , Set __contains__ , __iter__ ValuesView MappingView , Collection __contains__ , __iter__ Awaitable [ 1 ] __await__ Coroutine [ 1 ] Awaitable send , throw close AsyncIterable [ 1 ] __aiter__ AsyncIterator [ 1 ] AsyncIterable __anext__ __aiter__ AsyncGenerator [ 1 ] AsyncIterator asend , athrow aclose , __aiter__ , __anext__ Buffer [ 1 ] __buffer__\\n\\nFootnotes\\n\\n[1] (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)\\n\\nThese ABCs override __subclasshook__() to support testing an interface by verifying the required methods are present and have not been set to None. This only works for simple interfaces. More complex interfaces require registration or direct subclassing.\\n\\n[2]\\n\\nChecking isinstance(obj, Iterable) detects classes that are registered as Iterable or that have an __iter__() method, but it does not detect classes that iterate with the __getitem__() method. The only reliable way to determine whether an object is iterable is to call iter(obj).\\n\\nCollections Abstract Base Classes – Detailed Descriptions¶\\n\\nExamples and Recipes¶\\n\\nABCs allow us to ask classes or instances if they provide particular functionality, for example:\\n\\nsize = None\\nif isinstance(myvar, collections.abc.Sized):\\n size = len(myvar)\\n\\nSeveral of the ABCs are also useful as mixins that make it easier to develop classes supporting container APIs. For example, to write a class supporting the full Set API, it is only necessary to supply the three underlying abstract methods: __contains__(), __iter__(), and __len__(). The ABC supplies the remaining methods such as __and__() and isdisjoint():\\n\\nclass ListBasedSet(collections.abc.Set):\\n ''' Alternate set implementation favoring space over speed\\n and not requiring the set elements to be hashable. '''\\n def __init__(self, iterable):\\n self.elements = lst = []\\n for value in iterable:\\n if value not in lst:\\n lst.append(value)\\n\\n def __iter__(self):\\n return iter(self.elements)\\n\\n def __contains__(self, value):\\n return value in self.elements\\n\\n def __len__(self):\\n return len(self.elements)\\n\\ns1 = ListBasedSet('abcdef')\\ns2 = ListBasedSet('defghi')\\noverlap = s1 & s2 # The __and__() method is supported automatically\\n\\nNotes on using Set and MutableSet as a mixin:\\n\\nSince some set operations create new sets, the default mixin methods need a way to create new instances from an iterable. The class constructor is assumed to have a signature in the form ClassName(iterable). That assumption is factored-out to an internal classmethod called _from_iterable() which calls cls(iterable) to produce a new set. If the Set mixin is being used in a class with a different constructor signature, you will need to override _from_iterable() with a classmethod or regular method that can construct new instances from an iterable argument.\\n\\nTo override the comparisons (presumably for speed, as the semantics are fixed), redefine __le__() and __ge__(), then the other operations will automatically follow suit.\\n\\nThe Set mixin provides a _hash() method to compute a hash value for the set; however, __hash__() is not defined because not all sets are hashable or immutable. To add set hashability using mixins, inherit from both Set() and Hashable(), then define __hash__ = Set._hash.\\n\\nSee also\\n\\nOrderedSet recipe for an example built on MutableSet.\\n\\nFor more about ABCs, see the abc module and PEP 3119.\\n\\nTable of Contents\\n\\ncollections.abc — Abstract Base Classes for Containers\\n\\nCollections Abstract Base Classes\\n\\nCollections Abstract Base Classes – Detailed Descriptions\\n\\nExamples and Recipes\\n\\nPrevious topic\\n\\ncollections — Container datatypes\\n\\nNext topic\\n\\nheapq — Heap queue algorithm\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Types »\\n\\ncollections.abc — Abstract Base Classes for Containers\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.\"), Document(metadata={'source': '..\\\\..\\\\docs\\\\collections.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Types »\\n\\ncollections — Container datatypes\\n\\n|\\n\\ncollections — Container datatypes¶\\n\\nSource code: Lib/collections/__init__.py\\n\\nThis module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, dict, list, set, and tuple.\\n\\nnamedtuple() factory function for creating tuple subclasses with named fields deque list-like container with fast appends and pops on either end ChainMap dict-like class for creating a single view of multiple mappings Counter dict subclass for counting hashable objects OrderedDict dict subclass that remembers the order entries were added defaultdict dict subclass that calls a factory function to supply missing values UserDict wrapper around dictionary objects for easier dict subclassing UserList wrapper around list objects for easier list subclassing UserString wrapper around string objects for easier string subclassing\\n\\nChainMap objects¶\\n\\nAdded in version 3.3.\\n\\nA ChainMap class is provided for quickly linking a number of mappings so they can be treated as a single unit. It is often much faster than creating a new dictionary and running multiple update() calls.\\n\\nThe class can be used to simulate nested scopes and is useful in templating.\\n\\nSee also\\n\\nThe MultiContext class in the Enthought CodeTools package has options to support writing to any mapping in the chain.\\n\\nDjango’s Context class for templating is a read-only chain of mappings. It also features pushing and popping of contexts similar to the new_child() method and the parents property.\\n\\nThe Nested Contexts recipe has options to control whether writes and other mutations apply only to the first mapping or to any mapping in the chain.\\n\\nA greatly simplified read-only version of Chainmap.\\n\\nChainMap Examples and Recipes¶\\n\\nThis section shows various approaches to working with chained maps.\\n\\nExample of simulating Python’s internal lookup chain:\\n\\nimport builtins\\npylookup = ChainMap(locals(), globals(), vars(builtins))\\n\\nExample of letting user specified command-line arguments take precedence over environment variables which in turn take precedence over default values:\\n\\nimport os, argparse\\n\\ndefaults = {\\'color\\': \\'red\\', \\'user\\': \\'guest\\'}\\n\\nparser = argparse.ArgumentParser()\\nparser.add_argument(\\'-u\\', \\'--user\\')\\nparser.add_argument(\\'-c\\', \\'--color\\')\\nnamespace = parser.parse_args()\\ncommand_line_args = {k: v for k, v in vars(namespace).items() if v is not None}\\n\\ncombined = ChainMap(command_line_args, os.environ, defaults)\\nprint(combined[\\'color\\'])\\nprint(combined[\\'user\\'])\\n\\nExample patterns for using the ChainMap class to simulate nested contexts:\\n\\nc = ChainMap() # Create root context\\nd = c.new_child() # Create nested child context\\ne = c.new_child() # Child of c, independent from d\\ne.maps[0] # Current context dictionary -- like Python\\'s locals()\\ne.maps[-1] # Root context -- like Python\\'s globals()\\ne.parents # Enclosing context chain -- like Python\\'s nonlocals\\n\\nd[\\'x\\'] = 1 # Set value in current context\\nd[\\'x\\'] # Get first key in the chain of contexts\\ndel d[\\'x\\'] # Delete from current context\\nlist(d) # All nested values\\nk in d # Check all nested values\\nlen(d) # Number of nested values\\nd.items() # All nested items\\ndict(d) # Flatten into a regular dictionary\\n\\nThe ChainMap class only makes updates (writes and deletions) to the first mapping in the chain while lookups will search the full chain. However, if deep writes and deletions are desired, it is easy to make a subclass that updates keys found deeper in the chain:\\n\\nclass DeepChainMap(ChainMap):\\n \\'Variant of ChainMap that allows direct updates to inner scopes\\'\\n\\n def __setitem__(self, key, value):\\n for mapping in self.maps:\\n if key in mapping:\\n mapping[key] = value\\n return\\n self.maps[0][key] = value\\n\\n def __delitem__(self, key):\\n for mapping in self.maps:\\n if key in mapping:\\n del mapping[key]\\n return\\n raise KeyError(key)\\n\\n>>> d = DeepChainMap({\\'zebra\\': \\'black\\'}, {\\'elephant\\': \\'blue\\'}, {\\'lion\\': \\'yellow\\'})\\n>>> d[\\'lion\\'] = \\'orange\\' # update an existing key two levels down\\n>>> d[\\'snake\\'] = \\'red\\' # new keys get added to the topmost dict\\n>>> del d[\\'elephant\\'] # remove an existing key one level down\\n>>> d # display result\\nDeepChainMap({\\'zebra\\': \\'black\\', \\'snake\\': \\'red\\'}, {}, {\\'lion\\': \\'orange\\'})\\n\\nCounter objects¶\\n\\nA counter tool is provided to support convenient and rapid tallies. For example:\\n\\n>>> # Tally occurrences of words in a list\\n>>> cnt = Counter()\\n>>> for word in [\\'red\\', \\'blue\\', \\'red\\', \\'green\\', \\'blue\\', \\'blue\\']:\\n... cnt[word] += 1\\n...\\n>>> cnt\\nCounter({\\'blue\\': 3, \\'red\\': 2, \\'green\\': 1})\\n\\n>>> # Find the ten most common words in Hamlet\\n>>> import re\\n>>> words = re.findall(r\\'\\\\w+\\', open(\\'hamlet.txt\\').read().lower())\\n>>> Counter(words).most_common(10)\\n[(\\'the\\', 1143), (\\'and\\', 966), (\\'to\\', 762), (\\'of\\', 669), (\\'i\\', 631),\\n (\\'you\\', 554), (\\'a\\', 546), (\\'my\\', 514), (\\'hamlet\\', 471), (\\'in\\', 451)]\\n\\nCounters support rich comparison operators for equality, subset, and superset relationships: ==, !=, <, <=, >, >=. All of those tests treat missing elements as having zero counts so that Counter(a=1) == Counter(a=1, b=0) returns true.\\n\\nChanged in version 3.10: Rich comparison operations were added.\\n\\nChanged in version 3.10: In equality tests, missing elements are treated as having zero counts. Formerly, Counter(a=3) and Counter(a=3, b=0) were considered distinct.\\n\\nCommon patterns for working with Counter objects:\\n\\nc.total() # total of all counts\\nc.clear() # reset all counts\\nlist(c) # list unique elements\\nset(c) # convert to a set\\ndict(c) # convert to a regular dictionary\\nc.items() # access the (elem, cnt) pairs\\nCounter(dict(list_of_pairs)) # convert from a list of (elem, cnt) pairs\\nc.most_common()[:-n-1:-1] # n least common elements\\n+c # remove zero and negative counts\\n\\nSeveral mathematical operations are provided for combining Counter objects to produce multisets (counters that have counts greater than zero). Addition and subtraction combine counters by adding or subtracting the counts of corresponding elements. Intersection and union return the minimum and maximum of corresponding counts. Symmetric difference returns the difference between the maximum and minimum of the corresponding counts. Equality and inclusion compare corresponding counts. Each operation can accept inputs with signed counts, but the output will exclude results with counts of zero or below.\\n\\n>>> c = Counter(a=3, b=1)\\n>>> d = Counter(a=1, b=2)\\n>>> c + d # add two counters together: c[x] + d[x]\\nCounter({\\'a\\': 4, \\'b\\': 3})\\n>>> c - d # subtract (keeping only positive counts)\\nCounter({\\'a\\': 2})\\n>>> c & d # intersection: min(c[x], d[x])\\nCounter({\\'a\\': 1, \\'b\\': 1})\\n>>> c | d # union: max(c[x], d[x])\\nCounter({\\'a\\': 3, \\'b\\': 2})\\n>>> c ^ d # max(c[x], d[x]) - min(c[x], d[x])\\nCounter({\\'a\\': 2, \\'b\\': 1})\\n>>> c == d # equality: c[x] == d[x]\\nFalse\\n>>> c <= d # inclusion: c[x] <= d[x]\\nFalse\\n\\nUnary addition and subtraction are shortcuts for adding an empty counter or subtracting from an empty counter.\\n\\n>>> c = Counter(a=2, b=-4)\\n>>> +c\\nCounter({\\'a\\': 2})\\n>>> -c\\nCounter({\\'b\\': 4})\\n\\nAdded in version 3.3: Added support for unary plus, unary minus, and in-place multiset operations.\\n\\nAdded in version 3.15: Added support for the symmetric difference multiset operation, c ^ d.\\n\\nNote\\n\\nCounters were primarily designed to work with positive integers to represent running counts; however, care was taken to not unnecessarily preclude use cases needing other types or negative values. To help with those use cases, this section documents the minimum range and type restrictions.\\n\\nThe Counter class itself is a dictionary subclass with no restrictions on its keys and values. The values are intended to be numbers representing counts, but you could store anything in the value field.\\n\\nThe most_common() method requires only that the values be orderable.\\n\\nFor in-place operations such as c[key] += 1, the value type need only support addition and subtraction. So fractions, floats, and decimals would work and negative values are supported. The same is also true for update() and subtract() which allow negative and zero values for both inputs and outputs.\\n\\nThe multiset methods are designed only for use cases with positive values. The inputs may be negative or zero, but only outputs with positive values are created. There are no type restrictions, but the value type needs to support addition, subtraction, and comparison.\\n\\nThe elements() method requires integer counts. It ignores zero and negative counts.\\n\\nSee also\\n\\nBag class in Smalltalk.\\n\\nWikipedia entry for Multisets.\\n\\nC++ multisets tutorial with examples.\\n\\nFor mathematical operations on multisets and their use cases, see Knuth, Donald. The Art of Computer Programming Volume II, Section 4.6.3, Exercise 19.\\n\\nTo enumerate all distinct multisets of a given size over a given set of elements, see itertools.combinations_with_replacement():\\n\\nmap(Counter, combinations_with_replacement(\\'ABC\\', 2)) # --> AA AB AC BB BC CC\\n\\ndeque objects¶\\n\\nIn addition to the above, deques support iteration, pickling, len(d), reversed(d), copy.copy(d), copy.deepcopy(d), membership testing with the in operator, and subscript references such as d[0] to access the first element. Indexed access is O(1) at both ends but slows to O(n) in the middle. For fast random access, use lists instead.\\n\\nStarting in version 3.5, deques support __add__(), __mul__(), and __imul__().\\n\\nExample:\\n\\n>>> from collections import deque\\n>>> d = deque(\\'ghi\\') # make a new deque with three items\\n>>> for elem in d: # iterate over the deque\\'s elements\\n... print(elem.upper())\\nG\\nH\\nI\\n\\n>>> d.append(\\'j\\') # add a new entry to the right side\\n>>> d.appendleft(\\'f\\') # add a new entry to the left side\\n>>> d # show the representation of the deque\\ndeque([\\'f\\', \\'g\\', \\'h\\', \\'i\\', \\'j\\'])\\n\\n>>> d.pop() # return and remove the rightmost item\\n\\'j\\'\\n>>> d.popleft() # return and remove the leftmost item\\n\\'f\\'\\n>>> list(d) # list the contents of the deque\\n[\\'g\\', \\'h\\', \\'i\\']\\n>>> d[0] # peek at leftmost item\\n\\'g\\'\\n>>> d[-1] # peek at rightmost item\\n\\'i\\'\\n\\n>>> list(reversed(d)) # list the contents of a deque in reverse\\n[\\'i\\', \\'h\\', \\'g\\']\\n>>> \\'h\\' in d # search the deque\\nTrue\\n>>> d.extend(\\'jkl\\') # add multiple elements at once\\n>>> d\\ndeque([\\'g\\', \\'h\\', \\'i\\', \\'j\\', \\'k\\', \\'l\\'])\\n>>> d.rotate(1) # right rotation\\n>>> d\\ndeque([\\'l\\', \\'g\\', \\'h\\', \\'i\\', \\'j\\', \\'k\\'])\\n>>> d.rotate(-1) # left rotation\\n>>> d\\ndeque([\\'g\\', \\'h\\', \\'i\\', \\'j\\', \\'k\\', \\'l\\'])\\n\\n>>> deque(reversed(d)) # make a new deque in reverse order\\ndeque([\\'l\\', \\'k\\', \\'j\\', \\'i\\', \\'h\\', \\'g\\'])\\n>>> d.clear() # empty the deque\\n>>> d.pop() # cannot pop from an empty deque\\nTraceback (most recent call last):\\n File \"\", line 1, in -toplevel-\\n d.pop()\\nIndexError: pop from an empty deque\\n\\n>>> d.extendleft(\\'abc\\') # extendleft() reverses the input order\\n>>> d\\ndeque([\\'c\\', \\'b\\', \\'a\\'])\\n\\ndeque Recipes¶\\n\\nThis section shows various approaches to working with deques.\\n\\nBounded length deques provide functionality similar to the tail filter in Unix:\\n\\ndef tail(filename, n=10):\\n \\'Return the last n lines of a file\\'\\n with open(filename) as f:\\n return deque(f, n)\\n\\nAnother approach to using deques is to maintain a sequence of recently added elements by appending to the right and popping to the left:\\n\\ndef moving_average(iterable, n=3):\\n # moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0\\n # https://en.wikipedia.org/wiki/Moving_average\\n it = iter(iterable)\\n d = deque(itertools.islice(it, n-1))\\n d.appendleft(0)\\n s = sum(d)\\n for elem in it:\\n s += elem - d.popleft()\\n d.append(elem)\\n yield s / n\\n\\nA round-robin scheduler can be implemented with input iterators stored in a deque. Values are yielded from the active iterator in position zero. If that iterator is exhausted, it can be removed with popleft(); otherwise, it can be cycled back to the end with the rotate() method:\\n\\ndef roundrobin(*iterables):\\n \"roundrobin(\\'ABC\\', \\'D\\', \\'EF\\') --> A D E B F C\"\\n iterators = deque(map(iter, iterables))\\n while iterators:\\n try:\\n while True:\\n yield next(iterators[0])\\n iterators.rotate(-1)\\n except StopIteration:\\n # Remove an exhausted iterator.\\n iterators.popleft()\\n\\nThe rotate() method provides a way to implement deque slicing and deletion. For example, a pure Python implementation of del d[n] relies on the rotate() method to position elements to be popped:\\n\\ndef delete_nth(d, n):\\n d.rotate(-n)\\n d.popleft()\\n d.rotate(n)\\n\\nTo implement deque slicing, use a similar approach applying rotate() to bring a target element to the left side of the deque. Remove old entries with popleft(), add new entries with extend(), and then reverse the rotation. With minor variations on that approach, it is easy to implement Forth style stack manipulations such as dup, drop, swap, over, pick, rot, and roll.\\n\\ndefaultdict objects¶\\n\\ndefaultdict Examples¶\\n\\nUsing list as the default_factory, it is easy to group a sequence of key-value pairs into a dictionary of lists:\\n\\n>>> s = [(\\'yellow\\', 1), (\\'blue\\', 2), (\\'yellow\\', 3), (\\'blue\\', 4), (\\'red\\', 1)]\\n>>> d = defaultdict(list)\\n>>> for k, v in s:\\n... d[k].append(v)\\n...\\n>>> sorted(d.items())\\n[(\\'blue\\', [2, 4]), (\\'red\\', [1]), (\\'yellow\\', [1, 3])]\\n\\nWhen each key is encountered for the first time, it is not already in the mapping; so an entry is automatically created using the default_factory function which returns an empty list. The list.append() operation then attaches the value to the new list. When keys are encountered again, the look-up proceeds normally (returning the list for that key) and the list.append() operation adds another value to the list. This technique is simpler and faster than an equivalent technique using dict.setdefault():\\n\\n>>> d = {}\\n>>> for k, v in s:\\n... d.setdefault(k, []).append(v)\\n...\\n>>> sorted(d.items())\\n[(\\'blue\\', [2, 4]), (\\'red\\', [1]), (\\'yellow\\', [1, 3])]\\n\\nSetting the default_factory to int makes the defaultdict useful for counting (like a bag or multiset in other languages):\\n\\n>>> s = \\'mississippi\\'\\n>>> d = defaultdict(int)\\n>>> for k in s:\\n... d[k] += 1\\n...\\n>>> sorted(d.items())\\n[(\\'i\\', 4), (\\'m\\', 1), (\\'p\\', 2), (\\'s\\', 4)]\\n\\nWhen a letter is first encountered, it is missing from the mapping, so the default_factory function calls int() to supply a default count of zero. The increment operation then builds up the count for each letter.\\n\\nThe function int() which always returns zero is just a special case of constant functions. A faster and more flexible way to create constant functions is to use a lambda function which can supply any constant value (not just zero):\\n\\n>>> def constant_factory(value):\\n... return lambda: value\\n...\\n>>> d = defaultdict(constant_factory(\\'\\'))\\n>>> d.update(name=\\'John\\', action=\\'ran\\')\\n>>> \\'%(name)s %(action)s to %(object)s\\' % d\\n\\'John ran to \\'\\n\\nSetting the default_factory to set makes the defaultdict useful for building a dictionary of sets:\\n\\n>>> s = [(\\'red\\', 1), (\\'blue\\', 2), (\\'red\\', 3), (\\'blue\\', 4), (\\'red\\', 1), (\\'blue\\', 4)]\\n>>> d = defaultdict(set)\\n>>> for k, v in s:\\n... d[k].add(v)\\n...\\n>>> sorted(d.items())\\n[(\\'blue\\', {2, 4}), (\\'red\\', {1, 3})]\\n\\nnamedtuple() Factory Function for Tuples with Named Fields¶\\n\\nNamed tuples assign meaning to each position in a tuple and allow for more readable, self-documenting code. They can be used wherever regular tuples are used, and they add the ability to access fields by name instead of position index.\\n\\n>>> # Basic example\\n>>> Point = namedtuple(\\'Point\\', [\\'x\\', \\'y\\'])\\n>>> p = Point(11, y=22) # instantiate with positional or keyword arguments\\n>>> p[0] + p[1] # indexable like the plain tuple (11, 22)\\n33\\n>>> x, y = p # unpack like a regular tuple\\n>>> x, y\\n(11, 22)\\n>>> p.x + p.y # fields also accessible by name\\n33\\n>>> p # readable __repr__ with a name=value style\\nPoint(x=11, y=22)\\n\\nNamed tuples are especially useful for assigning field names to result tuples returned by the csv or sqlite3 modules:\\n\\nEmployeeRecord = namedtuple(\\'EmployeeRecord\\', \\'name, age, title, department, paygrade\\')\\n\\nimport csv\\nfor emp in map(EmployeeRecord._make, csv.reader(open(\"employees.csv\", \"rb\"))):\\n print(emp.name, emp.title)\\n\\nimport sqlite3\\nconn = sqlite3.connect(\\'/companydata\\')\\ncursor = conn.cursor()\\ncursor.execute(\\'SELECT name, age, title, department, paygrade FROM employees\\')\\nfor emp in map(EmployeeRecord._make, cursor.fetchall()):\\n print(emp.name, emp.title)\\n\\nIn addition to the methods inherited from tuples, named tuples support three additional methods and two attributes. To prevent conflicts with field names, the method and attribute names start with an underscore.\\n\\nTo retrieve a field whose name is stored in a string, use the getattr() function:\\n\\n>>> getattr(p, \\'x\\')\\n11\\n\\nTo convert a dictionary to a named tuple, use the double-star-operator (as described in Unpacking Argument Lists):\\n\\n>>> d = {\\'x\\': 11, \\'y\\': 22}\\n>>> Point(**d)\\nPoint(x=11, y=22)\\n\\nSince a named tuple is a regular Python class, it is easy to add or change functionality with a subclass. Here is how to add a calculated field and a fixed-width print format:\\n\\n>>> class Point(namedtuple(\\'Point\\', [\\'x\\', \\'y\\'])):\\n... __slots__ = ()\\n... @property\\n... def hypot(self):\\n... return (self.x ** 2 + self.y ** 2) ** 0.5\\n... def __str__(self):\\n... return \\'Point: x=%6.3f y=%6.3f hypot=%6.3f\\' % (self.x, self.y, self.hypot)\\n\\n>>> for p in Point(3, 4), Point(14, 5/7):\\n... print(p)\\nPoint: x= 3.000 y= 4.000 hypot= 5.000\\nPoint: x=14.000 y= 0.714 hypot=14.018\\n\\nThe subclass shown above sets __slots__ to an empty tuple. This helps keep memory requirements low by preventing the creation of instance dictionaries.\\n\\nSubclassing is not useful for adding new, stored fields. Instead, simply create a new named tuple type from the _fields attribute:\\n\\n>>> Point3D = namedtuple(\\'Point3D\\', Point._fields + (\\'z\\',))\\n\\nDocstrings can be customized by making direct assignments to the __doc__ fields:\\n\\n>>> Book = namedtuple(\\'Book\\', [\\'id\\', \\'title\\', \\'authors\\'])\\n>>> Book.__doc__ += \\': Hardcover book in active collection\\'\\n>>> Book.id.__doc__ = \\'13-digit ISBN\\'\\n>>> Book.title.__doc__ = \\'Title of first printing\\'\\n>>> Book.authors.__doc__ = \\'List of authors sorted by last name\\'\\n\\nChanged in version 3.5: Property docstrings became writeable.\\n\\nSee also\\n\\nSee typing.NamedTuple for a way to add type hints for named tuples. It also provides an elegant notation using the class keyword:\\n\\nclass Component(NamedTuple):\\n part_number: int\\n weight: float\\n description: Optional[str] = None\\n\\nSee types.SimpleNamespace() for a mutable namespace based on an underlying dictionary instead of a tuple.\\n\\nThe dataclasses module provides a decorator and functions for automatically adding generated special methods to user-defined classes.\\n\\nOrderedDict objects¶\\n\\nOrdered dictionaries are just like regular dictionaries but have some extra capabilities relating to ordering operations. They have become less important now that the built-in dict class gained the ability to remember insertion order (this new behavior became guaranteed in Python 3.7).\\n\\nSome differences from dict still remain:\\n\\nThe regular dict was designed to be very good at mapping operations. Tracking insertion order was secondary.\\n\\nThe OrderedDict was designed to be good at reordering operations. Space efficiency, iteration speed, and the performance of update operations were secondary.\\n\\nThe OrderedDict algorithm can handle frequent reordering operations better than dict. As shown in the recipes below, this makes it suitable for implementing various kinds of LRU caches.\\n\\nThe equality operation for OrderedDict checks for matching order.\\n\\nA regular dict can emulate the order sensitive equality test with p == q and all(k1 == k2 for k1, k2 in zip(p, q)).\\n\\nThe popitem() method of OrderedDict has a different signature. It accepts an optional argument to specify which item is popped.\\n\\nA regular dict can emulate OrderedDict’s od.popitem(last=True) with d.popitem() which is guaranteed to pop the rightmost (last) item.\\n\\nA regular dict can emulate OrderedDict’s od.popitem(last=False) with (k := next(iter(d)), d.pop(k)) which will return and remove the leftmost (first) item if it exists.\\n\\nOrderedDict has a move_to_end() method to efficiently reposition an element to an endpoint.\\n\\nA regular dict can emulate OrderedDict’s od.move_to_end(k, last=True) with d[k] = d.pop(k) which will move the key and its associated value to the rightmost (last) position.\\n\\nA regular dict does not have an efficient equivalent for OrderedDict’s od.move_to_end(k, last=False) which moves the key and its associated value to the leftmost (first) position.\\n\\nUntil Python 3.8, dict lacked a __reversed__() method.\\n\\nIn addition to the usual mapping methods, ordered dictionaries also support reverse iteration using reversed().\\n\\nEquality tests between OrderedDict objects are order-sensitive and are roughly equivalent to list(od1.items())==list(od2.items()).\\n\\nEquality tests between OrderedDict objects and other Mapping objects are order-insensitive like regular dictionaries. This allows OrderedDict objects to be substituted anywhere a regular dictionary is used.\\n\\nChanged in version 3.5: The items, keys, and values views of OrderedDict now support reverse iteration using reversed().\\n\\nChanged in version 3.6: With the acceptance of PEP 468, order is retained for keyword arguments passed to the OrderedDict constructor and its update() method.\\n\\nChanged in version 3.9: Added merge (|) and update (|=) operators, specified in PEP 584.\\n\\nOrderedDict Examples and Recipes¶\\n\\nIt is straightforward to create an ordered dictionary variant that remembers the order the keys were last inserted. If a new entry overwrites an existing entry, the original insertion position is changed and moved to the end:\\n\\nclass LastUpdatedOrderedDict(OrderedDict):\\n \\'Store items in the order that the keys were last updated.\\'\\n\\n def __setitem__(self, key, value):\\n super().__setitem__(key, value)\\n self.move_to_end(key)\\n\\nAn OrderedDict would also be useful for implementing variants of functools.lru_cache():\\n\\nfrom collections import OrderedDict\\nfrom time import time\\n\\nclass TimeBoundedLRU:\\n \"LRU Cache that invalidates and refreshes old entries.\"\\n\\n def __init__(self, func, maxsize=128, maxage=30):\\n self.cache = OrderedDict() # { args : (timestamp, result)}\\n self.func = func\\n self.maxsize = maxsize\\n self.maxage = maxage\\n\\n def __call__(self, *args):\\n if args in self.cache:\\n self.cache.move_to_end(args)\\n timestamp, result = self.cache[args]\\n if time() - timestamp <= self.maxage:\\n return result\\n result = self.func(*args)\\n self.cache[args] = time(), result\\n if len(self.cache) > self.maxsize:\\n self.cache.popitem(last=False)\\n return result\\n\\nclass MultiHitLRUCache:\\n \"\"\" LRU cache that defers caching a result until\\n it has been requested multiple times.\\n\\n To avoid flushing the LRU cache with one-time requests,\\n we don\\'t cache until a request has been made more than once.\\n\\n \"\"\"\\n\\n def __init__(self, func, maxsize=128, maxrequests=4096, cache_after=1):\\n self.requests = OrderedDict() # { uncached_key : request_count }\\n self.cache = OrderedDict() # { cached_key : function_result }\\n self.func = func\\n self.maxrequests = maxrequests # max number of uncached requests\\n self.maxsize = maxsize # max number of stored return values\\n self.cache_after = cache_after\\n\\n def __call__(self, *args):\\n if args in self.cache:\\n self.cache.move_to_end(args)\\n return self.cache[args]\\n result = self.func(*args)\\n self.requests[args] = self.requests.get(args, 0) + 1\\n if self.requests[args] <= self.cache_after:\\n self.requests.move_to_end(args)\\n if len(self.requests) > self.maxrequests:\\n self.requests.popitem(last=False)\\n else:\\n self.requests.pop(args, None)\\n self.cache[args] = result\\n if len(self.cache) > self.maxsize:\\n self.cache.popitem(last=False)\\n return result\\n\\nUserDict objects¶\\n\\nThe class, UserDict acts as a wrapper around dictionary objects. The need for this class has been partially supplanted by the ability to subclass directly from dict; however, this class can be easier to work with because the underlying dictionary is accessible as an attribute.\\n\\nUserList objects¶\\n\\nThis class acts as a wrapper around list objects. It is a useful base class for your own list-like classes which can inherit from them and override existing methods or add new ones. In this way, one can add new behaviors to lists.\\n\\nThe need for this class has been partially supplanted by the ability to subclass directly from list; however, this class can be easier to work with because the underlying list is accessible as an attribute.\\n\\nSubclassing requirements: Subclasses of UserList are expected to offer a constructor which can be called with either no arguments or one argument. List operations which return a new sequence attempt to create an instance of the actual implementation class. To do so, it assumes that the constructor can be called with a single parameter, which is a sequence object used as a data source.\\n\\nIf a derived class does not wish to comply with this requirement, all of the special methods supported by this class will need to be overridden; please consult the sources for information about the methods which need to be provided in that case.\\n\\nUserString objects¶\\n\\nThe class, UserString acts as a wrapper around string objects. The need for this class has been partially supplanted by the ability to subclass directly from str; however, this class can be easier to work with because the underlying string is accessible as an attribute.\\n\\nTable of Contents\\n\\ncollections — Container datatypes\\n\\nChainMap objects\\n\\nChainMap Examples and Recipes\\n\\nCounter objects\\n\\ndeque objects\\n\\ndeque Recipes\\n\\ndefaultdict objects\\n\\ndefaultdict Examples\\n\\nnamedtuple() Factory Function for Tuples with Named Fields\\n\\nOrderedDict objects\\n\\nOrderedDict Examples and Recipes\\n\\nUserDict objects\\n\\nUserList objects\\n\\nUserString objects\\n\\nPrevious topic\\n\\ncalendar — General calendar-related functions\\n\\nNext topic\\n\\ncollections.abc — Abstract Base Classes for Containers\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Types »\\n\\ncollections — Container datatypes\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\colorsys.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nMultimedia Services »\\n\\ncolorsys — Conversions between color systems\\n\\n|\\n\\ncolorsys — Conversions between color systems¶\\n\\nSource code: Lib/colorsys.py\\n\\nThe 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.\\n\\nSee also\\n\\nMore information about color spaces can be found at https://poynton.ca/ColorFAQ.html and https://www.cambridgeincolour.com/tutorials/color-spaces.htm.\\n\\nThe colorsys module defines the following functions:\\n\\nExample:\\n\\n>>> import colorsys\\n>>> colorsys.rgb_to_hsv(0.2, 0.4, 0.4)\\n(0.5, 0.5, 0.4)\\n>>> colorsys.hsv_to_rgb(0.5, 0.5, 0.4)\\n(0.2, 0.4, 0.4)\\n\\nPrevious topic\\n\\nwave — Read and write WAV files\\n\\nNext topic\\n\\nInternationalization\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nMultimedia Services »\\n\\ncolorsys — Conversions between color systems\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\compileall.html'}, page_content=\"Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Language Services »\\n\\ncompileall — Byte-compile Python libraries\\n\\n|\\n\\ncompileall — Byte-compile Python libraries¶\\n\\nSource code: Lib/compileall.py\\n\\nThis module provides some utility functions to support installing Python libraries. These functions compile Python source files in a directory tree. This module can be used to create the cached byte-code files at library installation time, which makes them available for use even by users who don’t have write permission to the library directories.\\n\\nAvailability: not WASI.\\n\\nThis module does not work or is not available on WebAssembly. See WebAssembly platforms for more information.\\n\\nCommand-line use¶\\n\\nThis module can work as a script (using python -m compileall) to compile Python sources.\\n\\nChanged in version 3.2: Added the -i, -b and -h options.\\n\\nChanged in version 3.5: Added the -j, -r, and -qq options. -q option was changed to a multilevel value. -b will always produce a byte-code file ending in .pyc, never .pyo.\\n\\nChanged in version 3.7: Added the --invalidation-mode option.\\n\\nChanged in version 3.9: Added the -s, -p, -e and --hardlink-dupes options. Raised the default recursion limit from 10 to sys.getrecursionlimit(). Added the possibility to specify the -o option multiple times.\\n\\nThere is no command-line option to control the optimization level used by the compile() function, because the Python interpreter itself already provides the option: python -O -m compileall.\\n\\nSimilarly, the compile() function respects the sys.pycache_prefix setting. The generated bytecode cache will only be useful if compile() is run with the same sys.pycache_prefix (if any) that will be used at runtime.\\n\\nPublic functions¶\\n\\nTo force a recompile of all the .py files in the Lib/ subdirectory and all its subdirectories:\\n\\nimport compileall\\n\\ncompileall.compile_dir('Lib/', force=True)\\n\\n# Perform same compilation, excluding files in .svn directories.\\nimport re\\ncompileall.compile_dir('Lib/', rx=re.compile(r'[/\\\\\\\\][.]svn'), force=True)\\n\\n# pathlib.Path objects can also be used.\\nimport pathlib\\ncompileall.compile_dir(pathlib.Path('Lib/'), force=True)\\n\\nSee also\\n\\nTable of Contents\\n\\ncompileall — Byte-compile Python libraries\\n\\nCommand-line use\\n\\nPublic functions\\n\\nPrevious topic\\n\\npy_compile — Compile Python source files\\n\\nNext topic\\n\\ndis — Disassembler for Python bytecode\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Language Services »\\n\\ncompileall — Byte-compile Python libraries\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.\"), Document(metadata={'source': '..\\\\..\\\\docs\\\\compression.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Compression and Archiving »\\n\\nThe compression package\\n\\n|\\n\\nThe compression package¶\\n\\nAdded in version 3.14.\\n\\nThe 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 compression is encouraged where practical.\\n\\ncompression.bz2 – Re-exports bz2\\n\\ncompression.gzip – Re-exports gzip\\n\\ncompression.lzma – Re-exports lzma\\n\\ncompression.zlib – Re-exports zlib\\n\\ncompression.zstd – Wrapper for the Zstandard compression library\\n\\nPrevious topic\\n\\nData Compression and Archiving\\n\\nNext topic\\n\\ncompression.zstd — Compression compatible with the Zstandard format\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Compression and Archiving »\\n\\nThe compression package\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\compression.zstd.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Compression and Archiving »\\n\\ncompression.zstd — Compression compatible with the Zstandard format\\n\\n|\\n\\ncompression.zstd — Compression compatible with the Zstandard format¶\\n\\nAdded in version 3.14.\\n\\nSource code: Lib/compression/zstd/__init__.py\\n\\nThis module provides classes and functions for compressing and decompressing data using the Zstandard (or zstd) compression algorithm. The zstd manual 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 .zst files created by the zstd utility, as well as raw zstd compressed streams.\\n\\nThe compression.zstd module contains:\\n\\nThe open() function and ZstdFile class for reading and writing compressed files.\\n\\nThe ZstdCompressor and ZstdDecompressor classes for incremental (de)compression.\\n\\nThe compress() and decompress() functions for one-shot (de)compression.\\n\\nThe train_dict() and finalize_dict() functions and the ZstdDict class to train and manage Zstandard dictionaries.\\n\\nThe CompressionParameter, DecompressionParameter, and Strategy classes for setting advanced (de)compression parameters.\\n\\nThis is an 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 Requirements for optional modules.\\n\\nExceptions¶\\n\\nReading and writing compressed files¶\\n\\nCompressing and decompressing data in memory¶\\n\\nZstandard dictionaries¶\\n\\nAdvanced parameter control¶\\n\\nMiscellaneous¶\\n\\nExamples¶\\n\\nReading in a compressed file:\\n\\nfrom compression import zstd\\n\\nwith zstd.open(\"file.zst\") as f:\\n file_content = f.read()\\n\\nCreating a compressed file:\\n\\nfrom compression import zstd\\n\\ndata = b\"Insert Data Here\"\\nwith zstd.open(\"file.zst\", \"w\") as f:\\n f.write(data)\\n\\nCompressing data in memory:\\n\\nfrom compression import zstd\\n\\ndata_in = b\"Insert Data Here\"\\ndata_out = zstd.compress(data_in)\\n\\nIncremental compression:\\n\\nfrom compression import zstd\\n\\ncomp = zstd.ZstdCompressor()\\nout1 = comp.compress(b\"Some data\\\\n\")\\nout2 = comp.compress(b\"Another piece of data\\\\n\")\\nout3 = comp.compress(b\"Even more data\\\\n\")\\nout4 = comp.flush()\\n# Concatenate all the partial results:\\nresult = b\"\".join([out1, out2, out3, out4])\\n\\nWriting compressed data to an already-open file:\\n\\nfrom compression import zstd\\n\\nwith open(\"myfile\", \"wb\") as f:\\n f.write(b\"This data will not be compressed\\\\n\")\\n with zstd.open(f, \"w\") as zstf:\\n zstf.write(b\"This *will* be compressed\\\\n\")\\n f.write(b\"Not compressed\\\\n\")\\n\\nCreating a compressed file using compression parameters:\\n\\nfrom compression import zstd\\n\\noptions = {\\n zstd.CompressionParameter.checksum_flag: 1\\n}\\nwith zstd.open(\"file.zst\", \"w\", options=options) as f:\\n f.write(b\"Mind if I squeeze in?\")\\n\\nTable of Contents\\n\\ncompression.zstd — Compression compatible with the Zstandard format\\n\\nExceptions\\n\\nReading and writing compressed files\\n\\nCompressing and decompressing data in memory\\n\\nZstandard dictionaries\\n\\nAdvanced parameter control\\n\\nMiscellaneous\\n\\nExamples\\n\\nPrevious topic\\n\\nThe compression package\\n\\nNext topic\\n\\nzlib — Compression compatible with gzip\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Compression and Archiving »\\n\\ncompression.zstd — Compression compatible with the Zstandard format\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\concurrency.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nConcurrent Execution\\n\\n|\\n\\nConcurrent Execution¶\\n\\nThe modules described in this chapter provide support for concurrent execution of code. The appropriate choice of tool will depend on the task to be executed (CPU bound vs IO bound) and preferred style of development (event driven cooperative multitasking vs preemptive multitasking). Here’s an overview:\\n\\nthreading — Thread-based parallelism\\n\\nIntroduction\\n\\nGIL and performance considerations\\n\\nReference\\n\\nThread-local data\\n\\nThread objects\\n\\nLock objects\\n\\nRLock objects\\n\\nCondition objects\\n\\nSemaphore objects\\n\\nSemaphore example\\n\\nEvent objects\\n\\nTimer objects\\n\\nBarrier objects\\n\\nUsing locks, conditions, and semaphores in the with statement\\n\\nmultiprocessing — Process-based parallelism\\n\\nIntroduction\\n\\nThe Process class\\n\\nContexts and start methods\\n\\nExchanging objects between processes\\n\\nSynchronization between processes\\n\\nSharing state between processes\\n\\nUsing a pool of workers\\n\\nReference\\n\\nGlobal start method\\n\\nProcess and exceptions\\n\\nPipes and Queues\\n\\nMiscellaneous\\n\\nConnection Objects\\n\\nSynchronization primitives\\n\\nShared ctypes Objects\\n\\nThe multiprocessing.sharedctypes module\\n\\nManagers\\n\\nCustomized managers\\n\\nUsing a remote manager\\n\\nProxy Objects\\n\\nCleanup\\n\\nProcess Pools\\n\\nListeners and Clients\\n\\nAddress Formats\\n\\nAuthentication keys\\n\\nLogging\\n\\nThe multiprocessing.dummy module\\n\\nProgramming guidelines\\n\\nAll start methods\\n\\nThe spawn and forkserver start methods\\n\\nExamples\\n\\nmultiprocessing.shared_memory — Shared memory for direct access across processes\\n\\nThe concurrent package\\n\\nconcurrent.futures — Launching parallel tasks\\n\\nExecutor Objects\\n\\nThreadPoolExecutor\\n\\nThreadPoolExecutor Example\\n\\nInterpreterPoolExecutor\\n\\nProcessPoolExecutor\\n\\nProcessPoolExecutor Example\\n\\nFuture Objects\\n\\nModule Functions\\n\\nException classes\\n\\nconcurrent.interpreters — Multiple interpreters in the same process\\n\\nKey details\\n\\nIntroduction\\n\\nMultiple Interpreters and Isolation\\n\\nRunning in an Interpreter\\n\\nConcurrency and Parallelism\\n\\nCommunication Between Interpreters\\n\\n“Sharing” Objects\\n\\nReference\\n\\nInterpreter objects\\n\\nExceptions\\n\\nCommunicating Between Interpreters\\n\\nBasic usage\\n\\nsubprocess — Subprocess management\\n\\nUsing the subprocess Module\\n\\nFrequently Used Arguments\\n\\nPopen Constructor\\n\\nExceptions\\n\\nSecurity Considerations\\n\\nPopen Objects\\n\\nWindows Popen Helpers\\n\\nWindows Constants\\n\\nOlder high-level API\\n\\nReplacing Older Functions with the subprocess Module\\n\\nReplacing /bin/sh shell command substitution\\n\\nReplacing shell pipeline\\n\\nReplacing os.system()\\n\\nReplacing the os.spawn family\\n\\nReplacing os.popen()\\n\\nLegacy Shell Invocation Functions\\n\\nNotes\\n\\nTimeout Behavior\\n\\nConverting an argument sequence to a string on Windows\\n\\nDisable use of posix_spawn()\\n\\nsched — Event scheduler\\n\\nScheduler Objects\\n\\nqueue — A synchronized queue class\\n\\nQueue Objects\\n\\nWaiting for task completion\\n\\nTerminating queues\\n\\nSimpleQueue Objects\\n\\ncontextvars — Context Variables\\n\\nContext Variables\\n\\nManual Context Management\\n\\nasyncio support\\n\\nThe following are support modules for some of the above services:\\n\\n_thread — Low-level threading API\\n\\nPrevious topic\\n\\ncmd — Support for line-oriented command interpreters\\n\\nNext topic\\n\\nthreading — Thread-based parallelism\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nConcurrent Execution\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\concurrent.futures.html'}, page_content=\"Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nConcurrent Execution »\\n\\nconcurrent.futures — Launching parallel tasks\\n\\n|\\n\\nconcurrent.futures — Launching parallel tasks¶\\n\\nAdded in version 3.2.\\n\\nSource code: Lib/concurrent/futures/thread.py, Lib/concurrent/futures/process.py, and Lib/concurrent/futures/interpreter.py\\n\\nThe concurrent.futures module provides a high-level interface for asynchronously executing callables.\\n\\nThe asynchronous execution can be performed with threads, using ThreadPoolExecutor or InterpreterPoolExecutor, or separate processes, using ProcessPoolExecutor. Each implements the same interface, which is defined by the abstract Executor class.\\n\\nconcurrent.futures.Future must not be confused with asyncio.Future, which is designed for use with asyncio tasks and coroutines. See the asyncio’s Future documentation for a detailed comparison of the two.\\n\\nAvailability: not WASI.\\n\\nThis module does not work or is not available on WebAssembly. See WebAssembly platforms for more information.\\n\\nExecutor Objects¶\\n\\nThreadPoolExecutor¶\\n\\nThreadPoolExecutor is an Executor subclass that uses a pool of threads to execute calls asynchronously.\\n\\nDeadlocks can occur when the callable associated with a Future waits on the results of another Future. For example:\\n\\nimport time\\ndef wait_on_b():\\n time.sleep(5)\\n print(b.result()) # b will never complete because it is waiting on a.\\n return 5\\n\\ndef wait_on_a():\\n time.sleep(5)\\n print(a.result()) # a will never complete because it is waiting on b.\\n return 6\\n\\n\\nexecutor = ThreadPoolExecutor(max_workers=2)\\na = executor.submit(wait_on_b)\\nb = executor.submit(wait_on_a)\\n\\nAnd:\\n\\ndef wait_on_future():\\n f = executor.submit(pow, 5, 2)\\n # This will never complete because there is only one worker thread and\\n # it is executing this function.\\n print(f.result())\\n\\nexecutor = ThreadPoolExecutor(max_workers=1)\\nfuture = executor.submit(wait_on_future)\\n# Note: calling future.result() would also cause a deadlock because\\n# the single worker thread is already waiting for wait_on_future().\\n\\nThreadPoolExecutor Example¶\\n\\nimport concurrent.futures\\nimport urllib.request\\n\\nURLS = ['http://www.foxnews.com/',\\n 'http://www.cnn.com/',\\n 'http://europe.wsj.com/',\\n 'http://www.bbc.co.uk/',\\n 'http://nonexistent-subdomain.python.org/']\\n\\n# Retrieve a single page and report the URL and contents\\ndef load_url(url, timeout):\\n with urllib.request.urlopen(url, timeout=timeout) as conn:\\n return conn.read()\\n\\n# We can use a with statement to ensure threads are cleaned up promptly\\nwith concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:\\n # Start the load operations and mark each future with its URL\\n future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}\\n for future in concurrent.futures.as_completed(future_to_url):\\n url = future_to_url[future]\\n try:\\n data = future.result()\\n except Exception as exc:\\n print('%r generated an exception: %s' % (url, exc))\\n else:\\n print('%r page is %d bytes' % (url, len(data)))\\n\\nInterpreterPoolExecutor¶\\n\\nAdded in version 3.14.\\n\\nThe InterpreterPoolExecutor class uses a pool of interpreters to execute calls asynchronously. It is a 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.\\n\\nThe biggest benefit to using interpreters instead of only threads is true multi-core parallelism. Each interpreter has its own 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.\\n\\nThe 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.\\n\\nEach 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 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 sys, builtins, and even __main__.\\n\\nIsolation 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.\\n\\nCommunicating and synchronizing between interpreters is most effectively done using dedicated tools, like those proposed in PEP 734. One less efficient alternative is to serialize with pickle and then send the bytes over a shared socket or pipe.\\n\\nsubmit() and map() work like normal, except the worker serializes the callable and arguments using pickle when sending them to its interpreter. The worker likewise serializes the return value when sending it back.\\n\\nWhen 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 __cause__ to a corresponding 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 ExecutionFailed instance instead.\\n\\nProcessPoolExecutor¶\\n\\nThe ProcessPoolExecutor class is an Executor subclass that uses a pool of processes to execute calls asynchronously. ProcessPoolExecutor uses the multiprocessing module, which allows it to side-step the Global Interpreter Lock but also means that only picklable objects can be executed and returned.\\n\\nThe __main__ module must be importable by worker subprocesses. This means that ProcessPoolExecutor will not work in the interactive interpreter.\\n\\nCalling Executor or Future methods from a callable submitted to a ProcessPoolExecutor will result in deadlock.\\n\\nNote that the restrictions on functions and arguments needing to picklable as per multiprocessing.Process apply when using submit() and map() on a ProcessPoolExecutor. A function defined in a REPL or a lambda should not be expected to work.\\n\\nProcessPoolExecutor Example¶\\n\\nimport concurrent.futures\\nimport math\\n\\nPRIMES = [\\n 112272535095293,\\n 112582705942171,\\n 112272535095293,\\n 115280095190773,\\n 115797848077099,\\n 1099726899285419]\\n\\ndef is_prime(n):\\n if n < 2:\\n return False\\n if n == 2:\\n return True\\n if n % 2 == 0:\\n return False\\n\\n sqrt_n = int(math.floor(math.sqrt(n)))\\n for i in range(3, sqrt_n + 1, 2):\\n if n % i == 0:\\n return False\\n return True\\n\\ndef main():\\n with concurrent.futures.ProcessPoolExecutor() as executor:\\n for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):\\n print('%d is prime: %s' % (number, prime))\\n\\nif __name__ == '__main__':\\n main()\\n\\nFuture Objects¶\\n\\nThe Future class encapsulates the asynchronous execution of a callable. Future instances are created by Executor.submit().\\n\\nModule Functions¶\\n\\nSee also\\n\\nException classes¶\\n\\nTable of Contents\\n\\nconcurrent.futures — Launching parallel tasks\\n\\nExecutor Objects\\n\\nThreadPoolExecutor\\n\\nThreadPoolExecutor Example\\n\\nInterpreterPoolExecutor\\n\\nProcessPoolExecutor\\n\\nProcessPoolExecutor Example\\n\\nFuture Objects\\n\\nModule Functions\\n\\nException classes\\n\\nPrevious topic\\n\\nThe concurrent package\\n\\nNext topic\\n\\nconcurrent.interpreters — Multiple interpreters in the same process\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nConcurrent Execution »\\n\\nconcurrent.futures — Launching parallel tasks\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.\"), Document(metadata={'source': '..\\\\..\\\\docs\\\\concurrent.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nConcurrent Execution »\\n\\nThe concurrent package\\n\\n|\\n\\nThe concurrent package¶\\n\\nThis package contains the following modules:\\n\\nconcurrent.futures – Launching parallel tasks\\n\\nconcurrent.interpreters – Multiple interpreters in the same process\\n\\nPrevious topic\\n\\nmultiprocessing.shared_memory — Shared memory for direct access across processes\\n\\nNext topic\\n\\nconcurrent.futures — Launching parallel tasks\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nConcurrent Execution »\\n\\nThe concurrent package\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\concurrent.interpreters.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nConcurrent Execution »\\n\\nconcurrent.interpreters — Multiple interpreters in the same process\\n\\n|\\n\\nconcurrent.interpreters — Multiple interpreters in the same process¶\\n\\nAdded in version 3.14.\\n\\nSource code: Lib/concurrent/interpreters\\n\\nThe concurrent.interpreters module constructs higher-level interfaces on top of the lower level _interpreters module.\\n\\nThe 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.\\n\\nFor 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 threads See below\\n\\nSee also\\n\\nPEP 554\\n\\nPEP 734\\n\\nPEP 684\\n\\nAvailability: not WASI.\\n\\nThis module does not work or is not available on WebAssembly. See WebAssembly platforms for more information.\\n\\nKey details¶\\n\\nBefore we dive in further, there are a small number of details to keep in mind about using multiple interpreters:\\n\\nisolated, by default\\n\\nno implicit threads\\n\\nnot all PyPI packages support use in multiple interpreters yet\\n\\nIntroduction¶\\n\\nAn “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.)\\n\\nThe 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 isolation was relatively incomplete until version 3.12.\\n\\nMultiple Interpreters and Isolation¶\\n\\nA 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).\\n\\nThat 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.\\n\\nNote\\n\\nInterpreters 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.\\n\\nRunning in an Interpreter¶\\n\\nRunning 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 concurrent.interpreters module provides a basic API for creating and managing interpreters, as well as the switch-and-call operation.\\n\\nNo other threads are automatically started for the operation. There is a helper for that though. There is another dedicated helper for calling the builtin exec() in an interpreter.\\n\\nWhen exec() (or eval()) are called in an interpreter, they run using the interpreter’s __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 __main__ module.\\n\\nConcurrency and Parallelism¶\\n\\nAs 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.\\n\\nAll 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.\\n\\nYou 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.\\n\\nEach 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.\\n\\nAt a high level, you can think of the combination of threads and interpreters as threads with opt-in sharing.\\n\\nAs a significant bonus, interpreters are sufficiently isolated that they do not share the GIL, which means combining threads with multiple interpreters enables full multi-core parallelism. (This has been the case since Python 3.12.)\\n\\nCommunication Between Interpreters¶\\n\\nIn 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.\\n\\nWith this in mind, the concurrent.interpreters module provides a queue.Queue implementation, available through create_queue().\\n\\n“Sharing” Objects¶\\n\\nAny data actually shared between interpreters loses the thread-safety provided by the 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.\\n\\nBy default, most objects are copied with pickle when they are passed to another interpreter. Nearly all of the immutable builtin objects are either directly shared or copied efficiently. For example:\\n\\nNone\\n\\nbool (True and False)\\n\\nbytes\\n\\nstr\\n\\nint\\n\\nfloat\\n\\ntuple (of similarly supported objects)\\n\\nThere is a small number of Python types that actually share mutable data between interpreters:\\n\\nmemoryview\\n\\nQueue\\n\\nReference¶\\n\\nThis module defines the following functions:\\n\\nInterpreter objects¶\\n\\nExceptions¶\\n\\nCommunicating Between Interpreters¶\\n\\nBasic usage¶\\n\\nCreating an interpreter and running code in it:\\n\\nfrom concurrent import interpreters\\n\\ninterp = interpreters.create()\\n\\n# Run in the current OS thread.\\n\\ninterp.exec(\\'print(\"spam!\")\\')\\n\\ninterp.exec(\"\"\"if True:\\n print(\\'spam!\\')\\n \"\"\")\\n\\nfrom textwrap import dedent\\ninterp.exec(dedent(\"\"\"\\n print(\\'spam!\\')\\n \"\"\"))\\n\\ndef run(arg):\\n return arg\\n\\nres = interp.call(run, \\'spam!\\')\\nprint(res)\\n\\ndef run():\\n print(\\'spam!\\')\\n\\ninterp.call(run)\\n\\n# Run in new OS thread.\\n\\nt = interp.call_in_thread(run)\\nt.join()\\n\\nTable of Contents\\n\\nconcurrent.interpreters — Multiple interpreters in the same process\\n\\nKey details\\n\\nIntroduction\\n\\nMultiple Interpreters and Isolation\\n\\nRunning in an Interpreter\\n\\nConcurrency and Parallelism\\n\\nCommunication Between Interpreters\\n\\n“Sharing” Objects\\n\\nReference\\n\\nInterpreter objects\\n\\nExceptions\\n\\nCommunicating Between Interpreters\\n\\nBasic usage\\n\\nPrevious topic\\n\\nconcurrent.futures — Launching parallel tasks\\n\\nNext topic\\n\\nsubprocess — Subprocess management\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nConcurrent Execution »\\n\\nconcurrent.interpreters — Multiple interpreters in the same process\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\configparser.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nFile Formats »\\n\\nconfigparser — Configuration file parser\\n\\n|\\n\\nconfigparser — Configuration file parser¶\\n\\nSource code: Lib/configparser.py\\n\\nThis module provides the ConfigParser class which implements a basic configuration language which provides a structure similar to what’s found in Microsoft Windows INI files. You can use this to write Python programs which can be customized by end users easily.\\n\\nNote\\n\\nThis library does not interpret or write the value-type prefixes used in the Windows Registry extended version of INI syntax.\\n\\nSee also\\n\\nQuick Start¶\\n\\nLet’s take a very basic configuration file that looks like this:\\n\\n[DEFAULT]\\nServerAliveInterval = 45\\nCompression = yes\\nCompressionLevel = 9\\nForwardX11 = yes\\n\\n[forge.example]\\nUser = hg\\n\\n[topsecret.server.example]\\nPort = 50022\\nForwardX11 = no\\n\\nThe structure of INI files is described in the following section. Essentially, the file consists of sections, each of which contains keys with values. configparser classes can read and write such files. Let’s start by creating the above configuration file programmatically.\\n\\n>>> import configparser\\n>>> config = configparser.ConfigParser()\\n>>> config[\\'DEFAULT\\'] = {\\'ServerAliveInterval\\': \\'45\\',\\n... \\'Compression\\': \\'yes\\',\\n... \\'CompressionLevel\\': \\'9\\'}\\n>>> config[\\'forge.example\\'] = {}\\n>>> config[\\'forge.example\\'][\\'User\\'] = \\'hg\\'\\n>>> config[\\'topsecret.server.example\\'] = {}\\n>>> topsecret = config[\\'topsecret.server.example\\']\\n>>> topsecret[\\'Port\\'] = \\'50022\\' # mutates the parser\\n>>> topsecret[\\'ForwardX11\\'] = \\'no\\' # same here\\n>>> config[\\'DEFAULT\\'][\\'ForwardX11\\'] = \\'yes\\'\\n>>> with open(\\'example.ini\\', \\'w\\') as configfile:\\n... config.write(configfile)\\n...\\n\\nAs you can see, we can treat a config parser much like a dictionary. There are differences, outlined later, but the behavior is very close to what you would expect from a dictionary.\\n\\nNow that we have created and saved a configuration file, let’s read it back and explore the data it holds.\\n\\n>>> config = configparser.ConfigParser()\\n>>> config.sections()\\n[]\\n>>> config.read(\\'example.ini\\')\\n[\\'example.ini\\']\\n>>> config.sections()\\n[\\'forge.example\\', \\'topsecret.server.example\\']\\n>>> \\'forge.example\\' in config\\nTrue\\n>>> \\'python.org\\' in config\\nFalse\\n>>> config[\\'forge.example\\'][\\'User\\']\\n\\'hg\\'\\n>>> config[\\'DEFAULT\\'][\\'Compression\\']\\n\\'yes\\'\\n>>> topsecret = config[\\'topsecret.server.example\\']\\n>>> topsecret[\\'ForwardX11\\']\\n\\'no\\'\\n>>> topsecret[\\'Port\\']\\n\\'50022\\'\\n>>> for key in config[\\'forge.example\\']:\\n... print(key)\\nuser\\ncompressionlevel\\nserveraliveinterval\\ncompression\\nforwardx11\\n>>> config[\\'forge.example\\'][\\'ForwardX11\\']\\n\\'yes\\'\\n\\nAs we can see above, the API is pretty straightforward. The only bit of magic involves the DEFAULT section which provides default values for all other sections [1]. Note also that keys in sections are case-insensitive and stored in lowercase [1].\\n\\nIt is possible to read several configurations into a single 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 override.ini file, which will override any conflicting keys from the example.ini file.\\n\\n[DEFAULT]\\nServerAliveInterval = -1\\n\\n>>> config_override = configparser.ConfigParser()\\n>>> config_override[\\'DEFAULT\\'] = {\\'ServerAliveInterval\\': \\'-1\\'}\\n>>> with open(\\'override.ini\\', \\'w\\') as configfile:\\n... config_override.write(configfile)\\n...\\n>>> config_override = configparser.ConfigParser()\\n>>> config_override.read([\\'example.ini\\', \\'override.ini\\'])\\n[\\'example.ini\\', \\'override.ini\\']\\n>>> print(config_override.get(\\'DEFAULT\\', \\'ServerAliveInterval\\'))\\n-1\\n\\nThis behaviour is equivalent to a ConfigParser.read() call with several files passed to the filenames parameter.\\n\\nSupported Datatypes¶\\n\\nConfig parsers do not guess datatypes of values in configuration files, always storing them internally as strings. This means that if you need other datatypes, you should convert on your own:\\n\\n>>> int(topsecret[\\'Port\\'])\\n50022\\n>>> float(topsecret[\\'CompressionLevel\\'])\\n9.0\\n\\nSince this task is so common, config parsers provide a range of handy getter methods to handle integers, floats and booleans. The last one is the most interesting because simply passing the value to bool() would do no good since bool(\\'False\\') is still True. This is why config parsers also provide getboolean(). This method is case-insensitive and recognizes Boolean values from \\'yes\\'/\\'no\\', \\'on\\'/\\'off\\', \\'true\\'/\\'false\\' and \\'1\\'/\\'0\\' [1]. For example:\\n\\n>>> topsecret.getboolean(\\'ForwardX11\\')\\nFalse\\n>>> config[\\'forge.example\\'].getboolean(\\'ForwardX11\\')\\nTrue\\n>>> config.getboolean(\\'forge.example\\', \\'Compression\\')\\nTrue\\n\\nApart from getboolean(), config parsers also provide equivalent getint() and getfloat() methods. You can register your own converters and customize the provided ones. [1]\\n\\nFallback Values¶\\n\\nAs with a dictionary, you can use a section’s get() method to provide fallback values:\\n\\n>>> topsecret.get(\\'Port\\')\\n\\'50022\\'\\n>>> topsecret.get(\\'CompressionLevel\\')\\n\\'9\\'\\n>>> topsecret.get(\\'Cipher\\')\\n>>> topsecret.get(\\'Cipher\\', \\'3des-cbc\\')\\n\\'3des-cbc\\'\\n\\nPlease note that default values have precedence over fallback values. For instance, in our example the \\'CompressionLevel\\' key was specified only in the \\'DEFAULT\\' section. If we try to get it from the section \\'topsecret.server.example\\', we will always get the default, even if we specify a fallback:\\n\\n>>> topsecret.get(\\'CompressionLevel\\', \\'3\\')\\n\\'9\\'\\n\\nOne more thing to be aware of is that the parser-level get() method provides a custom, more complex interface, maintained for backwards compatibility. When using this method, a fallback value can be provided via the fallback keyword-only argument:\\n\\n>>> config.get(\\'forge.example\\', \\'monster\\',\\n... fallback=\\'No such things as monsters\\')\\n\\'No such things as monsters\\'\\n\\nThe same fallback argument can be used with the getint(), getfloat() and getboolean() methods, for example:\\n\\n>>> \\'BatchMode\\' in topsecret\\nFalse\\n>>> topsecret.getboolean(\\'BatchMode\\', fallback=True)\\nTrue\\n>>> config[\\'DEFAULT\\'][\\'BatchMode\\'] = \\'no\\'\\n>>> topsecret.getboolean(\\'BatchMode\\', fallback=True)\\nFalse\\n\\nSupported INI File Structure¶\\n\\nA configuration file consists of sections, each led by a [section] header, followed by key/value entries separated by a specific string (= or : by default [1]). By default, section names are case sensitive but keys are not [1]. Leading and trailing whitespace is removed from keys and values. Values can be omitted if the parser is configured to allow it [1], 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.\\n\\nBy default, a valid section name can be any string that does not contain ‘\\\\n’. To change this, see ConfigParser.SECTCRE.\\n\\nThe first section name may be omitted if the parser is configured to allow an unnamed top level section with allow_unnamed_section=True. In this case, the keys/values may be retrieved by UNNAMED_SECTION as in config[UNNAMED_SECTION].\\n\\nConfiguration files may include comments, prefixed by specific characters (# and ; by default [1]). Comments may appear on their own on an otherwise empty line, possibly indented. [1]\\n\\nFor example:\\n\\n[Simple Values]\\nkey=value\\nspaces in keys=allowed\\nspaces in values=allowed as well\\nspaces around the delimiter = obviously\\nyou can also use : to delimit keys from values\\n\\n[All Values Are Strings]\\nvalues like this: 1000000\\nor this: 3.14159265359\\nare they treated as numbers? : no\\nintegers, floats and booleans are held as: strings\\ncan use the API to get converted values directly: true\\n\\n[Multiline Values]\\nchorus: I\\'m a lumberjack, and I\\'m okay\\n I sleep all night and I work all day\\n\\n[No Values]\\nkey_without_value\\nempty string value here =\\n\\n[You can use comments]\\n# like this\\n; or this\\n\\n# By default only in an empty line.\\n# Inline comments can be harmful because they prevent users\\n# from using the delimiting characters as parts of values.\\n# That being said, this can be customized.\\n\\n [Sections Can Be Indented]\\n can_values_be_as_well = True\\n does_that_mean_anything_special = False\\n purpose = formatting for readability\\n multiline_values = are\\n handled just fine as\\n long as they are indented\\n deeper than the first line\\n of a value\\n # Did I mention we can indent comments, too?\\n\\nUnnamed Sections¶\\n\\nThe name of the first section (or unique) may be omitted and values retrieved by the UNNAMED_SECTION attribute.\\n\\n>>> config = \"\"\"\\n... option = value\\n...\\n... [ Section 2 ]\\n... another = val\\n... \"\"\"\\n>>> unnamed = configparser.ConfigParser(allow_unnamed_section=True)\\n>>> unnamed.read_string(config)\\n>>> unnamed.get(configparser.UNNAMED_SECTION, \\'option\\')\\n\\'value\\'\\n\\nInterpolation of values¶\\n\\nOn top of the core functionality, ConfigParser supports interpolation. This means values can be preprocessed before returning them from get() calls.\\n\\nMapping Protocol Access¶\\n\\nAdded in version 3.2.\\n\\nMapping protocol access is a generic name for functionality that enables using custom objects as if they were dictionaries. In case of configparser, the mapping interface implementation is using the parser[\\'section\\'][\\'option\\'] notation.\\n\\nparser[\\'section\\'] in particular returns a proxy for the section’s data in the parser. This means that the values are not copied but they are taken from the original parser on demand. What’s even more important is that when values are changed on a section proxy, they are actually mutated in the original parser.\\n\\nconfigparser objects behave as close to actual dictionaries as possible. The mapping interface is complete and adheres to the MutableMapping ABC. However, there are a few differences that should be taken into account:\\n\\nBy default, all keys in sections are accessible in a case-insensitive manner [1]. E.g. for option in parser[\"section\"] yields only optionxform’ed option key names. This means lowercased keys by default. At the same time, for a section that holds the key \\'a\\', both expressions return True:\\n\\n\"a\" in parser[\"section\"]\\n\"A\" in parser[\"section\"]\\n\\nAll sections include DEFAULTSECT values as well which means that .clear() on a section may not leave the section visibly empty. This is because default values cannot be deleted from the section (because technically they are not there). If they are overridden in the section, deleting causes the default value to be visible again. Trying to delete a default value causes a KeyError.\\n\\nDEFAULTSECT cannot be removed from the parser:\\n\\ntrying to delete it raises ValueError,\\n\\nparser.clear() leaves it intact,\\n\\nparser.popitem() never returns it.\\n\\nparser.get(section, option, **kwargs) - the second argument is not a fallback value. Note however that the section-level get() methods are compatible both with the mapping protocol and the classic configparser API.\\n\\nparser.items() is compatible with the mapping protocol (returns a list of section_name, section_proxy pairs including the DEFAULTSECT). However, this method can also be invoked with arguments: parser.items(section, raw, vars). The latter call returns a list of option, value pairs for a specified section, with all interpolations expanded (unless raw=True is provided).\\n\\nThe mapping protocol is implemented on top of the existing legacy API so that subclasses overriding the original interface still should have mappings working as expected.\\n\\nCustomizing Parser Behaviour¶\\n\\nThere are nearly as many INI format variants as there are applications using it. 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.\\n\\nThe most common way to change the way a specific config parser works is to use the __init__() options:\\n\\ndefaults, default value: None\\n\\nThis option accepts a dictionary of key-value pairs which will be initially put in the DEFAULT section. This makes for an elegant way to support concise configuration files that don’t specify values which are the same as the documented default.\\n\\nHint: if you want to specify default values for a specific section, use read_dict() before you read the actual file.\\n\\ndict_type, default value: dict\\n\\nThis option has a major impact on how the mapping protocol will behave and how the written configuration files look. With the standard dictionary, every section is stored in the order they were added to the parser. Same goes for options within sections.\\n\\nAn alternative dictionary type can be used for example to sort sections and options on write-back.\\n\\nPlease note: there are ways to add a set of key-value pairs in a single operation. When you use a regular dictionary in those operations, the order of the keys will be ordered. For example:\\n\\n>>> parser = configparser.ConfigParser()\\n>>> parser.read_dict({\\'section1\\': {\\'key1\\': \\'value1\\',\\n... \\'key2\\': \\'value2\\',\\n... \\'key3\\': \\'value3\\'},\\n... \\'section2\\': {\\'keyA\\': \\'valueA\\',\\n... \\'keyB\\': \\'valueB\\',\\n... \\'keyC\\': \\'valueC\\'},\\n... \\'section3\\': {\\'foo\\': \\'x\\',\\n... \\'bar\\': \\'y\\',\\n... \\'baz\\': \\'z\\'}\\n... })\\n>>> parser.sections()\\n[\\'section1\\', \\'section2\\', \\'section3\\']\\n>>> [option for option in parser[\\'section3\\']]\\n[\\'foo\\', \\'bar\\', \\'baz\\']\\n\\nallow_no_value, default value: False\\n\\nSome configuration files are known to include settings without values, but which otherwise conform to the syntax supported by configparser. The allow_no_value parameter to the constructor can be used to indicate that such values should be accepted:\\n\\n>>> import configparser\\n\\n>>> sample_config = \"\"\"\\n... [mysqld]\\n... user = mysql\\n... pid-file = /var/run/mysqld/mysqld.pid\\n... skip-external-locking\\n... old_passwords = 1\\n... skip-bdb\\n... # we don\\'t need ACID today\\n... skip-innodb\\n... \"\"\"\\n>>> config = configparser.ConfigParser(allow_no_value=True)\\n>>> config.read_string(sample_config)\\n\\n>>> # Settings with values are treated as before:\\n>>> config[\"mysqld\"][\"user\"]\\n\\'mysql\\'\\n\\n>>> # Settings without values provide None:\\n>>> config[\"mysqld\"][\"skip-bdb\"]\\n\\n>>> # Settings which aren\\'t specified still raise an error:\\n>>> config[\"mysqld\"][\"does-not-exist\"]\\nTraceback (most recent call last):\\n ...\\nKeyError: \\'does-not-exist\\'\\n\\ndelimiters, default value: (\\'=\\', \\':\\')\\n\\nDelimiters are substrings that delimit keys from values within a section. The first occurrence of a delimiting substring on a line is considered a delimiter. This means values (but not keys) can contain the delimiters.\\n\\nSee also the space_around_delimiters argument to ConfigParser.write().\\n\\ncomment_prefixes, default value: (\\'#\\', \\';\\')\\n\\ninline_comment_prefixes, default value: None\\n\\nComment prefixes are strings that indicate the start of a valid comment within a config file. comment_prefixes are used only on otherwise empty lines (optionally indented) whereas inline_comment_prefixes can be used after every valid value (e.g. section names, options and empty lines as well). By default inline comments are disabled and \\'#\\' and \\';\\' are used as prefixes for whole line comments.\\n\\nChanged in version 3.2: In previous versions of configparser behaviour matched comment_prefixes=(\\'#\\',\\';\\') and inline_comment_prefixes=(\\';\\',).\\n\\nPlease note that config parsers don’t support escaping of comment prefixes so using inline_comment_prefixes may prevent users from specifying option values with characters used as comment prefixes. When in doubt, avoid setting inline_comment_prefixes. In any circumstances, the only way of storing comment prefix characters at the beginning of a line in multiline values is to interpolate the prefix, for example:\\n\\n>>> from configparser import ConfigParser, ExtendedInterpolation\\n>>> parser = ConfigParser(interpolation=ExtendedInterpolation())\\n>>> # the default BasicInterpolation could be used as well\\n>>> parser.read_string(\"\"\"\\n... [DEFAULT]\\n... hash = #\\n...\\n... [hashes]\\n... shebang =\\n... ${hash}!/usr/bin/env python\\n... ${hash} -*- coding: utf-8 -*-\\n...\\n... extensions =\\n... enabled_extension\\n... another_extension\\n... #disabled_by_comment\\n... yet_another_extension\\n...\\n... interpolation not necessary = if # is not at line start\\n... even in multiline values = line #1\\n... line #2\\n... line #3\\n... \"\"\")\\n>>> print(parser[\\'hashes\\'][\\'shebang\\'])\\n\\n#!/usr/bin/env python\\n# -*- coding: utf-8 -*-\\n>>> print(parser[\\'hashes\\'][\\'extensions\\'])\\n\\nenabled_extension\\nanother_extension\\nyet_another_extension\\n>>> print(parser[\\'hashes\\'][\\'interpolation not necessary\\'])\\nif # is not at line start\\n>>> print(parser[\\'hashes\\'][\\'even in multiline values\\'])\\nline #1\\nline #2\\nline #3\\n\\nstrict, default value: True\\n\\nWhen set to True, the parser will not allow for any section or option duplicates while reading from a single source (using read_file(), read_string() or read_dict()). It is recommended to use strict parsers in new applications.\\n\\nChanged in version 3.2: In previous versions of configparser behaviour matched strict=False.\\n\\nempty_lines_in_values, default value: True\\n\\nIn config parsers, values can span multiple lines as long as they are indented more than the key that holds them. By default parsers also let empty lines to be parts of values. At the same time, keys can be arbitrarily indented themselves to improve readability. In consequence, when configuration files get big and complex, it is easy for the user to lose track of the file structure. Take for instance:\\n\\n[Section]\\nkey = multiline\\n value with a gotcha\\n\\n this = is still a part of the multiline value of \\'key\\'\\n\\nThis can be especially problematic for the user to see if she’s using a proportional font to edit the file. That is why when your application does not need values with empty lines, you should consider disallowing them. This will make empty lines split keys every time. In the example above, it would produce two keys, key and this.\\n\\ndefault_section, default value: configparser.DEFAULTSECT (that is: \"DEFAULT\")\\n\\nThe convention of allowing a special section of default values for other sections or interpolation purposes is a powerful concept of this library, letting users create complex declarative configurations. This section is normally called \"DEFAULT\" but this can be customized to point to any other valid section name. Some typical values include: \"general\" or \"common\". The name provided is used for recognizing default sections when reading from any source and is used when writing configuration back to a file. Its current value can be retrieved using the parser_instance.default_section attribute and may be modified at runtime (i.e. to convert files from one format to another).\\n\\ninterpolation, default value: configparser.BasicInterpolation\\n\\nInterpolation behaviour may be customized by providing a custom handler through the interpolation argument. None can be used to turn off interpolation completely, ExtendedInterpolation() provides a more advanced variant inspired by zc.buildout. More on the subject in the dedicated documentation section. RawConfigParser has a default value of None.\\n\\nconverters, default value: not set\\n\\nConfig parsers provide option value getters that perform type conversion. By default getint(), getfloat(), and 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 {\\'decimal\\': decimal.Decimal} would add getdecimal() on both the parser object and all section proxies. In other words, it will be possible to write both parser_instance.getdecimal(\\'section\\', \\'key\\', fallback=0) and parser_instance[\\'section\\'].getdecimal(\\'key\\', 0).\\n\\nIf the converter needs to access the state of the parser, it can be implemented as a method on a config parser subclass. If the name of this method starts with get, it will be available on all section proxies, in the dict-compatible form (see the getdecimal() example above).\\n\\nMore advanced customization may be achieved by overriding default values of these parser attributes. The defaults are defined on the classes, so they may be overridden by subclasses or by attribute assignment.\\n\\nLegacy API Examples¶\\n\\nMainly because of backwards compatibility concerns, configparser provides also a legacy API with explicit get/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.\\n\\nAn example of writing to a configuration file:\\n\\nimport configparser\\n\\nconfig = configparser.RawConfigParser()\\n\\n# Please note that using RawConfigParser\\'s set functions, you can assign\\n# non-string values to keys internally, but will receive an error when\\n# attempting to write to a file or when you get it in non-raw mode. Setting\\n# values using the mapping protocol or ConfigParser\\'s set() does not allow\\n# such assignments to take place.\\nconfig.add_section(\\'Section1\\')\\nconfig.set(\\'Section1\\', \\'an_int\\', \\'15\\')\\nconfig.set(\\'Section1\\', \\'a_bool\\', \\'true\\')\\nconfig.set(\\'Section1\\', \\'a_float\\', \\'3.1415\\')\\nconfig.set(\\'Section1\\', \\'baz\\', \\'fun\\')\\nconfig.set(\\'Section1\\', \\'bar\\', \\'Python\\')\\nconfig.set(\\'Section1\\', \\'foo\\', \\'%(bar)s is %(baz)s!\\')\\n\\n# Writing our configuration file to \\'example.cfg\\'\\nwith open(\\'example.cfg\\', \\'w\\') as configfile:\\n config.write(configfile)\\n\\nAn example of reading the configuration file again:\\n\\nimport configparser\\n\\nconfig = configparser.RawConfigParser()\\nconfig.read(\\'example.cfg\\')\\n\\n# getfloat() raises an exception if the value is not a float\\n# getint() and getboolean() also do this for their respective types\\na_float = config.getfloat(\\'Section1\\', \\'a_float\\')\\nan_int = config.getint(\\'Section1\\', \\'an_int\\')\\nprint(a_float + an_int)\\n\\n# Notice that the next output does not interpolate \\'%(bar)s\\' or \\'%(baz)s\\'.\\n# This is because we are using a RawConfigParser().\\nif config.getboolean(\\'Section1\\', \\'a_bool\\'):\\n print(config.get(\\'Section1\\', \\'foo\\'))\\n\\nTo get interpolation, use ConfigParser:\\n\\nimport configparser\\n\\ncfg = configparser.ConfigParser()\\ncfg.read(\\'example.cfg\\')\\n\\n# Set the optional *raw* argument of get() to True if you wish to disable\\n# interpolation in a single get operation.\\nprint(cfg.get(\\'Section1\\', \\'foo\\', raw=False)) # -> \"Python is fun!\"\\nprint(cfg.get(\\'Section1\\', \\'foo\\', raw=True)) # -> \"%(bar)s is %(baz)s!\"\\n\\n# The optional *vars* argument is a dict with members that will take\\n# precedence in interpolation.\\nprint(cfg.get(\\'Section1\\', \\'foo\\', vars={\\'bar\\': \\'Documentation\\',\\n \\'baz\\': \\'evil\\'}))\\n\\n# The optional *fallback* argument can be used to provide a fallback value\\nprint(cfg.get(\\'Section1\\', \\'foo\\'))\\n # -> \"Python is fun!\"\\n\\nprint(cfg.get(\\'Section1\\', \\'foo\\', fallback=\\'Monty is not.\\'))\\n # -> \"Python is fun!\"\\n\\nprint(cfg.get(\\'Section1\\', \\'monster\\', fallback=\\'No such things as monsters.\\'))\\n # -> \"No such things as monsters.\"\\n\\n# A bare print(cfg.get(\\'Section1\\', \\'monster\\')) would raise NoOptionError\\n# but we can also use:\\n\\nprint(cfg.get(\\'Section1\\', \\'monster\\', fallback=None))\\n # -> None\\n\\nDefault values are available in both types of ConfigParsers. They are used in interpolation if an option used is not defined elsewhere.\\n\\nimport configparser\\n\\n# New instance with \\'bar\\' and \\'baz\\' defaulting to \\'Life\\' and \\'hard\\' each\\nconfig = configparser.ConfigParser({\\'bar\\': \\'Life\\', \\'baz\\': \\'hard\\'})\\nconfig.read(\\'example.cfg\\')\\n\\nprint(config.get(\\'Section1\\', \\'foo\\')) # -> \"Python is fun!\"\\nconfig.remove_option(\\'Section1\\', \\'bar\\')\\nconfig.remove_option(\\'Section1\\', \\'baz\\')\\nprint(config.get(\\'Section1\\', \\'foo\\')) # -> \"Life is hard!\"\\n\\nConfigParser Objects¶\\n\\nRawConfigParser Objects¶\\n\\nExceptions¶\\n\\nFootnotes\\n\\n[1] (1,2,3,4,5,6,7,8,9,10,11)\\n\\nConfig parsers allow for heavy customization. If you are interested in changing the behaviour outlined by the footnote reference, consult the Customizing Parser Behaviour section.\\n\\nTable of Contents\\n\\nconfigparser — Configuration file parser\\n\\nQuick Start\\n\\nSupported Datatypes\\n\\nFallback Values\\n\\nSupported INI File Structure\\n\\nUnnamed Sections\\n\\nInterpolation of values\\n\\nMapping Protocol Access\\n\\nCustomizing Parser Behaviour\\n\\nLegacy API Examples\\n\\nConfigParser Objects\\n\\nRawConfigParser Objects\\n\\nExceptions\\n\\nPrevious topic\\n\\ncsv — CSV File Reading and Writing\\n\\nNext topic\\n\\ntomllib — Parse TOML files\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nFile Formats »\\n\\nconfigparser — Configuration file parser\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\constants.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nBuilt-in Constants\\n\\n|\\n\\nBuilt-in Constants¶\\n\\nA small number of constants live in the built-in namespace. They are:\\n\\nNote\\n\\nThe names None, False, True and __debug__ cannot be reassigned (assignments to them, even as an attribute name, raise SyntaxError), so they can be considered “true” constants.\\n\\nConstants added by the site module¶\\n\\nThe site module (which is imported automatically during startup, except if the -S command-line option is given) adds several constants to the built-in namespace. They are useful for the interactive interpreter shell and should not be used in programs.\\n\\nTable of Contents\\n\\nBuilt-in Constants\\n\\nConstants added by the site module\\n\\nPrevious topic\\n\\nBuilt-in Functions\\n\\nNext topic\\n\\nBuilt-in Types\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nBuilt-in Constants\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\contextlib.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Runtime Services »\\n\\ncontextlib — Utilities for with-statement contexts\\n\\n|\\n\\ncontextlib — Utilities for with-statement contexts¶\\n\\nSource code: Lib/contextlib.py\\n\\nThis module provides utilities for common tasks involving the with statement. For more information see also Context Manager Types and With Statement Context Managers.\\n\\nUtilities¶\\n\\nFunctions and classes provided:\\n\\nExamples and Recipes¶\\n\\nThis section describes some examples and recipes for making effective use of the tools provided by contextlib.\\n\\nSupporting a variable number of context managers¶\\n\\nThe primary use case for ExitStack is the one given in the class documentation: supporting a variable number of context managers and other cleanup operations in a single with statement. The variability may come from the number of context managers needed being driven by user input (such as opening a user specified collection of files), or from some of the context managers being optional:\\n\\nwith ExitStack() as stack:\\n for resource in resources:\\n stack.enter_context(resource)\\n if need_special_resource():\\n special = acquire_special_resource()\\n stack.callback(release_special_resource, special)\\n # Perform operations that use the acquired resources\\n\\nAs shown, ExitStack also makes it quite easy to use with statements to manage arbitrary resources that don’t natively support the context management protocol.\\n\\nCatching exceptions from __enter__ methods¶\\n\\nIt is occasionally desirable to catch exceptions from an __enter__() method implementation, without inadvertently catching exceptions from the with statement body or the context manager’s __exit__() method. By using ExitStack the steps in the context management protocol can be separated slightly in order to allow this:\\n\\nstack = ExitStack()\\ntry:\\n x = stack.enter_context(cm)\\nexcept Exception:\\n # handle __enter__ exception\\nelse:\\n with stack:\\n # Handle normal case\\n\\nActually needing to do this is likely to indicate that the underlying API should be providing a direct resource management interface for use with try/except/finally statements, but not all APIs are well designed in that regard. When a context manager is the only resource management API provided, then ExitStack can make it easier to handle various situations that can’t be handled directly in a with statement.\\n\\nCleaning up in an __enter__ implementation¶\\n\\nAs noted in the documentation of ExitStack.push(), this method can be useful in cleaning up an already allocated resource if later steps in the __enter__() implementation fail.\\n\\nHere’s an example of doing this for a context manager that accepts resource acquisition and release functions, along with an optional validation function, and maps them to the context management protocol:\\n\\nfrom contextlib import contextmanager, AbstractContextManager, ExitStack\\n\\nclass ResourceManager(AbstractContextManager):\\n\\n def __init__(self, acquire_resource, release_resource, check_resource_ok=None):\\n self.acquire_resource = acquire_resource\\n self.release_resource = release_resource\\n if check_resource_ok is None:\\n def check_resource_ok(resource):\\n return True\\n self.check_resource_ok = check_resource_ok\\n\\n @contextmanager\\n def _cleanup_on_error(self):\\n with ExitStack() as stack:\\n stack.push(self)\\n yield\\n # The validation check passed and didn\\'t raise an exception\\n # Accordingly, we want to keep the resource, and pass it\\n # back to our caller\\n stack.pop_all()\\n\\n def __enter__(self):\\n resource = self.acquire_resource()\\n with self._cleanup_on_error():\\n if not self.check_resource_ok(resource):\\n msg = \"Failed validation for {!r}\"\\n raise RuntimeError(msg.format(resource))\\n return resource\\n\\n def __exit__(self, *exc_details):\\n # We don\\'t need to duplicate any of our resource release logic\\n self.release_resource()\\n\\nReplacing any use of try-finally and flag variables¶\\n\\nA pattern you will sometimes see is a try-finally statement with a flag variable to indicate whether or not the body of the finally clause should be executed. In its simplest form (that can’t already be handled just by using an except clause instead), it looks something like this:\\n\\ncleanup_needed = True\\ntry:\\n result = perform_operation()\\n if result:\\n cleanup_needed = False\\nfinally:\\n if cleanup_needed:\\n cleanup_resources()\\n\\nAs with any try statement based code, this can cause problems for development and review, because the setup code and the cleanup code can end up being separated by arbitrarily long sections of code.\\n\\nExitStack makes it possible to instead register a callback for execution at the end of a with statement, and then later decide to skip executing that callback:\\n\\nfrom contextlib import ExitStack\\n\\nwith ExitStack() as stack:\\n stack.callback(cleanup_resources)\\n result = perform_operation()\\n if result:\\n stack.pop_all()\\n\\nThis allows the intended cleanup behaviour to be made explicit up front, rather than requiring a separate flag variable.\\n\\nIf a particular application uses this pattern a lot, it can be simplified even further by means of a small helper class:\\n\\nfrom contextlib import ExitStack\\n\\nclass Callback(ExitStack):\\n def __init__(self, callback, /, *args, **kwds):\\n super().__init__()\\n self.callback(callback, *args, **kwds)\\n\\n def cancel(self):\\n self.pop_all()\\n\\nwith Callback(cleanup_resources) as cb:\\n result = perform_operation()\\n if result:\\n cb.cancel()\\n\\nIf the resource cleanup isn’t already neatly bundled into a standalone function, then it is still possible to use the decorator form of ExitStack.callback() to declare the resource cleanup in advance:\\n\\nfrom contextlib import ExitStack\\n\\nwith ExitStack() as stack:\\n @stack.callback\\n def cleanup_resources():\\n ...\\n result = perform_operation()\\n if result:\\n stack.pop_all()\\n\\nDue to the way the decorator protocol works, a callback function declared this way cannot take any parameters. Instead, any resources to be released must be accessed as closure variables.\\n\\nUsing a context manager as a function decorator¶\\n\\nContextDecorator makes it possible to use a context manager in both an ordinary with statement and also as a function decorator.\\n\\nFor example, it is sometimes useful to wrap functions or groups of statements with a logger that can track the time of entry and time of exit. Rather than writing both a function decorator and a context manager for the task, inheriting from ContextDecorator provides both capabilities in a single definition:\\n\\nfrom contextlib import ContextDecorator\\nimport logging\\n\\nlogging.basicConfig(level=logging.INFO)\\n\\nclass track_entry_and_exit(ContextDecorator):\\n def __init__(self, name):\\n self.name = name\\n\\n def __enter__(self):\\n logging.info(\\'Entering: %s\\', self.name)\\n\\n def __exit__(self, exc_type, exc, exc_tb):\\n logging.info(\\'Exiting: %s\\', self.name)\\n\\nInstances of this class can be used as both a context manager:\\n\\nwith track_entry_and_exit(\\'widget loader\\'):\\n print(\\'Some time consuming activity goes here\\')\\n load_widget()\\n\\nAnd also as a function decorator:\\n\\n@track_entry_and_exit(\\'widget loader\\')\\ndef activity():\\n print(\\'Some time consuming activity goes here\\')\\n load_widget()\\n\\nNote that there is one additional limitation when using context managers as function decorators: there’s no way to access the return value of __enter__(). If that value is needed, then it is still necessary to use an explicit with statement.\\n\\nSee also\\n\\nSingle use, reusable and reentrant context managers¶\\n\\nMost context managers are written in a way that means they can only be used effectively in a with statement once. These single use context managers must be created afresh each time they’re used - attempting to use them a second time will trigger an exception or otherwise not work correctly.\\n\\nThis common limitation means that it is generally advisable to create context managers directly in the header of the with statement where they are used (as shown in all of the usage examples above).\\n\\nFiles are an example of effectively single use context managers, since the first with statement will close the file, preventing any further IO operations using that file object.\\n\\nContext managers created using contextmanager() are also single use context managers, and will complain about the underlying generator failing to yield if an attempt is made to use them a second time:\\n\\n>>> from contextlib import contextmanager\\n>>> @contextmanager\\n... def singleuse():\\n... print(\"Before\")\\n... yield\\n... print(\"After\")\\n...\\n>>> cm = singleuse()\\n>>> with cm:\\n... pass\\n...\\nBefore\\nAfter\\n>>> with cm:\\n... pass\\n...\\nTraceback (most recent call last):\\n ...\\nRuntimeError: generator didn\\'t yield\\n\\nReentrant context managers¶\\n\\nMore sophisticated context managers may be “reentrant”. These context managers can not only be used in multiple with statements, but may also be used inside a with statement that is already using the same context manager.\\n\\nthreading.RLock is an example of a reentrant context manager, as are suppress(), redirect_stdout(), and chdir(). Here’s a very simple example of reentrant use:\\n\\n>>> from contextlib import redirect_stdout\\n>>> from io import StringIO\\n>>> stream = StringIO()\\n>>> write_to_stream = redirect_stdout(stream)\\n>>> with write_to_stream:\\n... print(\"This is written to the stream rather than stdout\")\\n... with write_to_stream:\\n... print(\"This is also written to the stream\")\\n...\\n>>> print(\"This is written directly to stdout\")\\nThis is written directly to stdout\\n>>> print(stream.getvalue())\\nThis is written to the stream rather than stdout\\nThis is also written to the stream\\n\\nReal world examples of reentrancy are more likely to involve multiple functions calling each other and hence be far more complicated than this example.\\n\\nNote also that being reentrant is not the same thing as being thread safe. redirect_stdout(), for example, is definitely not thread safe, as it makes a global modification to the system state by binding sys.stdout to a different stream.\\n\\nReusable context managers¶\\n\\nDistinct from both single use and reentrant context managers are “reusable” context managers (or, to be completely explicit, “reusable, but not reentrant” context managers, since reentrant context managers are also reusable). These context managers support being used multiple times, but will fail (or otherwise not work correctly) if the specific context manager instance has already been used in a containing with statement.\\n\\nthreading.Lock is an example of a reusable, but not reentrant, context manager (for a reentrant lock, it is necessary to use threading.RLock instead).\\n\\nAnother example of a reusable, but not reentrant, context manager is ExitStack, as it invokes all currently registered callbacks when leaving any with statement, regardless of where those callbacks were added:\\n\\n>>> from contextlib import ExitStack\\n>>> stack = ExitStack()\\n>>> with stack:\\n... stack.callback(print, \"Callback: from first context\")\\n... print(\"Leaving first context\")\\n...\\nLeaving first context\\nCallback: from first context\\n>>> with stack:\\n... stack.callback(print, \"Callback: from second context\")\\n... print(\"Leaving second context\")\\n...\\nLeaving second context\\nCallback: from second context\\n>>> with stack:\\n... stack.callback(print, \"Callback: from outer context\")\\n... with stack:\\n... stack.callback(print, \"Callback: from inner context\")\\n... print(\"Leaving inner context\")\\n... print(\"Leaving outer context\")\\n...\\nLeaving inner context\\nCallback: from inner context\\nCallback: from outer context\\nLeaving outer context\\n\\nAs the output from the example shows, reusing a single stack object across multiple with statements works correctly, but attempting to nest them will cause the stack to be cleared at the end of the innermost with statement, which is unlikely to be desirable behaviour.\\n\\nUsing separate ExitStack instances instead of reusing a single instance avoids that problem:\\n\\n>>> from contextlib import ExitStack\\n>>> with ExitStack() as outer_stack:\\n... outer_stack.callback(print, \"Callback: from outer context\")\\n... with ExitStack() as inner_stack:\\n... inner_stack.callback(print, \"Callback: from inner context\")\\n... print(\"Leaving inner context\")\\n... print(\"Leaving outer context\")\\n...\\nLeaving inner context\\nCallback: from inner context\\nLeaving outer context\\nCallback: from outer context\\n\\nTable of Contents\\n\\ncontextlib — Utilities for with-statement contexts\\n\\nUtilities\\n\\nExamples and Recipes\\n\\nSupporting a variable number of context managers\\n\\nCatching exceptions from __enter__ methods\\n\\nCleaning up in an __enter__ implementation\\n\\nReplacing any use of try-finally and flag variables\\n\\nUsing a context manager as a function decorator\\n\\nSingle use, reusable and reentrant context managers\\n\\nReentrant context managers\\n\\nReusable context managers\\n\\nPrevious topic\\n\\ndataclasses — Data Classes\\n\\nNext topic\\n\\nabc — Abstract Base Classes\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Runtime Services »\\n\\ncontextlib — Utilities for with-statement contexts\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\contextvars.html'}, page_content=\"Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nConcurrent Execution »\\n\\ncontextvars — Context Variables\\n\\n|\\n\\ncontextvars — Context Variables¶\\n\\nThis module provides APIs to manage, store, and access context-local state. The ContextVar class is used to declare and work with Context Variables. The copy_context() function and the Context class should be used to manage the current context in asynchronous frameworks.\\n\\nContext managers that have state should use Context Variables instead of threading.local() to prevent their state from bleeding to other code unexpectedly, when used in concurrent code.\\n\\nSee also PEP 567 for additional details.\\n\\nAdded in version 3.7.\\n\\nContext Variables¶\\n\\nManual Context Management¶\\n\\nasyncio support¶\\n\\nContext variables are natively supported in asyncio and are ready to be used without any extra configuration. For example, here is a simple echo server, that uses a context variable to make the address of a remote client available in the Task that handles that client:\\n\\nimport asyncio\\nimport contextvars\\n\\nclient_addr_var = contextvars.ContextVar('client_addr')\\n\\ndef render_goodbye():\\n # The address of the currently handled client can be accessed\\n # without passing it explicitly to this function.\\n\\n client_addr = client_addr_var.get()\\n return f'Good bye, client @ {client_addr}\\\\r\\\\n'.encode()\\n\\nasync def handle_request(reader, writer):\\n addr = writer.transport.get_extra_info('socket').getpeername()\\n client_addr_var.set(addr)\\n\\n # In any code that we call, it is now possible to get the\\n # client's address by calling 'client_addr_var.get()'.\\n\\n while True:\\n line = await reader.readline()\\n print(line)\\n if not line.strip():\\n break\\n\\n writer.write(b'HTTP/1.1 200 OK\\\\r\\\\n') # status line\\n writer.write(b'\\\\r\\\\n') # headers\\n writer.write(render_goodbye()) # body\\n writer.close()\\n\\nasync def main():\\n srv = await asyncio.start_server(\\n handle_request, '127.0.0.1', 8081)\\n\\n async with srv:\\n await srv.serve_forever()\\n\\nasyncio.run(main())\\n\\n# To test it you can use telnet or curl:\\n# telnet 127.0.0.1 8081\\n# curl 127.0.0.1:8081\\n\\nTable of Contents\\n\\ncontextvars — Context Variables\\n\\nContext Variables\\n\\nManual Context Management\\n\\nasyncio support\\n\\nPrevious topic\\n\\nqueue — A synchronized queue class\\n\\nNext topic\\n\\n_thread — Low-level threading API\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nConcurrent Execution »\\n\\ncontextvars — Context Variables\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.\"), Document(metadata={'source': '..\\\\..\\\\docs\\\\copy.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Types »\\n\\ncopy — Shallow and deep copy operations\\n\\n|\\n\\ncopy — Shallow and deep copy operations¶\\n\\nSource code: Lib/copy.py\\n\\nAssignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other. This module provides generic shallow and deep copy operations (explained below).\\n\\nInterface summary:\\n\\nThe difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):\\n\\nA shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.\\n\\nA deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.\\n\\nTwo problems often exist with deep copy operations that don’t exist with shallow copy operations:\\n\\nRecursive objects (compound objects that, directly or indirectly, contain a reference to themselves) may cause a recursive loop.\\n\\nBecause deep copy copies everything it may copy too much, such as data which is intended to be shared between copies.\\n\\nThe deepcopy() function avoids these problems by:\\n\\nkeeping a memo dictionary of objects already copied during the current copying pass; and\\n\\nletting user-defined classes override the copying operation or the set of components copied.\\n\\nThis module does not copy types like module, method, stack trace, stack frame, file, socket, window, or any similar types. It does “copy” functions and classes (shallow and deeply), by returning the original object unchanged; this is compatible with the way these are treated by the pickle module.\\n\\nShallow copies of dictionaries can be made using dict.copy(), and of lists by assigning a slice of the entire list, for example, copied_list = original_list[:].\\n\\nClasses can use the same interfaces to control copying that they use to control pickling. See the description of module pickle for information on these methods. In fact, the copy module uses the registered pickle functions from the copyreg module.\\n\\nIn order for a class to define its own copy implementation, it can define special methods __copy__() and __deepcopy__().\\n\\nFunction copy.replace() is more limited than copy() and deepcopy(), and only supports named tuples created by namedtuple(), dataclasses, and other classes which define method __replace__().\\n\\nSee also\\n\\nPrevious topic\\n\\ntypes — Dynamic type creation and names for built-in types\\n\\nNext topic\\n\\npprint — Data pretty printer\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Types »\\n\\ncopy — Shallow and deep copy operations\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\copyreg.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Persistence »\\n\\ncopyreg — Register pickle support functions\\n\\n|\\n\\ncopyreg — Register pickle support functions¶\\n\\nSource code: Lib/copyreg.py\\n\\nThe copyreg module offers a way to define functions used while pickling specific objects. The pickle and 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.\\n\\nExample¶\\n\\nThe example below would like to show how to register a pickle function and how it will be used:\\n\\n>>> import copyreg, copy, pickle\\n>>> class C:\\n... def __init__(self, a):\\n... self.a = a\\n...\\n>>> def pickle_c(c):\\n... print(\"pickling a C instance...\")\\n... return C, (c.a,)\\n...\\n>>> copyreg.pickle(C, pickle_c)\\n>>> c = C(1)\\n>>> d = copy.copy(c)\\npickling a C instance...\\n>>> p = pickle.dumps(c)\\npickling a C instance...\\n\\nTable of Contents\\n\\ncopyreg — Register pickle support functions\\n\\nExample\\n\\nPrevious topic\\n\\npickle — Python object serialization\\n\\nNext topic\\n\\nshelve — Python object persistence\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Persistence »\\n\\ncopyreg — Register pickle support functions\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\crypt.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nRemoved Modules »\\n\\ncrypt — Function to check Unix passwords\\n\\n|\\n\\ncrypt — Function to check Unix passwords¶\\n\\nDeprecated since version 3.11, removed in version 3.13.\\n\\nThis module is no longer part of the Python standard library. It was removed in Python 3.13 after being deprecated in Python 3.11. The removal was decided in PEP 594.\\n\\nApplications can use the hashlib module from the standard library. Other possible replacements are third-party libraries from PyPI: legacycrypt, bcrypt, or argon2-cffi. These are not supported or maintained by the Python core team.\\n\\nThe last version of Python that provided the crypt module was Python 3.12.\\n\\nPrevious topic\\n\\nchunk — Read IFF chunked data\\n\\nNext topic\\n\\ndistutils — Building and installing Python modules\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nRemoved Modules »\\n\\ncrypt — Function to check Unix passwords\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\crypto.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nCryptographic Services\\n\\n|\\n\\nCryptographic Services¶\\n\\nThe modules described in this chapter implement various algorithms of a cryptographic nature. They are available at the discretion of the installation. Here’s an overview:\\n\\nhashlib — Secure hashes and message digests\\n\\nHash algorithms\\n\\nUsage\\n\\nConstructors\\n\\nAttributes\\n\\nHash Objects\\n\\nSHAKE variable length digests\\n\\nFile hashing\\n\\nKey derivation\\n\\nBLAKE2\\n\\nCreating hash objects\\n\\nConstants\\n\\nExamples\\n\\nSimple hashing\\n\\nUsing different digest sizes\\n\\nKeyed hashing\\n\\nRandomized hashing\\n\\nPersonalization\\n\\nTree mode\\n\\nCredits\\n\\nhmac — Keyed-Hashing for Message Authentication\\n\\nsecrets — Generate secure random numbers for managing secrets\\n\\nRandom numbers\\n\\nGenerating tokens\\n\\nHow many bytes should tokens use?\\n\\nOther functions\\n\\nRecipes and best practices\\n\\nPrevious topic\\n\\nplistlib — Generate and parse Apple .plist files\\n\\nNext topic\\n\\nhashlib — Secure hashes and message digests\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nCryptographic Services\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\csv.html'}, page_content=\"Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nFile Formats »\\n\\ncsv — CSV File Reading and Writing\\n\\n|\\n\\ncsv — CSV File Reading and Writing¶\\n\\nSource code: Lib/csv.py\\n\\nThe so-called CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. CSV format was used for many years prior to attempts to describe the format in a standardized way in RFC 4180. The lack of a well-defined standard means that subtle differences often exist in the data produced and consumed by different applications. These differences can make it annoying to process CSV files from multiple sources. Still, while the delimiters and quoting characters vary, the overall format is similar enough that it is possible to write a single module which can efficiently manipulate such data, hiding the details of reading and writing the data from the programmer.\\n\\nThe 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.\\n\\nThe csv module’s reader and writer objects read and write sequences. Programmers can also read and write data in dictionary form using the DictReader and DictWriter classes.\\n\\nSee also\\n\\nModule Contents¶\\n\\nThe csv module defines the following functions:\\n\\nThe csv module defines the following classes:\\n\\nAn example for Sniffer use:\\n\\nwith open('example.csv', newline='') as csvfile:\\n dialect = csv.Sniffer().sniff(csvfile.read(1024))\\n csvfile.seek(0)\\n reader = csv.reader(csvfile, dialect)\\n # ... process CSV file contents here ...\\n\\nThe csv module defines the following constants:\\n\\nThe csv module defines the following exception:\\n\\nDialects and Formatting Parameters¶\\n\\nTo 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 Dialect class containing various attributes describing the format of the CSV file. When creating reader or writer objects, the programmer can specify a string or a subclass of the 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 Dialect class.\\n\\nDialects support the following attributes:\\n\\nReader Objects¶\\n\\nReader objects (DictReader instances and objects returned by the reader() function) have the following public methods:\\n\\nReader objects have the following public attributes:\\n\\nDictReader objects have the following public attribute:\\n\\nWriter Objects¶\\n\\nwriter objects (DictWriter instances and objects returned by the writer() function) have the following public methods. A row must be an iterable of strings or numbers for writer objects and a dictionary mapping fieldnames to strings or numbers (by passing them through str() first) for DictWriter objects. Note that complex numbers are written out surrounded by parens. This may cause some problems for other programs which read CSV files (assuming they support complex numbers at all).\\n\\nWriter objects have the following public attribute:\\n\\nDictWriter objects have the following public method:\\n\\nExamples¶\\n\\nThe simplest example of reading a CSV file:\\n\\nimport csv\\nwith open('some.csv', newline='') as f:\\n reader = csv.reader(f)\\n for row in reader:\\n print(row)\\n\\nReading a file with an alternate format:\\n\\nimport csv\\nwith open('passwd', newline='') as f:\\n reader = csv.reader(f, delimiter=':', quoting=csv.QUOTE_NONE)\\n for row in reader:\\n print(row)\\n\\nThe corresponding simplest possible writing example is:\\n\\nimport csv\\nwith open('some.csv', 'w', newline='') as f:\\n writer = csv.writer(f)\\n writer.writerows(someiterable)\\n\\nSince open() is used to open a CSV file for reading, the file will by default be decoded into unicode using the system default encoding (see locale.getencoding()). To decode a file using a different encoding, use the encoding argument of open:\\n\\nimport csv\\nwith open('some.csv', newline='', encoding='utf-8') as f:\\n reader = csv.reader(f)\\n for row in reader:\\n print(row)\\n\\nThe same applies to writing in something other than the system default encoding: specify the encoding argument when opening the output file.\\n\\nRegistering a new dialect:\\n\\nimport csv\\ncsv.register_dialect('unixpwd', delimiter=':', quoting=csv.QUOTE_NONE)\\nwith open('passwd', newline='') as f:\\n reader = csv.reader(f, 'unixpwd')\\n\\nA slightly more advanced use of the reader — catching and reporting errors:\\n\\nimport csv, sys\\nfilename = 'some.csv'\\nwith open(filename, newline='') as f:\\n reader = csv.reader(f)\\n try:\\n for row in reader:\\n print(row)\\n except csv.Error as e:\\n sys.exit(f'file {filename}, line {reader.line_num}: {e}')\\n\\nAnd while the module doesn’t directly support parsing strings, it can easily be done:\\n\\nimport csv\\nfor row in csv.reader(['one,two,three']):\\n print(row)\\n\\nFootnotes\\n\\n[1] (1,2)\\n\\nIf newline='' is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms that use \\\\r\\\\n line endings on write an extra \\\\r will be added. It should always be safe to specify newline='', since the csv module does its own (universal) newline handling.\\n\\nTable of Contents\\n\\ncsv — CSV File Reading and Writing\\n\\nModule Contents\\n\\nDialects and Formatting Parameters\\n\\nReader Objects\\n\\nWriter Objects\\n\\nExamples\\n\\nPrevious topic\\n\\nFile Formats\\n\\nNext topic\\n\\nconfigparser — Configuration file parser\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nFile Formats »\\n\\ncsv — CSV File Reading and Writing\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.\"), Document(metadata={'source': '..\\\\..\\\\docs\\\\ctypes.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nGeneric Operating System Services »\\n\\nctypes — A foreign function library for Python\\n\\n|\\n\\nctypes — A foreign function library for Python¶\\n\\nSource code: Lib/ctypes\\n\\nctypes 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.\\n\\nThis is an 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 Requirements for optional modules.\\n\\nctypes tutorial¶\\n\\nNote: Some code samples reference the ctypes c_int type. On platforms where sizeof(long) == sizeof(int) it is an alias to c_long. So, you should not be confused if c_long is printed if you would expect c_int — they are actually the same type.\\n\\nLoading dynamic link libraries¶\\n\\nctypes exports the cdll, and on Windows windll and oledll objects, for loading dynamic link libraries.\\n\\nYou load libraries by accessing them as attributes of these objects. cdll loads libraries which export functions using the standard cdecl calling convention, while windll libraries call functions using the stdcall calling convention. oledll also uses the stdcall calling convention, and assumes the functions return a Windows HRESULT error code. The error code is used to automatically raise an OSError exception when the function call fails.\\n\\nChanged in version 3.3: Windows errors used to raise WindowsError, which is now an alias of OSError.\\n\\nHere are some examples for Windows. Note that msvcrt is the MS standard C library containing most standard C functions, and uses the cdecl calling convention:\\n\\n>>> from ctypes import *\\n>>> print(windll.kernel32)\\n\\n>>> print(cdll.msvcrt)\\n\\n>>> libc = cdll.msvcrt\\n>>>\\n\\nWindows appends the usual .dll file suffix automatically.\\n\\nNote\\n\\nAccessing the standard C library through cdll.msvcrt will use an outdated version of the library that may be incompatible with the one being used by Python. Where possible, use native Python functionality, or else import and use the msvcrt module.\\n\\nOther systems require the filename including the extension to load a library, so attribute access can not be used to load libraries. Either the 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.\\n\\nFor example, on Linux:\\n\\n>>> cdll.LoadLibrary(\"libc.so.6\")\\n\\n>>> libc = CDLL(\"libc.so.6\")\\n>>> libc\\n\\n>>>\\n\\nOn macOS:\\n\\n>>> cdll.LoadLibrary(\"libc.dylib\")\\n\\n>>> libc = CDLL(\"libc.dylib\")\\n>>> libc\\n\\n\\nAccessing functions from loaded dlls¶\\n\\nFunctions are accessed as attributes of dll objects:\\n\\n>>> libc.printf\\n<_FuncPtr object at 0x...>\\n>>> print(windll.kernel32.GetModuleHandleA)\\n<_FuncPtr object at 0x...>\\n>>> print(windll.kernel32.MyOwnFunction)\\nTraceback (most recent call last):\\n File \"\", line 1, in \\n File \"ctypes.py\", line 239, in __getattr__\\n func = _StdcallFuncPtr(name, self)\\nAttributeError: function \\'MyOwnFunction\\' not found\\n>>>\\n\\nNote that win32 system dlls like kernel32 and user32 often export ANSI as well as UNICODE versions of a function. The UNICODE version is exported with a W appended to the name, while the ANSI version is exported with an A appended to the name. The win32 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 GetModuleHandle depending on whether UNICODE is defined or not:\\n\\n/* ANSI version */\\nHMODULE GetModuleHandleA(LPCSTR lpModuleName);\\n/* UNICODE version */\\nHMODULE GetModuleHandleW(LPCWSTR lpModuleName);\\n\\nwindll does not try to select one of them by magic, you must access the version you need by specifying GetModuleHandleA or GetModuleHandleW explicitly, and then call it with bytes or string objects respectively.\\n\\nSometimes, dlls export functions with names which aren’t valid Python identifiers, like \"??2@YAPAXI@Z\". In this case you have to use getattr() to retrieve the function:\\n\\n>>> getattr(cdll.msvcrt, \"??2@YAPAXI@Z\")\\n<_FuncPtr object at 0x...>\\n>>>\\n\\nOn Windows, some dlls export functions not by name but by ordinal. These functions can be accessed by indexing the dll object with the ordinal number:\\n\\n>>> cdll.kernel32[1]\\n<_FuncPtr object at 0x...>\\n>>> cdll.kernel32[0]\\nTraceback (most recent call last):\\n File \"\", line 1, in \\n File \"ctypes.py\", line 310, in __getitem__\\n func = _StdcallFuncPtr(name, self)\\nAttributeError: function ordinal 0 not found\\n>>>\\n\\nCalling functions¶\\n\\nYou can call these functions like any other Python callable. This example uses the rand() function, which takes no arguments and returns a pseudo-random integer:\\n\\n>>> print(libc.rand())\\n1804289383\\n\\nOn Windows, you can call the GetModuleHandleA() function, which returns a win32 module handle (passing None as single argument to call it with a NULL pointer):\\n\\n>>> print(hex(windll.kernel32.GetModuleHandleA(None)))\\n0x1d000000\\n>>>\\n\\nValueError is raised when you call an stdcall function with the cdecl calling convention, or vice versa:\\n\\n>>> cdll.kernel32.GetModuleHandleA(None)\\nTraceback (most recent call last):\\n File \"\", line 1, in \\nValueError: Procedure probably called with not enough arguments (4 bytes missing)\\n>>>\\n\\n>>> windll.msvcrt.printf(b\"spam\")\\nTraceback (most recent call last):\\n File \"\", line 1, in \\nValueError: Procedure probably called with too many arguments (4 bytes in excess)\\n>>>\\n\\nTo find out the correct calling convention you have to look into the C header file or the documentation for the function you want to call.\\n\\nOn Windows, ctypes uses win32 structured exception handling to prevent crashes from general protection faults when functions are called with invalid argument values:\\n\\n>>> windll.kernel32.GetModuleHandleA(32)\\nTraceback (most recent call last):\\n File \"\", line 1, in \\nOSError: exception: access violation reading 0x00000020\\n>>>\\n\\nThere are, however, enough ways to crash Python with ctypes, so you should be careful anyway. The faulthandler module can be helpful in debugging crashes (e.g. from segmentation faults produced by erroneous C library calls).\\n\\nNone, integers, bytes objects and (unicode) strings are the only native Python objects that can directly be used as parameters in these function calls. None is passed as a C 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.\\n\\nBefore we move on calling functions with other parameter types, we have to learn more about ctypes data types.\\n\\nFundamental data types¶\\n\\nctypes defines a number of primitive C compatible data types:\\n\\nctypes type C type Python type c_bool _Bool bool (1) c_char char 1-character bytes object c_wchar wchar_t 1-character string c_byte char int c_ubyte unsigned char int c_short short int c_ushort unsigned short int c_int int int c_int8 int8_t int c_int16 int16_t int c_int32 int32_t int c_int64 int64_t int c_uint unsigned int int c_uint8 uint8_t int c_uint16 uint16_t int c_uint32 uint32_t int c_uint64 uint64_t int c_long long int c_ulong unsigned long int c_longlong __int64 or long long int c_ulonglong unsigned __int64 or unsigned long long int c_size_t size_t int c_ssize_t ssize_t or Py_ssize_t int c_time_t time_t int c_float float float c_double double float c_longdouble long double float c_char_p char * (NUL terminated) bytes object or None c_wchar_p wchar_t * (NUL terminated) string or None c_void_p void * int or None\\n\\nThe constructor accepts any object with a truth value.\\n\\nAdditionally, if IEC 60559 compatible complex arithmetic (Annex G) is supported in both C and libffi, the following complex types are available:\\n\\nctypes type C type Python type c_float_complex float complex complex c_double_complex double complex complex c_longdouble_complex long double complex complex\\n\\nAll these types can be created by calling them with an optional initializer of the correct type and value:\\n\\n>>> c_int()\\nc_long(0)\\n>>> c_wchar_p(\"Hello, World\")\\nc_wchar_p(140018365411392)\\n>>> c_ushort(-3)\\nc_ushort(65533)\\n>>>\\n\\nSince these types are mutable, their value can also be changed afterwards:\\n\\n>>> i = c_int(42)\\n>>> print(i)\\nc_long(42)\\n>>> print(i.value)\\n42\\n>>> i.value = -99\\n>>> print(i.value)\\n-99\\n>>>\\n\\nAssigning a new value to instances of the pointer types c_char_p, c_wchar_p, and 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):\\n\\n>>> s = \"Hello, World\"\\n>>> c_s = c_wchar_p(s)\\n>>> print(c_s)\\nc_wchar_p(139966785747344)\\n>>> print(c_s.value)\\nHello World\\n>>> c_s.value = \"Hi, there\"\\n>>> print(c_s) # the memory location has changed\\nc_wchar_p(139966783348904)\\n>>> print(c_s.value)\\nHi, there\\n>>> print(s) # first object is unchanged\\nHello, World\\n>>>\\n\\nYou should be careful, however, not to pass them to functions expecting pointers to mutable memory. If you need mutable memory blocks, ctypes has a create_string_buffer() function which creates these in various ways. The current memory block contents can be accessed (or changed) with the raw property; if you want to access it as NUL terminated string, use the value property:\\n\\n>>> from ctypes import *\\n>>> p = create_string_buffer(3) # create a 3 byte buffer, initialized to NUL bytes\\n>>> print(sizeof(p), repr(p.raw))\\n3 b\\'\\\\x00\\\\x00\\\\x00\\'\\n>>> p = create_string_buffer(b\"Hello\") # create a buffer containing a NUL terminated string\\n>>> print(sizeof(p), repr(p.raw))\\n6 b\\'Hello\\\\x00\\'\\n>>> print(repr(p.value))\\nb\\'Hello\\'\\n>>> p = create_string_buffer(b\"Hello\", 10) # create a 10 byte buffer\\n>>> print(sizeof(p), repr(p.raw))\\n10 b\\'Hello\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\'\\n>>> p.value = b\"Hi\"\\n>>> print(sizeof(p), repr(p.raw))\\n10 b\\'Hi\\\\x00lo\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\'\\n>>>\\n\\nThe create_string_buffer() function replaces the old c_buffer() function (which is still available as an alias). To create a mutable memory block containing unicode characters of the C type wchar_t, use the create_unicode_buffer() function.\\n\\nCalling functions, continued¶\\n\\nNote that printf prints to the real standard output channel, not to sys.stdout, so these examples will only work at the console prompt, not from within IDLE or PythonWin:\\n\\n>>> printf = libc.printf\\n>>> printf(b\"Hello, %s\\\\n\", b\"World!\")\\nHello, World!\\n14\\n>>> printf(b\"Hello, %S\\\\n\", \"World!\")\\nHello, World!\\n14\\n>>> printf(b\"%d bottles of beer\\\\n\", 42)\\n42 bottles of beer\\n19\\n>>> printf(b\"%f bottles of beer\\\\n\", 42.5)\\nTraceback (most recent call last):\\n File \"\", line 1, in \\nctypes.ArgumentError: argument 2: TypeError: Don\\'t know how to convert parameter 2\\n>>>\\n\\nAs has been mentioned before, all Python types except integers, strings, and bytes objects have to be wrapped in their corresponding ctypes type, so that they can be converted to the required C data type:\\n\\n>>> printf(b\"An int %d, a double %f\\\\n\", 1234, c_double(3.14))\\nAn int 1234, a double 3.140000\\n31\\n>>>\\n\\nCalling variadic functions¶\\n\\nOn 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.\\n\\nOn those platforms it is required to specify the argtypes attribute for the regular, non-variadic, function arguments:\\n\\nlibc.printf.argtypes = [ctypes.c_char_p]\\n\\nBecause specifying the attribute does not inhibit portability it is advised to always specify argtypes for all variadic functions.\\n\\nCalling functions with your own custom data types¶\\n\\nYou can also customize ctypes argument conversion to allow instances of your own classes be used as function arguments. ctypes looks for an _as_parameter_ attribute and uses this as the function argument. The attribute must be an integer, string, bytes, a ctypes instance, or an object with an _as_parameter_ attribute:\\n\\n>>> class Bottles:\\n... def __init__(self, number):\\n... self._as_parameter_ = number\\n...\\n>>> bottles = Bottles(42)\\n>>> printf(b\"%d bottles of beer\\\\n\", bottles)\\n42 bottles of beer\\n19\\n>>>\\n\\nIf you don’t want to store the instance’s data in the _as_parameter_ instance variable, you could define a property which makes the attribute available on request.\\n\\nSpecifying the required argument types (function prototypes)¶\\n\\nIt is possible to specify the required argument types of functions exported from DLLs by setting the argtypes attribute.\\n\\nargtypes must be a sequence of C data types (the 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):\\n\\n>>> printf.argtypes = [c_char_p, c_char_p, c_int, c_double]\\n>>> printf(b\"String \\'%s\\', Int %d, Double %f\\\\n\", b\"Hi\", 10, 2.2)\\nString \\'Hi\\', Int 10, Double 2.200000\\n37\\n>>>\\n\\nSpecifying a format protects against incompatible argument types (just as a prototype for a C function), and tries to convert the arguments to valid types:\\n\\n>>> printf(b\"%d %d %d\", 1, 2, 3)\\nTraceback (most recent call last):\\n File \"\", line 1, in \\nctypes.ArgumentError: argument 2: TypeError: \\'int\\' object cannot be interpreted as ctypes.c_char_p\\n>>> printf(b\"%s %d %f\\\\n\", b\"X\", 2, 3)\\nX 2 3.000000\\n13\\n>>>\\n\\nIf you have defined your own classes which you pass to function calls, you have to implement a from_param() class method for them to be able to use them in the argtypes sequence. The 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 _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 ctypes instance, or an object with an _as_parameter_ attribute.\\n\\nReturn types¶\\n\\nBy default functions are assumed to return the C int type. Other return types can be specified by setting the restype attribute of the function object.\\n\\nThe C prototype of time() is time_t time(time_t *). Because time_t might be of a different type than the default return type int, you should specify the restype attribute:\\n\\n>>> libc.time.restype = c_time_t\\n\\nThe argument types can be specified using argtypes:\\n\\n>>> libc.time.argtypes = (POINTER(c_time_t),)\\n\\nTo call the function with a NULL pointer as first argument, use None:\\n\\n>>> print(libc.time(None))\\n1150640792\\n\\nHere is a more advanced example, it uses the strchr() function, which expects a string pointer and a char, and returns a pointer to a string:\\n\\n>>> strchr = libc.strchr\\n>>> strchr(b\"abcdef\", ord(\"d\"))\\n8059983\\n>>> strchr.restype = c_char_p # c_char_p is a pointer to a string\\n>>> strchr(b\"abcdef\", ord(\"d\"))\\nb\\'def\\'\\n>>> print(strchr(b\"abcdef\", ord(\"x\")))\\nNone\\n>>>\\n\\nIf you want to avoid the ord(\"x\") calls above, you can set the argtypes attribute, and the second argument will be converted from a single character Python bytes object into a C char:\\n\\n>>> strchr.restype = c_char_p\\n>>> strchr.argtypes = [c_char_p, c_char]\\n>>> strchr(b\"abcdef\", b\"d\")\\nb\\'def\\'\\n>>> strchr(b\"abcdef\", b\"def\")\\nTraceback (most recent call last):\\nctypes.ArgumentError: argument 2: TypeError: one character bytes, bytearray or integer expected\\n>>> print(strchr(b\"abcdef\", b\"x\"))\\nNone\\n>>> strchr(b\"abcdef\", b\"d\")\\nb\\'def\\'\\n>>>\\n\\nYou can also use a callable Python object (a function or a class for example) as the 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:\\n\\n>>> GetModuleHandle = windll.kernel32.GetModuleHandleA\\n>>> def ValidHandle(value):\\n... if value == 0:\\n... raise WinError()\\n... return value\\n...\\n>>>\\n>>> GetModuleHandle.restype = ValidHandle\\n>>> GetModuleHandle(None)\\n486539264\\n>>> GetModuleHandle(\"something silly\")\\nTraceback (most recent call last):\\n File \"\", line 1, in \\n File \"\", line 3, in ValidHandle\\nOSError: [Errno 126] The specified module could not be found.\\n>>>\\n\\nWinError is a function which will call Windows FormatMessage() api to get the string representation of an error code, and returns an exception. WinError takes an optional error code parameter, if no one is used, it calls GetLastError() to retrieve it.\\n\\nPlease note that a much more powerful error checking mechanism is available through the errcheck attribute; see the reference manual for details.\\n\\nPassing pointers (or: passing parameters by reference)¶\\n\\nSometimes a C api function expects a pointer to a data type as parameter, probably to write into the corresponding location, or if the data is too large to be passed by value. This is also known as passing parameters by reference.\\n\\nctypes exports the byref() function which is used to pass parameters by reference. The same effect can be achieved with the pointer() function, although pointer() does a lot more work since it constructs a real pointer object, so it is faster to use byref() if you don’t need the pointer object in Python itself:\\n\\n>>> i = c_int()\\n>>> f = c_float()\\n>>> s = create_string_buffer(b\\'\\\\000\\' * 32)\\n>>> print(i.value, f.value, repr(s.value))\\n0 0.0 b\\'\\'\\n>>> libc.sscanf(b\"1 3.14 Hello\", b\"%d %f %s\",\\n... byref(i), byref(f), s)\\n3\\n>>> print(i.value, f.value, repr(s.value))\\n1 3.1400001049 b\\'Hello\\'\\n>>>\\n\\nStructures and unions¶\\n\\nStructures and unions must derive from the Structure and Union base classes which are defined in the ctypes module. Each subclass must define a _fields_ attribute. _fields_ must be a list of 2-tuples, containing a field name and a field type.\\n\\nThe field type must be a ctypes type like c_int, or any other derived ctypes type: structure, union, array, pointer.\\n\\nHere is a simple example of a POINT structure, which contains two integers named x and y, and also shows how to initialize a structure in the constructor:\\n\\n>>> from ctypes import *\\n>>> class POINT(Structure):\\n... _fields_ = [(\"x\", c_int),\\n... (\"y\", c_int)]\\n...\\n>>> point = POINT(10, 20)\\n>>> print(point.x, point.y)\\n10 20\\n>>> point = POINT(y=5)\\n>>> print(point.x, point.y)\\n0 5\\n>>> POINT(1, 2, 3)\\nTraceback (most recent call last):\\n File \"\", line 1, in \\nTypeError: too many initializers\\n>>>\\n\\nYou can, however, build much more complicated structures. A structure can itself contain other structures by using a structure as a field type.\\n\\nHere is a RECT structure which contains two POINTs named upperleft and lowerright:\\n\\n>>> class RECT(Structure):\\n... _fields_ = [(\"upperleft\", POINT),\\n... (\"lowerright\", POINT)]\\n...\\n>>> rc = RECT(point)\\n>>> print(rc.upperleft.x, rc.upperleft.y)\\n0 5\\n>>> print(rc.lowerright.x, rc.lowerright.y)\\n0 0\\n>>>\\n\\nNested structures can also be initialized in the constructor in several ways:\\n\\n>>> r = RECT(POINT(1, 2), POINT(3, 4))\\n>>> r = RECT((1, 2), (3, 4))\\n\\nField descriptors can be retrieved from the class, they are useful for debugging because they can provide useful information. See CField:\\n\\n>>> POINT.x\\n\\n>>> POINT.y\\n\\n>>>\\n\\nWarning\\n\\nctypes 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.\\n\\nStructure/union layout, alignment and byte order¶\\n\\nBy 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 _layout_ class attribute in the subclass definition; see the attribute documentation for details.\\n\\nIt is possible to specify the maximum alignment for the fields and/or for the structure itself by setting the class attributes _pack_ and/or _align_, respectively. See the attribute documentation for details.\\n\\nctypes uses the native byte order for Structures and Unions. To build structures with non-native byte order, you can use one of the BigEndianStructure, LittleEndianStructure, BigEndianUnion, and LittleEndianUnion base classes. These classes cannot contain pointer fields.\\n\\nBit fields in structures and unions¶\\n\\nIt 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 _fields_ tuples:\\n\\n>>> class Int(Structure):\\n... _fields_ = [(\"first_16\", c_int, 16),\\n... (\"second_16\", c_int, 16)]\\n...\\n>>> print(Int.first_16)\\n\\n>>> print(Int.second_16)\\n\\n\\nIt 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 _layout_ attribute for details on the default behavior and how to change it.\\n\\nArrays¶\\n\\nArrays are sequences, containing a fixed number of instances of the same type.\\n\\nThe recommended way to create array types is by multiplying a data type with a positive integer:\\n\\nTenPointsArrayType = POINT * 10\\n\\nHere is an example of a somewhat artificial data type, a structure containing 4 POINTs among other stuff:\\n\\n>>> from ctypes import *\\n>>> class POINT(Structure):\\n... _fields_ = (\"x\", c_int), (\"y\", c_int)\\n...\\n>>> class MyStruct(Structure):\\n... _fields_ = [(\"a\", c_int),\\n... (\"b\", c_float),\\n... (\"point_array\", POINT * 4)]\\n>>>\\n>>> print(len(MyStruct().point_array))\\n4\\n>>>\\n\\nInstances are created in the usual way, by calling the class:\\n\\narr = TenPointsArrayType()\\nfor pt in arr:\\n print(pt.x, pt.y)\\n\\nThe above code print a series of 0 0 lines, because the array contents is initialized to zeros.\\n\\nInitializers of the correct type can also be specified:\\n\\n>>> from ctypes import *\\n>>> TenIntegers = c_int * 10\\n>>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\\n>>> print(ii)\\n\\n>>> for i in ii: print(i, end=\" \")\\n...\\n1 2 3 4 5 6 7 8 9 10\\n>>>\\n\\nPointers¶\\n\\nPointer instances are created by calling the pointer() function on a ctypes type:\\n\\n>>> from ctypes import *\\n>>> i = c_int(42)\\n>>> pi = pointer(i)\\n>>>\\n\\nPointer instances have a contents attribute which returns the object to which the pointer points, the i object above:\\n\\n>>> pi.contents\\nc_long(42)\\n>>>\\n\\nNote that ctypes does not have OOR (original object return), it constructs a new, equivalent object each time you retrieve an attribute:\\n\\n>>> pi.contents is i\\nFalse\\n>>> pi.contents is pi.contents\\nFalse\\n>>>\\n\\nAssigning another c_int instance to the pointer’s contents attribute would cause the pointer to point to the memory location where this is stored:\\n\\n>>> i = c_int(99)\\n>>> pi.contents = i\\n>>> pi.contents\\nc_long(99)\\n>>>\\n\\nPointer instances can also be indexed with integers:\\n\\n>>> pi[0]\\n99\\n>>>\\n\\nAssigning to an integer index changes the pointed to value:\\n\\n>>> print(i)\\nc_long(99)\\n>>> pi[0] = 22\\n>>> print(i)\\nc_long(22)\\n>>>\\n\\nIt is also possible to use indexes different from 0, but you must know what you’re doing, just as in C: You can access or change arbitrary memory locations. Generally you only use this feature if you receive a pointer from a C function, and you know that the pointer actually points to an array instead of a single item.\\n\\nBehind the scenes, the pointer() function does more than simply create pointer instances, it has to create pointer types first. This is done with the POINTER() function, which accepts any ctypes type, and returns a new type:\\n\\n>>> PI = POINTER(c_int)\\n>>> PI\\n\\n>>> PI(42)\\nTraceback (most recent call last):\\n File \"\", line 1, in \\nTypeError: expected c_long instead of int\\n>>> PI(c_int(42))\\n\\n>>>\\n\\nCalling the pointer type without an argument creates a NULL pointer. NULL pointers have a False boolean value:\\n\\n>>> null_ptr = POINTER(c_int)()\\n>>> print(bool(null_ptr))\\nFalse\\n>>>\\n\\nctypes checks for NULL when dereferencing pointers (but dereferencing invalid non-NULL pointers would crash Python):\\n\\n>>> null_ptr[0]\\nTraceback (most recent call last):\\n ....\\nValueError: NULL pointer access\\n>>>\\n\\n>>> null_ptr[0] = 1234\\nTraceback (most recent call last):\\n ....\\nValueError: NULL pointer access\\n>>>\\n\\nThread safety without the GIL¶\\n\\nFrom Python 3.13 onward, the GIL can be disabled on the free-threaded build. In ctypes, reads and writes to a single object concurrently is safe, but not across multiple objects:\\n\\n>>> number = c_int(42)\\n>>> pointer_a = pointer(number)\\n>>> pointer_b = pointer(number)\\n\\nIn the above, it’s only safe for one object to read and write to the address at once if the GIL is disabled. So, pointer_a can be shared and written to across multiple threads, but only if pointer_b is not also attempting to do the same. If this is an issue, consider using a threading.Lock to synchronize access to memory:\\n\\n>>> import threading\\n>>> lock = threading.Lock()\\n>>> # Thread 1\\n>>> with lock:\\n... pointer_a.contents = 24\\n>>> # Thread 2\\n>>> with lock:\\n... pointer_b.contents = 42\\n\\nType conversions¶\\n\\nUsually, ctypes does strict type checking. This means, if you have POINTER(c_int) in the 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 POINTER(c_int), ctypes accepts an array of c_int:\\n\\n>>> class Bar(Structure):\\n... _fields_ = [(\"count\", c_int), (\"values\", POINTER(c_int))]\\n...\\n>>> bar = Bar()\\n>>> bar.values = (c_int * 3)(1, 2, 3)\\n>>> bar.count = 3\\n>>> for i in range(bar.count):\\n... print(bar.values[i])\\n...\\n1\\n2\\n3\\n>>>\\n\\nIn addition, if a function argument is explicitly declared to be a pointer type (such as POINTER(c_int)) in argtypes, an object of the pointed type (c_int in this case) can be passed to the function. ctypes will apply the required byref() conversion in this case automatically.\\n\\nTo set a POINTER type field to NULL, you can assign None:\\n\\n>>> bar.values = None\\n>>>\\n\\nSometimes you have instances of incompatible types. In C, you can cast one type into another type. ctypes provides a cast() function which can be used in the same way. The Bar structure defined above accepts POINTER(c_int) pointers or c_int arrays for its values field, but not instances of other types:\\n\\n>>> bar.values = (c_byte * 4)()\\nTraceback (most recent call last):\\n File \"\", line 1, in \\nTypeError: incompatible types, c_byte_Array_4 instance instead of LP_c_long instance\\n>>>\\n\\nFor these cases, the cast() function is handy.\\n\\nThe cast() function can be used to cast a ctypes instance into a pointer to a different ctypes data type. cast() takes two parameters, a ctypes object that is or can be converted to a pointer of some kind, and a ctypes pointer type. It returns an instance of the second argument, which references the same memory block as the first argument:\\n\\n>>> a = (c_byte * 4)()\\n>>> cast(a, POINTER(c_int))\\n\\n>>>\\n\\nSo, cast() can be used to assign to the values field of Bar the structure:\\n\\n>>> bar = Bar()\\n>>> bar.values = cast((c_byte * 4)(), POINTER(c_int))\\n>>> print(bar.values[0])\\n0\\n>>>\\n\\nIncomplete Types¶\\n\\nIncomplete Types are structures, unions or arrays whose members are not yet specified. In C, they are specified by forward declarations, which are defined later:\\n\\nstruct cell; /* forward declaration */\\n\\nstruct cell {\\n char *name;\\n struct cell *next;\\n};\\n\\nThe straightforward translation into ctypes code would be this, but it does not work:\\n\\n>>> class cell(Structure):\\n... _fields_ = [(\"name\", c_char_p),\\n... (\"next\", POINTER(cell))]\\n...\\nTraceback (most recent call last):\\n File \"\", line 1, in \\n File \"\", line 2, in cell\\nNameError: name \\'cell\\' is not defined\\n>>>\\n\\nbecause the new class cell is not available in the class statement itself. In ctypes, we can define the cell class and set the _fields_ attribute later, after the class statement:\\n\\n>>> from ctypes import *\\n>>> class cell(Structure):\\n... pass\\n...\\n>>> cell._fields_ = [(\"name\", c_char_p),\\n... (\"next\", POINTER(cell))]\\n>>>\\n\\nLet’s try it. We create two instances of cell, and let them point to each other, and finally follow the pointer chain a few times:\\n\\n>>> c1 = cell()\\n>>> c1.name = b\"foo\"\\n>>> c2 = cell()\\n>>> c2.name = b\"bar\"\\n>>> c1.next = pointer(c2)\\n>>> c2.next = pointer(c1)\\n>>> p = c1\\n>>> for i in range(8):\\n... print(p.name, end=\" \")\\n... p = p.next[0]\\n...\\nfoo bar foo bar foo bar foo bar\\n>>>\\n\\nCallback functions¶\\n\\nctypes allows creating C callable function pointers from Python callables. These are sometimes called callback functions.\\n\\nFirst, you must create a class for the callback function. The class knows the calling convention, the return type, and the number and types of arguments this function will receive.\\n\\nThe CFUNCTYPE() factory function creates types for callback functions using the cdecl calling convention. On Windows, the WINFUNCTYPE() factory function creates types for callback functions using the stdcall calling convention.\\n\\nBoth of these factory functions are called with the result type as first argument, and the callback functions expected argument types as the remaining arguments.\\n\\nI will present an example here which uses the standard C library’s qsort() function, that is used to sort items with the help of a callback function. qsort() will be used to sort an array of integers:\\n\\n>>> IntArray5 = c_int * 5\\n>>> ia = IntArray5(5, 1, 7, 33, 99)\\n>>> qsort = libc.qsort\\n>>> qsort.restype = None\\n>>>\\n\\nqsort() 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.\\n\\nSo our callback function receives pointers to integers, and must return an integer. First we create the type for the callback function:\\n\\n>>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))\\n>>>\\n\\nTo get started, here is a simple callback that shows the values it gets passed:\\n\\n>>> def py_cmp_func(a, b):\\n... print(\"py_cmp_func\", a[0], b[0])\\n... return 0\\n...\\n>>> cmp_func = CMPFUNC(py_cmp_func)\\n>>>\\n\\nThe result:\\n\\n>>> qsort(ia, len(ia), sizeof(c_int), cmp_func)\\npy_cmp_func 5 1\\npy_cmp_func 33 99\\npy_cmp_func 7 33\\npy_cmp_func 5 7\\npy_cmp_func 1 7\\n>>>\\n\\nNow we can actually compare the two items and return a useful result:\\n\\n>>> def py_cmp_func(a, b):\\n... print(\"py_cmp_func\", a[0], b[0])\\n... return a[0] - b[0]\\n...\\n>>>\\n>>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func))\\npy_cmp_func 5 1\\npy_cmp_func 33 99\\npy_cmp_func 7 33\\npy_cmp_func 1 7\\npy_cmp_func 5 7\\n>>>\\n\\nAs we can easily check, our array is sorted now:\\n\\n>>> for i in ia: print(i, end=\" \")\\n...\\n1 5 7 33 99\\n>>>\\n\\nThe function factories can be used as decorator factories, so we may as well write:\\n\\n>>> @CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))\\n... def py_cmp_func(a, b):\\n... print(\"py_cmp_func\", a[0], b[0])\\n... return a[0] - b[0]\\n...\\n>>> qsort(ia, len(ia), sizeof(c_int), py_cmp_func)\\npy_cmp_func 5 1\\npy_cmp_func 33 99\\npy_cmp_func 7 33\\npy_cmp_func 1 7\\npy_cmp_func 5 7\\n>>>\\n\\nNote\\n\\nMake sure you keep references to CFUNCTYPE() objects as long as they are used from C code. ctypes doesn’t, and if you don’t, they may be garbage collected, crashing your program when a callback is made.\\n\\nAlso, note that if the callback function is called in a thread created outside of Python’s control (e.g. by the foreign code that calls the callback), ctypes creates a new dummy Python thread on every invocation. This behavior is correct for most purposes, but it means that values stored with threading.local will not survive across different callbacks, even when those calls are made from the same C thread.\\n\\nAccessing values exported from dlls¶\\n\\nSome shared libraries not only export functions, they also export variables. An example in the Python library itself is the Py_Version, Python runtime version number encoded in a single constant integer.\\n\\nctypes can access values like this with the in_dll() class methods of the type. pythonapi is a predefined symbol giving access to the Python C api:\\n\\n>>> version = ctypes.c_int.in_dll(ctypes.pythonapi, \"Py_Version\")\\n>>> print(hex(version.value))\\n0x30c00a0\\n\\nAn extended example which also demonstrates the use of pointers accesses the PyImport_FrozenModules pointer exported by Python.\\n\\nQuoting the docs for that value:\\n\\nThis pointer is initialized to point to an array of _frozen records, terminated by one whose members are all NULL or zero. When a frozen module is imported, it is searched in this table. Third-party code could play tricks with this to provide a dynamically created collection of frozen modules.\\n\\nSo manipulating this pointer could even prove useful. To restrict the example size, we show only how this table can be read with ctypes:\\n\\n>>> from ctypes import *\\n>>>\\n>>> class struct_frozen(Structure):\\n... _fields_ = [(\"name\", c_char_p),\\n... (\"code\", POINTER(c_ubyte)),\\n... (\"size\", c_int),\\n... (\"get_code\", POINTER(c_ubyte)), # Function pointer\\n... ]\\n...\\n>>>\\n\\nWe have defined the _frozen data type, so we can get the pointer to the table:\\n\\n>>> FrozenTable = POINTER(struct_frozen)\\n>>> table = FrozenTable.in_dll(pythonapi, \"_PyImport_FrozenBootstrap\")\\n>>>\\n\\nSince table is a pointer to the array of struct_frozen records, we can iterate over it, but we just have to make sure that our loop terminates, because pointers have no size. Sooner or later it would probably crash with an access violation or whatever, so it’s better to break out of the loop when we hit the NULL entry:\\n\\n>>> for item in table:\\n... if item.name is None:\\n... break\\n... print(item.name.decode(\"ascii\"), item.size)\\n...\\n_frozen_importlib 31764\\n_frozen_importlib_external 41499\\nzipimport 12345\\n>>>\\n\\nThe fact that standard Python has a frozen module and a frozen package (indicated by the negative size member) is not well known, it is only used for testing. Try it out with import __hello__ for example.\\n\\nSurprises¶\\n\\nThere are some edges in ctypes where you might expect something other than what actually happens.\\n\\nConsider the following example:\\n\\n>>> from ctypes import *\\n>>> class POINT(Structure):\\n... _fields_ = (\"x\", c_int), (\"y\", c_int)\\n...\\n>>> class RECT(Structure):\\n... _fields_ = (\"a\", POINT), (\"b\", POINT)\\n...\\n>>> p1 = POINT(1, 2)\\n>>> p2 = POINT(3, 4)\\n>>> rc = RECT(p1, p2)\\n>>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)\\n1 2 3 4\\n>>> # now swap the two points\\n>>> rc.a, rc.b = rc.b, rc.a\\n>>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)\\n3 4 3 4\\n>>>\\n\\nHm. We certainly expected the last statement to print 3 4 1 2. What happened? Here are the steps of the rc.a, rc.b = rc.b, rc.a line above:\\n\\n>>> temp0, temp1 = rc.b, rc.a\\n>>> rc.a = temp0\\n>>> rc.b = temp1\\n>>>\\n\\nNote that temp0 and temp1 are objects still using the internal buffer of the rc object above. So executing rc.a = temp0 copies the buffer contents of temp0 into rc ‘s buffer. This, in turn, changes the contents of temp1. So, the last assignment rc.b = temp1, doesn’t have the expected effect.\\n\\nKeep in mind that retrieving sub-objects from Structure, Unions, and Arrays doesn’t copy the sub-object, instead it retrieves a wrapper object accessing the root-object’s underlying buffer.\\n\\nAnother example that may behave differently from what one would expect is this:\\n\\n>>> s = c_char_p()\\n>>> s.value = b\"abc def ghi\"\\n>>> s.value\\nb\\'abc def ghi\\'\\n>>> s.value is s.value\\nFalse\\n>>>\\n\\nNote\\n\\nObjects instantiated from c_char_p can only have their value set to bytes or integers.\\n\\nWhy is it printing False? ctypes instances are objects containing a memory block plus some descriptors accessing the contents of the memory. Storing a Python object in the memory block does not store the object itself, instead the contents of the object is stored. Accessing the contents again constructs a new Python object each time!\\n\\nVariable-sized data types¶\\n\\nctypes provides some support for variable-sized arrays and structures.\\n\\nThe resize() function can be used to resize the memory buffer of an existing ctypes object. The function takes the object as first argument, and the requested size in bytes as the second argument. The memory block cannot be made smaller than the natural memory block specified by the objects type, a ValueError is raised if this is tried:\\n\\n>>> short_array = (c_short * 4)()\\n>>> print(sizeof(short_array))\\n8\\n>>> resize(short_array, 4)\\nTraceback (most recent call last):\\n ...\\nValueError: minimum size is 8\\n>>> resize(short_array, 32)\\n>>> sizeof(short_array)\\n32\\n>>> sizeof(type(short_array))\\n8\\n>>>\\n\\nThis is nice and fine, but how would one access the additional elements contained in this array? Since the type still only knows about 4 elements, we get errors accessing other elements:\\n\\n>>> short_array[:]\\n[0, 0, 0, 0]\\n>>> short_array[7]\\nTraceback (most recent call last):\\n ...\\nIndexError: invalid index\\n>>>\\n\\nAnother way to use variable-sized data types with 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.\\n\\nctypes reference¶\\n\\nFinding shared libraries¶\\n\\nWhen programming in a compiled language, shared libraries are accessed when compiling/linking a program, and when the program is run.\\n\\nThe purpose of the find_library() function is to locate a library in a way similar to what the compiler or runtime loader does (on platforms with several versions of a shared library the most recent should be loaded), while the ctypes library loaders act like when a program is run, and call the runtime loader directly.\\n\\nThe ctypes.util module provides a function which can help to determine the library to load.\\n\\nThe exact functionality is system dependent.\\n\\nOn Linux, find_library() tries to run external programs (/sbin/ldconfig, gcc, objdump and ld) to find the library file. It returns the filename of the library file.\\n\\nNote 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.\\n\\nChanged in version 3.6: On Linux, the value of the environment variable LD_LIBRARY_PATH is used when searching for libraries, if a library cannot be found by any other means.\\n\\nHere are some examples:\\n\\n>>> from ctypes.util import find_library\\n>>> find_library(\"m\")\\n\\'libm.so.6\\'\\n>>> find_library(\"c\")\\n\\'libc.so.6\\'\\n>>> find_library(\"bz2\")\\n\\'libbz2.so.1.0\\'\\n>>>\\n\\nOn macOS and Android, find_library() uses the system’s standard naming schemes and paths to locate the library, and returns a full pathname if successful:\\n\\n>>> from ctypes.util import find_library\\n>>> find_library(\"c\")\\n\\'/usr/lib/libc.dylib\\'\\n>>> find_library(\"m\")\\n\\'/usr/lib/libm.dylib\\'\\n>>> find_library(\"bz2\")\\n\\'/usr/lib/libbz2.dylib\\'\\n>>> find_library(\"AGL\")\\n\\'/System/Library/Frameworks/AGL.framework/AGL\\'\\n>>>\\n\\nOn Windows, find_library() searches along the system search path, and returns the full pathname, but since there is no predefined naming scheme a call like find_library(\"c\") will fail and return None.\\n\\nIf wrapping a shared library with ctypes, it may be better to determine the shared library name at development time, and hardcode that into the wrapper module instead of using find_library() to locate the library at runtime.\\n\\nListing loaded shared libraries¶\\n\\nWhen 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.\\n\\nThe ctypes.util module provides the 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.\\n\\nThe 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:\\n\\n>>> from ctypes.util import dllist\\n>>> dllist()\\n[\\'\\', \\'linux-vdso.so.1\\', \\'/lib/x86_64-linux-gnu/libm.so.6\\', \\'/lib/x86_64-linux-gnu/libc.so.6\\', ... ]\\n\\nLoading shared libraries¶\\n\\nThere are several ways to load shared libraries into the Python process. One way is to instantiate CDLL or one of its subclasses:\\n\\nShared libraries can also be loaded by using one of the prefabricated objects, which are instances of the LibraryLoader class, either by calling the LoadLibrary() method, or by retrieving the library as attribute of the loader instance.\\n\\nThese prefabricated library loaders are available:\\n\\nFor accessing the C Python api directly, a ready-to-use Python shared library object is available:\\n\\nLoading a library through any of these objects raises an auditing event ctypes.dlopen with string argument name, the name used to load the library.\\n\\nAccessing a function on a loaded library raises an auditing event ctypes.dlsym with arguments library (the library object) and name (the symbol’s name as a string or integer).\\n\\nIn cases when only the library handle is available rather than the object, accessing a function raises an auditing event ctypes.dlsym/handle with arguments handle (the raw library handle) and name.\\n\\nForeign functions¶\\n\\nAs 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.\\n\\nThey are instances of a private local class _FuncPtr (not exposed in ctypes) which inherits from the private _CFuncPtr class:\\n\\n>>> import ctypes\\n>>> lib = ctypes.CDLL(None)\\n>>> issubclass(lib._FuncPtr, ctypes._CFuncPtr)\\nTrue\\n>>> lib._FuncPtr is ctypes._CFuncPtr\\nFalse\\n\\nOn 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 ctypes.set_exception with argument code will be raised, allowing an audit hook to replace the exception with its own.\\n\\nSome ways to invoke foreign function calls as well as some of the functions in this module may raise an auditing event ctypes.call_function with arguments function pointer and arguments.\\n\\nFunction prototypes¶\\n\\nForeign functions can also be created by instantiating function prototypes. Function prototypes are similar to function prototypes in C; they describe a function (return type, argument types, calling convention) without defining an implementation. The factory functions must be called with the desired result type and the argument types of the function, and can be used as decorator factories, and as such, be applied to functions through the @wrapper syntax. See Callback functions for examples.\\n\\nFunction prototypes created by these factory functions can be instantiated in different ways, depending on the type and number of the parameters in the call:\\n\\nThe optional paramflags parameter creates foreign function wrappers with much more functionality than the features described above.\\n\\nparamflags must be a tuple of the same length as argtypes.\\n\\nEach item in this tuple contains further information about a parameter, it must be a tuple containing one, two, or three items.\\n\\nThe first item is an integer containing a combination of direction flags for the parameter:\\n\\nThe optional second item is the parameter name as string. If this is specified, the foreign function can be called with named parameters.\\n\\nThe optional third item is the default value for this parameter.\\n\\nThe following example demonstrates how to wrap the Windows MessageBoxW function so that it supports default parameters and named arguments. The C declaration from the windows header file is this:\\n\\nWINUSERAPI int WINAPI\\nMessageBoxW(\\n HWND hWnd,\\n LPCWSTR lpText,\\n LPCWSTR lpCaption,\\n UINT uType);\\n\\nHere is the wrapping with ctypes:\\n\\n>>> from ctypes import c_int, WINFUNCTYPE, windll\\n>>> from ctypes.wintypes import HWND, LPCWSTR, UINT\\n>>> prototype = WINFUNCTYPE(c_int, HWND, LPCWSTR, LPCWSTR, UINT)\\n>>> paramflags = (1, \"hwnd\", 0), (1, \"text\", \"Hi\"), (1, \"caption\", \"Hello from ctypes\"), (1, \"flags\", 0)\\n>>> MessageBox = prototype((\"MessageBoxW\", windll.user32), paramflags)\\n\\nThe MessageBox foreign function can now be called in these ways:\\n\\n>>> MessageBox()\\n>>> MessageBox(text=\"Spam, spam, spam\")\\n>>> MessageBox(flags=2, text=\"foo bar\")\\n\\nA second example demonstrates output parameters. The win32 GetWindowRect function retrieves the dimensions of a specified window by copying them into RECT structure that the caller has to supply. Here is the C declaration:\\n\\nWINUSERAPI BOOL WINAPI\\nGetWindowRect(\\n HWND hWnd,\\n LPRECT lpRect);\\n\\nHere is the wrapping with ctypes:\\n\\n>>> from ctypes import POINTER, WINFUNCTYPE, windll, WinError\\n>>> from ctypes.wintypes import BOOL, HWND, RECT\\n>>> prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))\\n>>> paramflags = (1, \"hwnd\"), (2, \"lprect\")\\n>>> GetWindowRect = prototype((\"GetWindowRect\", windll.user32), paramflags)\\n>>>\\n\\nFunctions with output parameters will automatically return the output parameter value if there is a single one, or a tuple containing the output parameter values when there are more than one, so the GetWindowRect function now returns a RECT instance, when called.\\n\\nOutput parameters can be combined with the errcheck protocol to do further output processing and error checking. The win32 GetWindowRect api function returns a BOOL to signal success or failure, so this function could do the error checking, and raises an exception when the api call failed:\\n\\n>>> def errcheck(result, func, args):\\n... if not result:\\n... raise WinError()\\n... return args\\n...\\n>>> GetWindowRect.errcheck = errcheck\\n>>>\\n\\nIf the errcheck function returns the argument tuple it receives unchanged, ctypes continues the normal processing it does on the output parameters. If you want to return a tuple of window coordinates instead of a RECT instance, you can retrieve the fields in the function and return them instead, the normal processing will no longer take place:\\n\\n>>> def errcheck(result, func, args):\\n... if not result:\\n... raise WinError()\\n... rc = args[1]\\n... return rc.left, rc.top, rc.bottom, rc.right\\n...\\n>>> GetWindowRect.errcheck = errcheck\\n>>>\\n\\nUtility functions¶\\n\\nData types¶\\n\\nFundamental data types¶\\n\\nFundamental 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 restype of c_char_p, you will always receive a Python bytes object, not a c_char_p instance.\\n\\nSubclasses of fundamental data types do not inherit this behavior. So, if a foreign functions restype is a subclass of 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 value attribute.\\n\\nThese are the fundamental ctypes data types:\\n\\nThe ctypes.wintypes module provides quite some other Windows specific data types, for example HWND, WPARAM, or DWORD. Some useful structures like MSG or RECT are also defined.\\n\\nStructured data types¶\\n\\nStructures and unions with non-native byte order cannot contain pointer type fields, or any other data types containing pointer type fields.\\n\\nArrays and pointers¶\\n\\nExceptions¶\\n\\nTable of Contents\\n\\nctypes — A foreign function library for Python\\n\\nctypes tutorial\\n\\nLoading dynamic link libraries\\n\\nAccessing functions from loaded dlls\\n\\nCalling functions\\n\\nFundamental data types\\n\\nCalling functions, continued\\n\\nCalling variadic functions\\n\\nCalling functions with your own custom data types\\n\\nSpecifying the required argument types (function prototypes)\\n\\nReturn types\\n\\nPassing pointers (or: passing parameters by reference)\\n\\nStructures and unions\\n\\nStructure/union layout, alignment and byte order\\n\\nBit fields in structures and unions\\n\\nArrays\\n\\nPointers\\n\\nThread safety without the GIL\\n\\nType conversions\\n\\nIncomplete Types\\n\\nCallback functions\\n\\nAccessing values exported from dlls\\n\\nSurprises\\n\\nVariable-sized data types\\n\\nctypes reference\\n\\nFinding shared libraries\\n\\nListing loaded shared libraries\\n\\nLoading shared libraries\\n\\nForeign functions\\n\\nFunction prototypes\\n\\nUtility functions\\n\\nData types\\n\\nFundamental data types\\n\\nStructured data types\\n\\nArrays and pointers\\n\\nExceptions\\n\\nPrevious topic\\n\\nerrno — Standard errno system symbols\\n\\nNext topic\\n\\nCommand-line interface libraries\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nGeneric Operating System Services »\\n\\nctypes — A foreign function library for Python\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\curses.ascii.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nCommand-line interface libraries »\\n\\ncurses.ascii — Utilities for ASCII characters\\n\\n|\\n\\ncurses.ascii — Utilities for ASCII characters¶\\n\\nSource code: Lib/curses/ascii.py\\n\\nThe 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:\\n\\nName Meaning curses.ascii. NUL ¶ curses.ascii. SOH ¶ Start of heading, console interrupt curses.ascii. STX ¶ Start of text curses.ascii. ETX ¶ End of text curses.ascii. EOT ¶ End of transmission curses.ascii. ENQ ¶ Enquiry, goes with ACK flow control curses.ascii. ACK ¶ Acknowledgement curses.ascii. BEL ¶ Bell curses.ascii. BS ¶ Backspace curses.ascii. TAB ¶ Tab curses.ascii. HT ¶ Alias for TAB : “Horizontal tab” curses.ascii. LF ¶ Line feed curses.ascii. NL ¶ Alias for LF : “New line” curses.ascii. VT ¶ Vertical tab curses.ascii. FF ¶ Form feed curses.ascii. CR ¶ Carriage return curses.ascii. SO ¶ Shift-out, begin alternate character set curses.ascii. SI ¶ Shift-in, resume default character set curses.ascii. DLE ¶ Data-link escape curses.ascii. DC1 ¶ XON, for flow control curses.ascii. DC2 ¶ Device control 2, block-mode flow control curses.ascii. DC3 ¶ XOFF, for flow control curses.ascii. DC4 ¶ Device control 4 curses.ascii. NAK ¶ Negative acknowledgement curses.ascii. SYN ¶ Synchronous idle curses.ascii. ETB ¶ End transmission block curses.ascii. CAN ¶ Cancel curses.ascii. EM ¶ End of medium curses.ascii. SUB ¶ Substitute curses.ascii. ESC ¶ Escape curses.ascii. FS ¶ File separator curses.ascii. GS ¶ Group separator curses.ascii. RS ¶ Record separator, block-mode terminator curses.ascii. US ¶ Unit separator curses.ascii. SP ¶ Space curses.ascii. DEL ¶ Delete\\n\\nNote that many of these have little practical significance in modern usage. The mnemonics derive from teleprinter conventions that predate digital computers.\\n\\nThe module supplies the following functions, patterned on those in the standard C library:\\n\\nThese functions accept either integers or single-character strings; when the argument is a string, it is first converted using the built-in function ord().\\n\\nNote that all these functions check ordinal bit values derived from the character of the string you pass in; they do not actually know anything about the host machine’s character encoding.\\n\\nThe following two functions take either a single-character string or integer byte value; they return a value of the same type.\\n\\nThe following function takes either a single-character string or integer value; it returns a string.\\n\\nPrevious topic\\n\\ncurses — Terminal handling for character-cell displays\\n\\nNext topic\\n\\ncurses.panel — A panel stack extension for curses\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nCommand-line interface libraries »\\n\\ncurses.ascii — Utilities for ASCII characters\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\curses.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nCommand-line interface libraries »\\n\\ncurses — Terminal handling for character-cell displays\\n\\n|\\n\\ncurses — Terminal handling for character-cell displays¶\\n\\nSource code: Lib/curses\\n\\nThe curses module provides an interface to the curses library, the de-facto standard for portable advanced terminal handling.\\n\\nWhile curses is most widely used in the Unix environment, versions are available for Windows, DOS, and possibly other systems as well. This extension module is designed to match the API of ncurses, an open-source curses library hosted on Linux and the BSD variants of Unix.\\n\\nAvailability: not Android, not iOS, not WASI.\\n\\nThis module is not supported on mobile platforms or WebAssembly platforms.\\n\\nThis is an 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 Requirements for optional modules.\\n\\nAvailability: Unix.\\n\\nNote\\n\\nWhenever the documentation mentions a character it can be specified as an integer, a one-character Unicode string or a one-byte byte string.\\n\\nWhenever the documentation mentions a character string it can be specified as a Unicode string or a byte string.\\n\\nSee also\\n\\nFunctions¶\\n\\nThe module curses defines the following exception:\\n\\nNote\\n\\nWhenever x or y arguments to a function or a method are optional, they default to the current cursor location. Whenever attr is optional, it defaults to A_NORMAL.\\n\\nThe module curses defines the following functions:\\n\\nWindow Objects¶\\n\\nConstants¶\\n\\nThe curses module defines the following data members:\\n\\nSome constants are available to specify character cell attributes. The exact constants available are system dependent.\\n\\nAttribute Meaning curses. A_ALTCHARSET ¶ Alternate character set mode curses. A_BLINK ¶ Blink mode curses. A_BOLD ¶ Bold mode curses. A_DIM ¶ Dim mode curses. A_INVIS ¶ Invisible or blank mode curses. A_ITALIC ¶ Italic mode curses. A_NORMAL ¶ Normal attribute curses. A_PROTECT ¶ Protected mode curses. A_REVERSE ¶ Reverse background and\\nforeground colors curses. A_STANDOUT ¶ Standout mode curses. A_UNDERLINE ¶ Underline mode curses. A_HORIZONTAL ¶ Horizontal highlight curses. A_LEFT ¶ Left highlight curses. A_LOW ¶ Low highlight curses. A_RIGHT ¶ Right highlight curses. A_TOP ¶ Top highlight curses. A_VERTICAL ¶ Vertical highlight\\n\\nAdded in version 3.7: A_ITALIC was added.\\n\\nSeveral constants are available to extract corresponding attributes returned by some methods.\\n\\nBit-mask Meaning curses. A_ATTRIBUTES ¶ Bit-mask to extract\\nattributes curses. A_CHARTEXT ¶ Bit-mask to extract a\\ncharacter curses. A_COLOR ¶ Bit-mask to extract\\ncolor-pair field information\\n\\nKeys are referred to by integer constants with names starting with KEY_. The exact keycaps available are system dependent.\\n\\nKey constant Key curses. KEY_MIN ¶ Minimum key value curses. KEY_BREAK ¶ Break key (unreliable) curses. KEY_DOWN ¶ Down-arrow curses. KEY_UP ¶ Up-arrow curses. KEY_LEFT ¶ Left-arrow curses. KEY_RIGHT ¶ Right-arrow curses. KEY_HOME ¶ Home key (upward+left arrow) curses. KEY_BACKSPACE ¶ Backspace (unreliable) curses. KEY_F0 ¶ Function keys. Up to 64 function keys are\\nsupported. curses. KEY_Fn ¶ Value of function key n curses. KEY_DL ¶ Delete line curses. KEY_IL ¶ Insert line curses. KEY_DC ¶ Delete character curses. KEY_IC ¶ Insert char or enter insert mode curses. KEY_EIC ¶ Exit insert char mode curses. KEY_CLEAR ¶ Clear screen curses. KEY_EOS ¶ Clear to end of screen curses. KEY_EOL ¶ Clear to end of line curses. KEY_SF ¶ Scroll 1 line forward curses. KEY_SR ¶ Scroll 1 line backward (reverse) curses. KEY_NPAGE ¶ Next page curses. KEY_PPAGE ¶ Previous page curses. KEY_STAB ¶ Set tab curses. KEY_CTAB ¶ Clear tab curses. KEY_CATAB ¶ Clear all tabs curses. KEY_ENTER ¶ Enter or send (unreliable) curses. KEY_SRESET ¶ Soft (partial) reset (unreliable) curses. KEY_RESET ¶ Reset or hard reset (unreliable) curses. KEY_PRINT ¶ Print curses. KEY_LL ¶ Home down or bottom (lower left) curses. KEY_A1 ¶ Upper left of keypad curses. KEY_A3 ¶ Upper right of keypad curses. KEY_B2 ¶ Center of keypad curses. KEY_C1 ¶ Lower left of keypad curses. KEY_C3 ¶ Lower right of keypad curses. KEY_BTAB ¶ Back tab curses. KEY_BEG ¶ Beg (beginning) curses. KEY_CANCEL ¶ Cancel curses. KEY_CLOSE ¶ Close curses. KEY_COMMAND ¶ Cmd (command) curses. KEY_COPY ¶ Copy curses. KEY_CREATE ¶ Create curses. KEY_END ¶ End curses. KEY_EXIT ¶ Exit curses. KEY_FIND ¶ Find curses. KEY_HELP ¶ Help curses. KEY_MARK ¶ Mark curses. KEY_MESSAGE ¶ Message curses. KEY_MOVE ¶ Move curses. KEY_NEXT ¶ Next curses. KEY_OPEN ¶ Open curses. KEY_OPTIONS ¶ Options curses. KEY_PREVIOUS ¶ Prev (previous) curses. KEY_REDO ¶ Redo curses. KEY_REFERENCE ¶ Ref (reference) curses. KEY_REFRESH ¶ Refresh curses. KEY_REPLACE ¶ Replace curses. KEY_RESTART ¶ Restart curses. KEY_RESUME ¶ Resume curses. KEY_SAVE ¶ Save curses. KEY_SBEG ¶ Shifted Beg (beginning) curses. KEY_SCANCEL ¶ Shifted Cancel curses. KEY_SCOMMAND ¶ Shifted Command curses. KEY_SCOPY ¶ Shifted Copy curses. KEY_SCREATE ¶ Shifted Create curses. KEY_SDC ¶ Shifted Delete char curses. KEY_SDL ¶ Shifted Delete line curses. KEY_SELECT ¶ Select curses. KEY_SEND ¶ Shifted End curses. KEY_SEOL ¶ Shifted Clear line curses. KEY_SEXIT ¶ Shifted Exit curses. KEY_SFIND ¶ Shifted Find curses. KEY_SHELP ¶ Shifted Help curses. KEY_SHOME ¶ Shifted Home curses. KEY_SIC ¶ Shifted Input curses. KEY_SLEFT ¶ Shifted Left arrow curses. KEY_SMESSAGE ¶ Shifted Message curses. KEY_SMOVE ¶ Shifted Move curses. KEY_SNEXT ¶ Shifted Next curses. KEY_SOPTIONS ¶ Shifted Options curses. KEY_SPREVIOUS ¶ Shifted Prev curses. KEY_SPRINT ¶ Shifted Print curses. KEY_SREDO ¶ Shifted Redo curses. KEY_SREPLACE ¶ Shifted Replace curses. KEY_SRIGHT ¶ Shifted Right arrow curses. KEY_SRSUME ¶ Shifted Resume curses. KEY_SSAVE ¶ Shifted Save curses. KEY_SSUSPEND ¶ Shifted Suspend curses. KEY_SUNDO ¶ Shifted Undo curses. KEY_SUSPEND ¶ Suspend curses. KEY_UNDO ¶ Undo curses. KEY_MOUSE ¶ Mouse event has occurred curses. KEY_RESIZE ¶ Terminal resize event curses. KEY_MAX ¶ Maximum key value\\n\\nOn VT100s and their software emulations, such as X terminal emulators, there are normally at least four function keys (KEY_F1, KEY_F2, KEY_F3, KEY_F4) available, and the arrow keys mapped to KEY_UP, KEY_DOWN, KEY_LEFT and 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:\\n\\nKeycap Constant Insert KEY_IC Delete KEY_DC Home KEY_HOME End KEY_END Page Up KEY_PPAGE Page Down KEY_NPAGE\\n\\nThe following table lists characters from the alternate character set. These are inherited from the VT100 terminal, and will generally be available on software emulations such as X terminals. When there is no graphic available, curses falls back on a crude printable ASCII approximation.\\n\\nNote\\n\\nThese are available only after initscr() has been called.\\n\\nACS code Meaning curses. ACS_BBSS ¶ alternate name for upper right corner curses. ACS_BLOCK ¶ solid square block curses. ACS_BOARD ¶ board of squares curses. ACS_BSBS ¶ alternate name for horizontal line curses. ACS_BSSB ¶ alternate name for upper left corner curses. ACS_BSSS ¶ alternate name for top tee curses. ACS_BTEE ¶ bottom tee curses. ACS_BULLET ¶ bullet curses. ACS_CKBOARD ¶ checker board (stipple) curses. ACS_DARROW ¶ arrow pointing down curses. ACS_DEGREE ¶ degree symbol curses. ACS_DIAMOND ¶ diamond curses. ACS_GEQUAL ¶ greater-than-or-equal-to curses. ACS_HLINE ¶ horizontal line curses. ACS_LANTERN ¶ lantern symbol curses. ACS_LARROW ¶ left arrow curses. ACS_LEQUAL ¶ less-than-or-equal-to curses. ACS_LLCORNER ¶ lower left-hand corner curses. ACS_LRCORNER ¶ lower right-hand corner curses. ACS_LTEE ¶ left tee curses. ACS_NEQUAL ¶ not-equal sign curses. ACS_PI ¶ letter pi curses. ACS_PLMINUS ¶ plus-or-minus sign curses. ACS_PLUS ¶ big plus sign curses. ACS_RARROW ¶ right arrow curses. ACS_RTEE ¶ right tee curses. ACS_S1 ¶ scan line 1 curses. ACS_S3 ¶ scan line 3 curses. ACS_S7 ¶ scan line 7 curses. ACS_S9 ¶ scan line 9 curses. ACS_SBBS ¶ alternate name for lower right corner curses. ACS_SBSB ¶ alternate name for vertical line curses. ACS_SBSS ¶ alternate name for right tee curses. ACS_SSBB ¶ alternate name for lower left corner curses. ACS_SSBS ¶ alternate name for bottom tee curses. ACS_SSSB ¶ alternate name for left tee curses. ACS_SSSS ¶ alternate name for crossover or big plus curses. ACS_STERLING ¶ pound sterling curses. ACS_TTEE ¶ top tee curses. ACS_UARROW ¶ up arrow curses. ACS_ULCORNER ¶ upper left corner curses. ACS_URCORNER ¶ upper right corner curses. ACS_VLINE ¶ vertical line\\n\\nThe following table lists mouse button constants used by getmouse():\\n\\nMouse button constant Meaning curses. BUTTONn_PRESSED ¶ Mouse button n pressed curses. BUTTONn_RELEASED ¶ Mouse button n released curses. BUTTONn_CLICKED ¶ Mouse button n clicked curses. BUTTONn_DOUBLE_CLICKED ¶ Mouse button n double clicked curses. BUTTONn_TRIPLE_CLICKED ¶ Mouse button n triple clicked curses. BUTTON_SHIFT ¶ Shift was down during button state change curses. BUTTON_CTRL ¶ Control was down during button state change curses. BUTTON_ALT ¶ Control was down during button state change\\n\\nChanged in version 3.10: The BUTTON5_* constants are now exposed if they are provided by the underlying curses library.\\n\\nThe following table lists the predefined colors:\\n\\nConstant Color curses. COLOR_BLACK ¶ Black curses. COLOR_BLUE ¶ Blue curses. COLOR_CYAN ¶ Cyan (light greenish blue) curses. COLOR_GREEN ¶ Green curses. COLOR_MAGENTA ¶ Magenta (purplish red) curses. COLOR_RED ¶ Red curses. COLOR_WHITE ¶ White curses. COLOR_YELLOW ¶ Yellow\\n\\ncurses.textpad — Text input widget for curses programs¶\\n\\nThe curses.textpad module provides a 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.\\n\\nThe module curses.textpad defines the following function:\\n\\nTextbox objects¶\\n\\nYou can instantiate a Textbox object as follows:\\n\\nTable of Contents\\n\\ncurses — Terminal handling for character-cell displays\\n\\nFunctions\\n\\nWindow Objects\\n\\nConstants\\n\\ncurses.textpad — Text input widget for curses programs\\n\\nTextbox objects\\n\\nPrevious topic\\n\\nfileinput — Iterate over lines from multiple input streams\\n\\nNext topic\\n\\ncurses.ascii — Utilities for ASCII characters\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nCommand-line interface libraries »\\n\\ncurses — Terminal handling for character-cell displays\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\curses.panel.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nCommand-line interface libraries »\\n\\ncurses.panel — A panel stack extension for curses\\n\\n|\\n\\ncurses.panel — A panel stack extension for curses¶\\n\\nPanels are windows with the added feature of depth, so they can be stacked on top of each other, and only the visible portions of each window will be displayed. Panels can be added, moved up or down in the stack, and removed.\\n\\nFunctions¶\\n\\nThe module curses.panel defines the following functions:\\n\\nPanel Objects¶\\n\\nPanel objects, as returned by new_panel() above, are windows with a stacking order. There’s always a window associated with a panel which determines the content, while the panel methods are responsible for the window’s depth in the panel stack.\\n\\nPanel objects have the following methods:\\n\\nTable of Contents\\n\\ncurses.panel — A panel stack extension for curses\\n\\nFunctions\\n\\nPanel Objects\\n\\nPrevious topic\\n\\ncurses.ascii — Utilities for ASCII characters\\n\\nNext topic\\n\\ncmd — Support for line-oriented command interpreters\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nCommand-line interface libraries »\\n\\ncurses.panel — A panel stack extension for curses\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\custominterp.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nCustom Python Interpreters\\n\\n|\\n\\nCustom Python Interpreters¶\\n\\nThe modules described in this chapter allow writing interfaces similar to Python’s interactive interpreter. If you want a Python interpreter that supports some special feature in addition to the Python language, you should look at the code module. (The codeop module is lower-level, used to support compiling a possibly incomplete chunk of Python code.)\\n\\nThe full list of modules described in this chapter is:\\n\\ncode — Interpreter base classes\\n\\nInteractive Interpreter Objects\\n\\nInteractive Console Objects\\n\\ncodeop — Compile Python code\\n\\nPrevious topic\\n\\nsite — Site-specific configuration hook\\n\\nNext topic\\n\\ncode — Interpreter base classes\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nCustom Python Interpreters\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\dataclasses.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Runtime Services »\\n\\ndataclasses — Data Classes\\n\\n|\\n\\ndataclasses — Data Classes¶\\n\\nSource code: Lib/dataclasses.py\\n\\nThis module provides a decorator and functions for automatically adding generated special methods such as __init__() and __repr__() to user-defined classes. It was originally described in PEP 557.\\n\\nThe member variables to use in these generated methods are defined using PEP 526 type annotations. For example, this code:\\n\\nfrom dataclasses import dataclass\\n\\n@dataclass\\nclass InventoryItem:\\n \"\"\"Class for keeping track of an item in inventory.\"\"\"\\n name: str\\n unit_price: float\\n quantity_on_hand: int = 0\\n\\n def total_cost(self) -> float:\\n return self.unit_price * self.quantity_on_hand\\n\\nwill add, among other things, a __init__() that looks like:\\n\\ndef __init__(self, name: str, unit_price: float, quantity_on_hand: int = 0):\\n self.name = name\\n self.unit_price = unit_price\\n self.quantity_on_hand = quantity_on_hand\\n\\nNote that this method is automatically added to the class: it is not directly specified in the InventoryItem definition shown above.\\n\\nAdded in version 3.7.\\n\\nModule contents¶\\n\\nPost-init processing¶\\n\\nThe __init__() method generated by @dataclass does not call base class __init__() methods. If the base class has an __init__() method that has to be called, it is common to call this method in a __post_init__() method:\\n\\nclass Rectangle:\\n def __init__(self, height, width):\\n self.height = height\\n self.width = width\\n\\n@dataclass\\nclass Square(Rectangle):\\n side: float\\n\\n def __post_init__(self):\\n super().__init__(self.side, self.side)\\n\\nNote, however, that in general the dataclass-generated __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.\\n\\nSee the section below on init-only variables for ways to pass parameters to __post_init__(). Also see the warning about how replace() handles init=False fields.\\n\\nClass variables¶\\n\\nOne of the few places where @dataclass actually inspects the type of a field is to determine if a field is a class variable as defined in PEP 526. It does this by checking if the type of the field is typing.ClassVar. If a field is a ClassVar, it is excluded from consideration as a field and is ignored by the dataclass mechanisms. Such ClassVar pseudo-fields are not returned by the module-level fields() function.\\n\\nInit-only variables¶\\n\\nAnother place where @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 InitVar. If a field is an 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 fields() function. Init-only fields are added as parameters to the generated __init__() method, and are passed to the optional __post_init__() method. They are not otherwise used by dataclasses.\\n\\nFor example, suppose a field will be initialized from a database, if a value is not provided when creating the class:\\n\\n@dataclass\\nclass C:\\n i: int\\n j: int | None = None\\n database: InitVar[DatabaseType | None] = None\\n\\n def __post_init__(self, database):\\n if self.j is None and database is not None:\\n self.j = database.lookup(\\'j\\')\\n\\nc = C(10, database=my_database)\\n\\nIn this case, fields() will return Field objects for i and j, but not for database.\\n\\nFrozen instances¶\\n\\nIt is not possible to create truly immutable Python objects. However, by passing frozen=True to the @dataclass decorator you can emulate immutability. In that case, dataclasses will add __setattr__() and __delattr__() methods to the class. These methods will raise a FrozenInstanceError when invoked.\\n\\nThere is a tiny performance penalty when using frozen=True: __init__() cannot use simple assignment to initialize fields, and must use object.__setattr__().\\n\\nInheritance¶\\n\\nWhen the dataclass is being created by the @dataclass decorator, it looks through all of the class’s base classes in reverse MRO (that is, starting at 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:\\n\\n@dataclass\\nclass Base:\\n x: Any = 15.0\\n y: int = 0\\n\\n@dataclass\\nclass C(Base):\\n z: int = 10\\n x: int = 15\\n\\nThe final list of fields is, in order, x, y, z. The final type of x is int, as specified in class C.\\n\\nThe generated __init__() method for C will look like:\\n\\ndef __init__(self, x: int = 15, y: int = 0, z: int = 10):\\n\\nRe-ordering of keyword-only parameters in __init__()¶\\n\\nAfter the parameters needed for __init__() are computed, any keyword-only parameters are moved to come after all regular (non-keyword-only) parameters. This is a requirement of how keyword-only parameters are implemented in Python: they must come after non-keyword-only parameters.\\n\\nIn this example, Base.y, Base.w, and D.t are keyword-only fields, and Base.x and D.z are regular fields:\\n\\n@dataclass\\nclass Base:\\n x: Any = 15.0\\n _: KW_ONLY\\n y: int = 0\\n w: int = 1\\n\\n@dataclass\\nclass D(Base):\\n z: int = 10\\n t: int = field(kw_only=True, default=0)\\n\\nThe generated __init__() method for D will look like:\\n\\ndef __init__(self, x: Any = 15.0, z: int = 10, *, y: int = 0, w: int = 1, t: int = 0):\\n\\nNote that the parameters have been re-ordered from how they appear in the list of fields: parameters derived from regular fields are followed by parameters derived from keyword-only fields.\\n\\nThe relative ordering of keyword-only parameters is maintained in the re-ordered __init__() parameter list.\\n\\nDefault factory functions¶\\n\\nIf a 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:\\n\\nmylist: list = field(default_factory=list)\\n\\nIf a field is excluded from __init__() (using init=False) and the field also specifies default_factory, then the default factory function will always be called from the generated __init__() function. This happens because there is no other way to give the field an initial value.\\n\\nMutable default values¶\\n\\nPython stores default member variable values in class attributes. Consider this example, not using dataclasses:\\n\\nclass C:\\n x = []\\n def add(self, element):\\n self.x.append(element)\\n\\no1 = C()\\no2 = C()\\no1.add(1)\\no2.add(2)\\nassert o1.x == [1, 2]\\nassert o1.x is o2.x\\n\\nNote that the two instances of class C share the same class variable x, as expected.\\n\\nUsing dataclasses, if this code was valid:\\n\\n@dataclass\\nclass D:\\n x: list = [] # This code raises ValueError\\n def add(self, element):\\n self.x.append(element)\\n\\nit would generate code similar to:\\n\\nclass D:\\n x = []\\n def __init__(self, x=x):\\n self.x = x\\n def add(self, element):\\n self.x.append(element)\\n\\nassert D().x is D().x\\n\\nThis has the same issue as the original example using class C. That is, two instances of class D that do not specify a value for x when creating a class instance will share the same copy of 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 @dataclass decorator will raise a 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.\\n\\nUsing default factory functions is a way to create new instances of mutable types as default values for fields:\\n\\n@dataclass\\nclass D:\\n x: list = field(default_factory=list)\\n\\nassert D().x is not D().x\\n\\nChanged in version 3.11: Instead of looking for and disallowing objects of type list, dict, or set, unhashable objects are now not allowed as default values. Unhashability is used to approximate mutability.\\n\\nDescriptor-typed fields¶\\n\\nFields that are assigned descriptor objects as their default value have the following special behaviors:\\n\\nThe value for the field passed to the dataclass’s __init__() method is passed to the descriptor’s __set__() method rather than overwriting the descriptor object.\\n\\nSimilarly, when getting or setting the field, the descriptor’s __get__() or __set__() method is called rather than returning or overwriting the descriptor object.\\n\\nTo determine whether a field contains a default value, @dataclass will call the descriptor’s __get__() method using its class access form: 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 AttributeError in this situation, no default value will be provided for the field.\\n\\nclass IntConversionDescriptor:\\n def __init__(self, *, default):\\n self._default = default\\n\\n def __set_name__(self, owner, name):\\n self._name = \"_\" + name\\n\\n def __get__(self, obj, type):\\n if obj is None:\\n return self._default\\n\\n return getattr(obj, self._name, self._default)\\n\\n def __set__(self, obj, value):\\n setattr(obj, self._name, int(value))\\n\\n@dataclass\\nclass InventoryItem:\\n quantity_on_hand: IntConversionDescriptor = IntConversionDescriptor(default=100)\\n\\ni = InventoryItem()\\nprint(i.quantity_on_hand) # 100\\ni.quantity_on_hand = 2.5 # calls __set__ with 2.5\\nprint(i.quantity_on_hand) # 2\\n\\nNote 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.\\n\\nTable of Contents\\n\\ndataclasses — Data Classes\\n\\nModule contents\\n\\nPost-init processing\\n\\nClass variables\\n\\nInit-only variables\\n\\nFrozen instances\\n\\nInheritance\\n\\nRe-ordering of keyword-only parameters in __init__()\\n\\nDefault factory functions\\n\\nMutable default values\\n\\nDescriptor-typed fields\\n\\nPrevious topic\\n\\nwarnings — Warning control\\n\\nNext topic\\n\\ncontextlib — Utilities for with-statement contexts\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Runtime Services »\\n\\ndataclasses — Data Classes\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\datatypes.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Types\\n\\n|\\n\\nData Types¶\\n\\nThe modules described in this chapter provide a variety of specialized data types such as dates and times, fixed-type arrays, heap queues, double-ended queues, and enumerations.\\n\\nPython also provides some built-in data types, in particular, dict, list, set and frozenset, and tuple. The str class is used to hold Unicode strings, and the bytes and bytearray classes are used to hold binary data.\\n\\nThe following modules are documented in this chapter:\\n\\ndatetime — Basic date and time types\\n\\nAware and naive objects\\n\\nConstants\\n\\nAvailable types\\n\\nCommon properties\\n\\nDetermining if an object is aware or naive\\n\\ntimedelta objects\\n\\nExamples of usage: timedelta\\n\\ndate objects\\n\\nExamples of usage: date\\n\\ndatetime objects\\n\\nExamples of usage: datetime\\n\\ntime objects\\n\\nExamples of usage: time\\n\\ntzinfo objects\\n\\ntimezone objects\\n\\nstrftime() and strptime() behavior\\n\\nstrftime() and strptime() format codes\\n\\nTechnical detail\\n\\nzoneinfo — IANA time zone support\\n\\nUsing ZoneInfo\\n\\nData sources\\n\\nConfiguring the data sources\\n\\nCompile-time configuration\\n\\nEnvironment configuration\\n\\nRuntime configuration\\n\\nThe ZoneInfo class\\n\\nString representations\\n\\nPickle serialization\\n\\nFunctions\\n\\nGlobals\\n\\nExceptions and warnings\\n\\ncalendar — General calendar-related functions\\n\\nCommand-line usage\\n\\ncollections — Container datatypes\\n\\nChainMap objects\\n\\nChainMap Examples and Recipes\\n\\nCounter objects\\n\\ndeque objects\\n\\ndeque Recipes\\n\\ndefaultdict objects\\n\\ndefaultdict Examples\\n\\nnamedtuple() Factory Function for Tuples with Named Fields\\n\\nOrderedDict objects\\n\\nOrderedDict Examples and Recipes\\n\\nUserDict objects\\n\\nUserList objects\\n\\nUserString objects\\n\\ncollections.abc — Abstract Base Classes for Containers\\n\\nCollections Abstract Base Classes\\n\\nCollections Abstract Base Classes – Detailed Descriptions\\n\\nExamples and Recipes\\n\\nheapq — Heap queue algorithm\\n\\nBasic Examples\\n\\nOther Applications\\n\\nPriority Queue Implementation Notes\\n\\nTheory\\n\\nbisect — Array bisection algorithm\\n\\nPerformance Notes\\n\\nSearching Sorted Lists\\n\\nExamples\\n\\narray — Efficient arrays of numeric values\\n\\nweakref — Weak references\\n\\nWeak Reference Objects\\n\\nExample\\n\\nFinalizer Objects\\n\\nComparing finalizers with __del__() methods\\n\\ntypes — Dynamic type creation and names for built-in types\\n\\nDynamic Type Creation\\n\\nStandard Interpreter Types\\n\\nAdditional Utility Classes and Functions\\n\\nCoroutine Utility Functions\\n\\ncopy — Shallow and deep copy operations\\n\\npprint — Data pretty printer\\n\\nFunctions\\n\\nPrettyPrinter Objects\\n\\nExample\\n\\nreprlib — Alternate repr() implementation\\n\\nRepr Objects\\n\\nSubclassing Repr Objects\\n\\nenum — Support for enumerations\\n\\nModule Contents\\n\\nData Types\\n\\nSupported __dunder__ names\\n\\nSupported _sunder_ names\\n\\nUtilities and Decorators\\n\\nNotes\\n\\ngraphlib — Functionality to operate with graph-like structures\\n\\nExceptions\\n\\nPrevious topic\\n\\ncodecs — Codec registry and base classes\\n\\nNext topic\\n\\ndatetime — Basic date and time types\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Types\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\datetime.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Types »\\n\\ndatetime — Basic date and time types\\n\\n|\\n\\ndatetime — Basic date and time types¶\\n\\nSource code: Lib/datetime.py\\n\\nThe datetime module supplies classes for manipulating dates and times.\\n\\nWhile date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation.\\n\\nTip\\n\\nSkip to the format codes.\\n\\nSee also\\n\\nAware and naive objects¶\\n\\nDate and time objects may be categorized as “aware” or “naive” depending on whether or not they include time zone information.\\n\\nWith sufficient knowledge of applicable algorithmic and political time adjustments, such as time zone and daylight saving time information, an aware object can locate itself relative to other aware objects. An aware object represents a specific moment in time that is not open to interpretation. [1]\\n\\nA naive object does not contain enough information to unambiguously locate itself relative to other date/time objects. Whether a naive object represents Coordinated Universal Time (UTC), local time, or time in some other time zone is purely up to the program, just like it is up to the program whether a particular number represents metres, miles, or mass. Naive objects are easy to understand and to work with, at the cost of ignoring some aspects of reality.\\n\\nFor applications requiring aware objects, datetime and time objects have an optional time zone information attribute, tzinfo, that can be set to an instance of a subclass of the abstract tzinfo class. These tzinfo objects capture information about the offset from UTC time, the time zone name, and whether daylight saving time is in effect.\\n\\nOnly one concrete tzinfo class, the timezone class, is supplied by the datetime module. The timezone class can represent simple time zones with fixed offsets from UTC, such as UTC itself or North American EST and EDT time zones. Supporting time zones at deeper levels of detail is up to the application. The rules for time adjustment across the world are more political than rational, change frequently, and there is no standard suitable for every application aside from UTC.\\n\\nConstants¶\\n\\nThe datetime module exports the following constants:\\n\\nAvailable types¶\\n\\nObjects of these types are immutable.\\n\\nSubclass relationships:\\n\\nCommon properties¶\\n\\nThe date, datetime, time, and timezone types share these common features:\\n\\nObjects of these types are immutable.\\n\\nObjects of these types are hashable, meaning that they can be used as dictionary keys.\\n\\nObjects of these types support efficient pickling via the pickle module.\\n\\nDetermining if an object is aware or naive¶\\n\\nObjects of the date type are always naive.\\n\\nAn object of type time or datetime may be aware or naive.\\n\\nA datetime object d is aware if both of the following hold:\\n\\nd.tzinfo is not None\\n\\nd.tzinfo.utcoffset(d) does not return None\\n\\nOtherwise, d is naive.\\n\\nA time object t is aware if both of the following hold:\\n\\nt.tzinfo is not None\\n\\nt.tzinfo.utcoffset(None) does not return None.\\n\\nOtherwise, t is naive.\\n\\nThe distinction between aware and naive doesn’t apply to timedelta objects.\\n\\ntimedelta objects¶\\n\\nA timedelta object represents a duration, the difference between two datetime or date instances.\\n\\nClass attributes:\\n\\nNote that, because of normalization, timedelta.max is greater than -timedelta.min. -timedelta.max is not representable as a timedelta object.\\n\\nInstance attributes (read-only):\\n\\nSupported operations:\\n\\nOperation Result t1 = t2 + t3 Sum of t2 and t3 .\\nAfterwards t1 - t2 == t3 and t1 - t3 == t2 are true. (1) t1 = t2 - t3 Difference of t2 and t3 . Afterwards t1 == t2 - t3 and t2 == t1 + t3 are\\ntrue. (1)(6) t1 = t2 * i or t1 = i * t2 Delta multiplied by an integer.\\nAfterwards t1 // i == t2 is true,\\nprovided i != 0 . In general, t1 * i == t1 * (i-1) + t1 is true. (1) t1 = t2 * f or t1 = f * t2 Delta multiplied by a float. The result is\\nrounded to the nearest multiple of\\ntimedelta.resolution using round-half-to-even. f = t2 / t3 Division (3) of overall duration t2 by\\ninterval unit t3 . Returns a float object. t1 = t2 / f or t1 = t2 / i Delta divided by a float or an int. The result\\nis rounded to the nearest multiple of\\ntimedelta.resolution using round-half-to-even. t1 = t2 // i or t1 = t2 // t3 The floor is computed and the remainder (if\\nany) is thrown away. In the second case, an\\ninteger is returned. (3) t1 = t2 % t3 The remainder is computed as a timedelta object. (3) q, r = divmod(t1, t2) Computes the quotient and the remainder: q = t1 // t2 (3) and r = t1 % t2 . q is an integer and r is a timedelta object. +t1 Returns a timedelta object with the\\nsame value. (2) -t1 Equivalent to timedelta(-t1.days, -t1.seconds, -t1.microseconds) ,\\nand to t1 * -1 . (1)(4) abs(t) Equivalent to +t when t.days >= 0 ,\\nand to -t when t.days < 0 . (2) str(t) Returns a string in the form [D day[s], ][H]H:MM:SS[.UUUUUU] , where D\\nis negative for negative t . (5) repr(t) Returns a string representation of the timedelta object as a constructor\\ncall with canonical attribute values.\\n\\nNotes:\\n\\nThis is exact but may overflow.\\n\\nThis is exact and cannot overflow.\\n\\nDivision by zero raises ZeroDivisionError.\\n\\ntimedelta.max is not representable as a timedelta object.\\n\\nString representations of timedelta objects are normalized similarly to their internal representation. This leads to somewhat unusual results for negative timedeltas. For example:\\n\\n>>> timedelta(hours=-5)\\ndatetime.timedelta(days=-1, seconds=68400)\\n>>> print(_)\\n-1 day, 19:00:00\\n\\nThe expression t2 - t3 will always be equal to the expression t2 + (-t3) except when t3 is equal to timedelta.max; in that case the former will produce a result while the latter will overflow.\\n\\nIn addition to the operations listed above, timedelta objects support certain additions and subtractions with date and datetime objects (see below).\\n\\nChanged in version 3.2: Floor division and true division of a timedelta object by another timedelta object are now supported, as are remainder operations and the divmod() function. True division and multiplication of a timedelta object by a float object are now supported.\\n\\ntimedelta objects support equality and order comparisons.\\n\\nIn Boolean contexts, a timedelta object is considered to be true if and only if it isn’t equal to timedelta(0).\\n\\nInstance methods:\\n\\nExamples of usage: timedelta¶\\n\\nAn additional example of normalization:\\n\\n>>> # Components of another_year add up to exactly 365 days\\n>>> import datetime as dt\\n>>> year = dt.timedelta(days=365)\\n>>> another_year = dt.timedelta(weeks=40, days=84, hours=23,\\n... minutes=50, seconds=600)\\n>>> year == another_year\\nTrue\\n>>> year.total_seconds()\\n31536000.0\\n\\nExamples of timedelta arithmetic:\\n\\n>>> import datetime as dt\\n>>> year = dt.timedelta(days=365)\\n>>> ten_years = 10 * year\\n>>> ten_years\\ndatetime.timedelta(days=3650)\\n>>> ten_years.days // 365\\n10\\n>>> nine_years = ten_years - year\\n>>> nine_years\\ndatetime.timedelta(days=3285)\\n>>> three_years = nine_years // 3\\n>>> three_years, three_years.days // 365\\n(datetime.timedelta(days=1095), 3)\\n\\ndate objects¶\\n\\nA date object represents a date (year, month and day) in an idealized calendar, the current Gregorian calendar indefinitely extended in both directions.\\n\\nJanuary 1 of year 1 is called day number 1, January 2 of year 1 is called day number 2, and so on. [2]\\n\\nOther constructors, all class methods:\\n\\nClass attributes:\\n\\nInstance attributes (read-only):\\n\\nSupported operations:\\n\\nOperation Result date2 = date1 + timedelta date2 will be timedelta.days days\\nafter date1 . (1) date2 = date1 - timedelta Computes date2 such that date2 + timedelta == date1 . (2) timedelta = date1 - date2 (3) date1 == date2 date1 != date2 Equality comparison. (4) date1 < date2 date1 > date2 date1 <= date2 date1 >= date2 Order comparison. (5)\\n\\nNotes:\\n\\ndate2 is moved forward in time if timedelta.days > 0, or backward if timedelta.days < 0. Afterward date2 - date1 == timedelta.days. timedelta.seconds and timedelta.microseconds are ignored. OverflowError is raised if date2.year would be smaller than MINYEAR or larger than MAXYEAR.\\n\\ntimedelta.seconds and timedelta.microseconds are ignored.\\n\\nThis is exact, and cannot overflow. timedelta.seconds and timedelta.microseconds are 0, and date2 + timedelta == date1 after.\\n\\ndate objects are equal if they represent the same date.\\n\\ndate objects that are not also datetime instances are never equal to datetime objects, even if they represent the same date.\\n\\ndate1 is considered less than date2 when date1 precedes date2 in time. In other words, date1 < date2 if and only if date1.toordinal() < date2.toordinal().\\n\\nOrder comparison between a date object that is not also a datetime instance and a datetime object raises TypeError.\\n\\nChanged in version 3.13: Comparison between datetime object and an instance of the date subclass that is not a datetime subclass no longer converts the latter to date, ignoring the time part and the time zone. The default behavior can be changed by overriding the special comparison methods in subclasses.\\n\\nIn Boolean contexts, all date objects are considered to be true.\\n\\nInstance methods:\\n\\nExamples of usage: date¶\\n\\nExample of counting days to an event:\\n\\n>>> import time\\n>>> import datetime as dt\\n>>> today = dt.date.today()\\n>>> today\\ndatetime.date(2007, 12, 5)\\n>>> today == dt.date.fromtimestamp(time.time())\\nTrue\\n>>> my_birthday = dt.date(today.year, 6, 24)\\n>>> if my_birthday < today:\\n... my_birthday = my_birthday.replace(year=today.year + 1)\\n...\\n>>> my_birthday\\ndatetime.date(2008, 6, 24)\\n>>> time_to_birthday = abs(my_birthday - today)\\n>>> time_to_birthday.days\\n202\\n\\nMore examples of working with date:\\n\\n>>> import datetime as dt\\n>>> d = dt.date.fromordinal(730920) # 730920th day after 1. 1. 0001\\n>>> d\\ndatetime.date(2002, 3, 11)\\n\\n>>> # Methods related to formatting string output\\n>>> d.isoformat()\\n\\'2002-03-11\\'\\n>>> d.strftime(\"%d/%m/%y\")\\n\\'11/03/02\\'\\n>>> d.strftime(\"%A %d. %B %Y\")\\n\\'Monday 11. March 2002\\'\\n>>> d.ctime()\\n\\'Mon Mar 11 00:00:00 2002\\'\\n>>> \\'The {1} is {0:%d}, the {2} is {0:%B}.\\'.format(d, \"day\", \"month\")\\n\\'The day is 11, the month is March.\\'\\n\\n>>> # Methods for extracting \\'components\\' under different calendars\\n>>> t = d.timetuple()\\n>>> for i in t:\\n... print(i)\\n2002 # year\\n3 # month\\n11 # day\\n0\\n0\\n0\\n0 # weekday (0 = Monday)\\n70 # 70th day in the year\\n-1\\n>>> ic = d.isocalendar()\\n>>> for i in ic:\\n... print(i)\\n2002 # ISO year\\n11 # ISO week number\\n1 # ISO day number ( 1 = Monday )\\n\\n>>> # A date object is immutable; all operations produce a new object\\n>>> d.replace(year=2005)\\ndatetime.date(2005, 3, 11)\\n\\ndatetime objects¶\\n\\nA datetime object is a single object containing all the information from a date object and a time object.\\n\\nLike a date object, datetime assumes the current Gregorian calendar extended in both directions; like a time object, datetime assumes there are exactly 3600*24 seconds in every day.\\n\\nConstructor:\\n\\nOther constructors, all class methods:\\n\\nClass attributes:\\n\\nInstance attributes (read-only):\\n\\nSupported operations:\\n\\nOperation Result datetime2 = datetime1 + timedelta (1) datetime2 = datetime1 - timedelta (2) timedelta = datetime1 - datetime2 (3) datetime1 == datetime2 datetime1 != datetime2 Equality comparison. (4) datetime1 < datetime2 datetime1 > datetime2 datetime1 <= datetime2 datetime1 >= datetime2 Order comparison. (5)\\n\\ndatetime2 is a duration of timedelta removed from datetime1, moving forward in time if timedelta.days > 0, or backward if timedelta.days < 0. The result has the same tzinfo attribute as the input datetime, and datetime2 - datetime1 == timedelta after. OverflowError is raised if datetime2.year would be smaller than MINYEAR or larger than MAXYEAR. Note that no time zone adjustments are done even if the input is an aware object.\\n\\nComputes the datetime2 such that datetime2 + timedelta == datetime1. As for addition, the result has the same tzinfo attribute as the input datetime, and no time zone adjustments are done even if the input is aware.\\n\\nSubtraction of a datetime from a datetime is defined only if both operands are naive, or if both are aware. If one is aware and the other is naive, TypeError is raised.\\n\\nIf both are naive, or both are aware and have the same tzinfo attribute, the tzinfo attributes are ignored, and the result is a timedelta object t such that datetime2 + t == datetime1. No time zone adjustments are done in this case.\\n\\nIf both are aware and have different tzinfo attributes, a-b acts as if a and b were first converted to naive UTC datetimes. The result is (a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None) - b.utcoffset()) except that the implementation never overflows.\\n\\ndatetime objects are equal if they represent the same date and time, taking into account the time zone.\\n\\nNaive and aware datetime objects are never equal.\\n\\nIf both comparands are aware, and have the same tzinfo attribute, the tzinfo and fold attributes are ignored and the base datetimes are compared. If both comparands are aware and have different tzinfo attributes, the comparison acts as comparands were first converted to UTC datetimes except that the implementation never overflows. datetime instances in a repeated interval are never equal to datetime instances in other time zone.\\n\\ndatetime1 is considered less than datetime2 when datetime1 precedes datetime2 in time, taking into account the time zone.\\n\\nOrder comparison between naive and aware datetime objects raises TypeError.\\n\\nIf both comparands are aware, and have the same tzinfo attribute, the tzinfo and fold attributes are ignored and the base datetimes are compared. If both comparands are aware and have different tzinfo attributes, the comparison acts as comparands were first converted to UTC datetimes except that the implementation never overflows.\\n\\nChanged in version 3.3: Equality comparisons between aware and naive datetime instances don’t raise TypeError.\\n\\nChanged in version 3.13: Comparison between datetime object and an instance of the date subclass that is not a datetime subclass no longer converts the latter to date, ignoring the time part and the time zone. The default behavior can be changed by overriding the special comparison methods in subclasses.\\n\\nInstance methods:\\n\\nExamples of usage: datetime¶\\n\\nExamples of working with datetime objects:\\n\\n>>> import datetime as dt\\n\\n>>> # Using datetime.combine()\\n>>> d = dt.date(2005, 7, 14)\\n>>> t = dt.time(12, 30)\\n>>> dt.datetime.combine(d, t)\\ndatetime.datetime(2005, 7, 14, 12, 30)\\n\\n>>> # Using datetime.now()\\n>>> dt.datetime.now()\\ndatetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1\\n>>> dt.datetime.now(dt.timezone.utc)\\ndatetime.datetime(2007, 12, 6, 15, 29, 43, 79060, tzinfo=datetime.timezone.utc)\\n\\n>>> # Using datetime.strptime()\\n>>> my_datetime = dt.datetime.strptime(\"21/11/06 16:30\", \"%d/%m/%y %H:%M\")\\n>>> my_datetime\\ndatetime.datetime(2006, 11, 21, 16, 30)\\n\\n>>> # Using datetime.timetuple() to get tuple of all attributes\\n>>> tt = my_datetime.timetuple()\\n>>> for it in tt:\\n... print(it)\\n...\\n2006 # year\\n11 # month\\n21 # day\\n16 # hour\\n30 # minute\\n0 # second\\n1 # weekday (0 = Monday)\\n325 # number of days since 1st January\\n-1 # dst - method tzinfo.dst() returned None\\n\\n>>> # Date in ISO format\\n>>> ic = my_datetime.isocalendar()\\n>>> for it in ic:\\n... print(it)\\n...\\n2006 # ISO year\\n47 # ISO week\\n2 # ISO weekday\\n\\n>>> # Formatting a datetime\\n>>> my_datetime.strftime(\"%A, %d. %B %Y %I:%M%p\")\\n\\'Tuesday, 21. November 2006 04:30PM\\'\\n>>> \\'The {1} is {0:%d}, the {2} is {0:%B}, the {3} is {0:%I:%M%p}.\\'.format(my_datetime, \"day\", \"month\", \"time\")\\n\\'The day is 21, the month is November, the time is 04:30PM.\\'\\n\\nThe example below defines a tzinfo subclass capturing time zone information for Kabul, Afghanistan, which used +4 UTC until 1945 and then +4:30 UTC thereafter:\\n\\nimport datetime as dt\\n\\nclass KabulTz(dt.tzinfo):\\n # Kabul used +4 until 1945, when they moved to +4:30\\n UTC_MOVE_DATE = dt.datetime(1944, 12, 31, 20, tzinfo=dt.timezone.utc)\\n\\n def utcoffset(self, when):\\n if when.year < 1945:\\n return dt.timedelta(hours=4)\\n elif (1945, 1, 1, 0, 0) <= when.timetuple()[:5] < (1945, 1, 1, 0, 30):\\n # An ambiguous (\"imaginary\") half-hour range representing\\n # a \\'fold\\' in time due to the shift from +4 to +4:30.\\n # If when falls in the imaginary range, use fold to decide how\\n # to resolve. See PEP 495.\\n return dt.timedelta(hours=4, minutes=(30 if when.fold else 0))\\n else:\\n return dt.timedelta(hours=4, minutes=30)\\n\\n def fromutc(self, when):\\n # Follow same validations as in datetime.tzinfo\\n if not isinstance(when, dt.datetime):\\n raise TypeError(\"fromutc() requires a datetime argument\")\\n if when.tzinfo is not self:\\n raise ValueError(\"when.tzinfo is not self\")\\n\\n # A custom implementation is required for fromutc as\\n # the input to this function is a datetime with utc values\\n # but with a tzinfo set to self.\\n # See datetime.astimezone or fromtimestamp.\\n if when.replace(tzinfo=dt.timezone.utc) >= self.UTC_MOVE_DATE:\\n return when + dt.timedelta(hours=4, minutes=30)\\n else:\\n return when + dt.timedelta(hours=4)\\n\\n def dst(self, when):\\n # Kabul does not observe daylight saving time.\\n return dt.timedelta(0)\\n\\n def tzname(self, when):\\n if when >= self.UTC_MOVE_DATE:\\n return \"+04:30\"\\n return \"+04\"\\n\\nUsage of KabulTz from above:\\n\\n>>> tz1 = KabulTz()\\n\\n>>> # Datetime before the change\\n>>> dt1 = dt.datetime(1900, 11, 21, 16, 30, tzinfo=tz1)\\n>>> print(dt1.utcoffset())\\n4:00:00\\n\\n>>> # Datetime after the change\\n>>> dt2 = dt.datetime(2006, 6, 14, 13, 0, tzinfo=tz1)\\n>>> print(dt2.utcoffset())\\n4:30:00\\n\\n>>> # Convert datetime to another time zone\\n>>> dt3 = dt2.astimezone(dt.timezone.utc)\\n>>> dt3\\ndatetime.datetime(2006, 6, 14, 8, 30, tzinfo=datetime.timezone.utc)\\n>>> dt2\\ndatetime.datetime(2006, 6, 14, 13, 0, tzinfo=KabulTz())\\n>>> dt2 == dt3\\nTrue\\n\\ntime objects¶\\n\\nA time object represents a (local) time of day, independent of any particular day, and subject to adjustment via a tzinfo object.\\n\\nClass attributes:\\n\\nInstance attributes (read-only):\\n\\ntime objects support equality and order comparisons, where a is considered less than b when a precedes b in time.\\n\\nNaive and aware time objects are never equal. Order comparison between naive and aware time objects raises TypeError.\\n\\nIf both comparands are aware, and have the same tzinfo attribute, the tzinfo and fold attributes are ignored and the base times are compared. If both comparands are aware and have different tzinfo attributes, the comparands are first adjusted by subtracting their UTC offsets (obtained from self.utcoffset()).\\n\\nChanged in version 3.3: Equality comparisons between aware and naive time instances don’t raise TypeError.\\n\\nIn Boolean contexts, a time object is always considered to be true.\\n\\nChanged in version 3.5: Before Python 3.5, a 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 for more information.\\n\\nOther constructors:\\n\\nInstance methods:\\n\\nExamples of usage: time¶\\n\\nExamples of working with a time object:\\n\\n>>> import datetime as dt\\n>>> class TZ1(dt.tzinfo):\\n... def utcoffset(self, when):\\n... return dt.timedelta(hours=1)\\n... def dst(self, when):\\n... return dt.timedelta(0)\\n... def tzname(self, when):\\n... return \"+01:00\"\\n... def __repr__(self):\\n... return f\"{self.__class__.__name__}()\"\\n...\\n>>> t = dt.time(12, 10, 30, tzinfo=TZ1())\\n>>> t\\ndatetime.time(12, 10, 30, tzinfo=TZ1())\\n>>> t.isoformat()\\n\\'12:10:30+01:00\\'\\n>>> t.dst()\\ndatetime.timedelta(0)\\n>>> t.tzname()\\n\\'+01:00\\'\\n>>> t.strftime(\"%H:%M:%S %Z\")\\n\\'12:10:30 +01:00\\'\\n>>> \\'The {} is {:%H:%M}.\\'.format(\"time\", t)\\n\\'The time is 12:10.\\'\\n\\ntzinfo objects¶\\n\\nThese methods are called by a datetime or time object, in response to their methods of the same names. A datetime object passes itself as the argument, and a time object passes None as the argument. A tzinfo subclass’s methods should therefore be prepared to accept a dt argument of None, or of class datetime.\\n\\nWhen None is passed, it’s up to the class designer to decide the best response. For example, returning None is appropriate if the class wishes to say that time objects don’t participate in the tzinfo protocols. It may be more useful for utcoffset(None) to return the standard UTC offset, as there is no other convention for discovering the standard offset.\\n\\nWhen a datetime object is passed in response to a datetime method, dt.tzinfo is the same object as self. tzinfo methods can rely on this, unless user code calls tzinfo methods directly. The intent is that the tzinfo methods interpret dt as being in local time, and not need worry about objects in other time zones.\\n\\nThere is one more tzinfo method that a subclass may wish to override:\\n\\nIn the following tzinfo_examples.py file there are some examples of tzinfo classes:\\n\\nimport datetime as dt\\n\\n# A class capturing the platform\\'s idea of local time.\\n# (May result in wrong values on historical times in\\n# timezones where UTC offset and/or the DST rules had\\n# changed in the past.)\\nimport time\\n\\nZERO = dt.timedelta(0)\\nHOUR = dt.timedelta(hours=1)\\nSECOND = dt.timedelta(seconds=1)\\n\\nSTDOFFSET = dt.timedelta(seconds=-time.timezone)\\nif time.daylight:\\n DSTOFFSET = dt.timedelta(seconds=-time.altzone)\\nelse:\\n DSTOFFSET = STDOFFSET\\n\\nDSTDIFF = DSTOFFSET - STDOFFSET\\n\\n\\nclass LocalTimezone(dt.tzinfo):\\n\\n def fromutc(self, when):\\n assert when.tzinfo is self\\n stamp = (when - dt.datetime(1970, 1, 1, tzinfo=self)) // SECOND\\n args = time.localtime(stamp)[:6]\\n dst_diff = DSTDIFF // SECOND\\n # Detect fold\\n fold = (args == time.localtime(stamp - dst_diff))\\n return dt.datetime(*args, microsecond=when.microsecond,\\n tzinfo=self, fold=fold)\\n\\n def utcoffset(self, when):\\n if self._isdst(when):\\n return DSTOFFSET\\n else:\\n return STDOFFSET\\n\\n def dst(self, when):\\n if self._isdst(when):\\n return DSTDIFF\\n else:\\n return ZERO\\n\\n def tzname(self, when):\\n return time.tzname[self._isdst(when)]\\n\\n def _isdst(self, when):\\n tt = (when.year, when.month, when.day,\\n when.hour, when.minute, when.second,\\n when.weekday(), 0, 0)\\n stamp = time.mktime(tt)\\n tt = time.localtime(stamp)\\n return tt.tm_isdst > 0\\n\\n\\nLocal = LocalTimezone()\\n\\n\\n# A complete implementation of current DST rules for major US time zones.\\n\\ndef first_sunday_on_or_after(when):\\n days_to_go = 6 - when.weekday()\\n if days_to_go:\\n when += dt.timedelta(days_to_go)\\n return when\\n\\n\\n# US DST Rules\\n#\\n# This is a simplified (i.e., wrong for a few cases) set of rules for US\\n# DST start and end times. For a complete and up-to-date set of DST rules\\n# and timezone definitions, visit the Olson Database (or try pytz):\\n# http://www.twinsun.com/tz/tz-link.htm\\n# https://sourceforge.net/projects/pytz/ (might not be up-to-date)\\n#\\n# In the US, since 2007, DST starts at 2am (standard time) on the second\\n# Sunday in March, which is the first Sunday on or after Mar 8.\\nDSTSTART_2007 = dt.datetime(1, 3, 8, 2)\\n# and ends at 2am (DST time) on the first Sunday of Nov.\\nDSTEND_2007 = dt.datetime(1, 11, 1, 2)\\n# From 1987 to 2006, DST used to start at 2am (standard time) on the first\\n# Sunday in April and to end at 2am (DST time) on the last\\n# Sunday of October, which is the first Sunday on or after Oct 25.\\nDSTSTART_1987_2006 = dt.datetime(1, 4, 1, 2)\\nDSTEND_1987_2006 = dt.datetime(1, 10, 25, 2)\\n# From 1967 to 1986, DST used to start at 2am (standard time) on the last\\n# Sunday in April (the one on or after April 24) and to end at 2am (DST time)\\n# on the last Sunday of October, which is the first Sunday\\n# on or after Oct 25.\\nDSTSTART_1967_1986 = dt.datetime(1, 4, 24, 2)\\nDSTEND_1967_1986 = DSTEND_1987_2006\\n\\n\\ndef us_dst_range(year):\\n # Find start and end times for US DST. For years before 1967, return\\n # start = end for no DST.\\n if 2006 < year:\\n dststart, dstend = DSTSTART_2007, DSTEND_2007\\n elif 1986 < year < 2007:\\n dststart, dstend = DSTSTART_1987_2006, DSTEND_1987_2006\\n elif 1966 < year < 1987:\\n dststart, dstend = DSTSTART_1967_1986, DSTEND_1967_1986\\n else:\\n return (dt.datetime(year, 1, 1), ) * 2\\n\\n start = first_sunday_on_or_after(dststart.replace(year=year))\\n end = first_sunday_on_or_after(dstend.replace(year=year))\\n return start, end\\n\\n\\nclass USTimeZone(dt.tzinfo):\\n\\n def __init__(self, hours, reprname, stdname, dstname):\\n self.stdoffset = dt.timedelta(hours=hours)\\n self.reprname = reprname\\n self.stdname = stdname\\n self.dstname = dstname\\n\\n def __repr__(self):\\n return self.reprname\\n\\n def tzname(self, when):\\n if self.dst(when):\\n return self.dstname\\n else:\\n return self.stdname\\n\\n def utcoffset(self, when):\\n return self.stdoffset + self.dst(when)\\n\\n def dst(self, when):\\n if when is None or when.tzinfo is None:\\n # An exception may be sensible here, in one or both cases.\\n # It depends on how you want to treat them. The default\\n # fromutc() implementation (called by the default astimezone()\\n # implementation) passes a datetime with when.tzinfo is self.\\n return ZERO\\n assert when.tzinfo is self\\n start, end = us_dst_range(when.year)\\n # Can\\'t compare naive to aware objects, so strip the timezone from\\n # when first.\\n when = when.replace(tzinfo=None)\\n if start + HOUR <= when < end - HOUR:\\n # DST is in effect.\\n return HOUR\\n if end - HOUR <= when < end:\\n # Fold (an ambiguous hour): use when.fold to disambiguate.\\n return ZERO if when.fold else HOUR\\n if start <= when < start + HOUR:\\n # Gap (a non-existent hour): reverse the fold rule.\\n return HOUR if when.fold else ZERO\\n # DST is off.\\n return ZERO\\n\\n def fromutc(self, when):\\n assert when.tzinfo is self\\n start, end = us_dst_range(when.year)\\n start = start.replace(tzinfo=self)\\n end = end.replace(tzinfo=self)\\n std_time = when + self.stdoffset\\n dst_time = std_time + HOUR\\n if end <= dst_time < end + HOUR:\\n # Repeated hour\\n return std_time.replace(fold=1)\\n if std_time < start or dst_time >= end:\\n # Standard time\\n return std_time\\n if start <= std_time < end - HOUR:\\n # Daylight saving time\\n return dst_time\\n\\n\\nEastern = USTimeZone(-5, \"Eastern\", \"EST\", \"EDT\")\\nCentral = USTimeZone(-6, \"Central\", \"CST\", \"CDT\")\\nMountain = USTimeZone(-7, \"Mountain\", \"MST\", \"MDT\")\\nPacific = USTimeZone(-8, \"Pacific\", \"PST\", \"PDT\")\\n\\nNote that there are unavoidable subtleties twice per year in a tzinfo subclass accounting for both standard and daylight time, at the DST transition points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the minute after 1:59 (EST) on the second Sunday in March, and ends the minute after 1:59 (EDT) on the first Sunday in November:\\n\\n UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM\\n EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM\\n EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM\\n\\nstart 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM\\n\\n end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM\\n\\nWhen DST starts (the “start” line), the local wall clock leaps from 1:59 to 3:00. A wall time of the form 2:MM doesn’t really make sense on that day, so astimezone(Eastern) won’t deliver a result with hour == 2 on the day DST begins. For example, at the Spring forward transition of 2016, we get:\\n\\n>>> import datetime as dt\\n>>> from tzinfo_examples import HOUR, Eastern\\n>>> u0 = dt.datetime(2016, 3, 13, 5, tzinfo=dt.timezone.utc)\\n>>> for i in range(4):\\n... u = u0 + i*HOUR\\n... t = u.astimezone(Eastern)\\n... print(u.time(), \\'UTC =\\', t.time(), t.tzname())\\n...\\n05:00:00 UTC = 00:00:00 EST\\n06:00:00 UTC = 01:00:00 EST\\n07:00:00 UTC = 03:00:00 EDT\\n08:00:00 UTC = 04:00:00 EDT\\n\\nWhen DST ends (the “end” line), there’s a potentially worse problem: there’s an hour that can’t be spelled unambiguously in local wall time: the last hour of daylight time. In Eastern, that’s times of the form 5:MM UTC on the day daylight time ends. The local wall clock leaps from 1:59 (daylight time) back to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous. astimezone() mimics the local clock’s behavior by mapping two adjacent UTC hours into the same local hour then. In the Eastern example, UTC times of the form 5:MM and 6:MM both map to 1:MM when converted to Eastern, but earlier times have the fold attribute set to 0 and the later times have it set to 1. For example, at the Fall back transition of 2016, we get:\\n\\n>>> import datetime as dt\\n>>> from tzinfo_examples import HOUR, Eastern\\n>>> u0 = dt.datetime(2016, 11, 6, 4, tzinfo=dt.timezone.utc)\\n>>> for i in range(4):\\n... u = u0 + i*HOUR\\n... t = u.astimezone(Eastern)\\n... print(u.time(), \\'UTC =\\', t.time(), t.tzname(), t.fold)\\n...\\n04:00:00 UTC = 00:00:00 EDT 0\\n05:00:00 UTC = 01:00:00 EDT 0\\n06:00:00 UTC = 01:00:00 EST 1\\n07:00:00 UTC = 02:00:00 EST 0\\n\\nNote that the datetime instances that differ only by the value of the fold attribute are considered equal in comparisons.\\n\\nApplications that can’t bear wall-time ambiguities should explicitly check the value of the fold attribute or avoid using hybrid tzinfo subclasses; there are no ambiguities when using timezone, or any other fixed-offset tzinfo subclass (such as a class representing only EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).\\n\\nSee also\\n\\ntimezone objects¶\\n\\nThe timezone class is a subclass of tzinfo, each instance of which represents a time zone defined by a fixed offset from UTC.\\n\\nObjects of this class cannot be used to represent time zone information in the locations where different offsets are used in different days of the year or where historical changes have been made to civil time.\\n\\nClass attributes:\\n\\nstrftime() and strptime() behavior¶\\n\\ndate, datetime, and time objects all support a strftime(format) method, to create a string representing the time under the control of an explicit format string.\\n\\nConversely, the date.strptime(), datetime.strptime() and time.strptime() class methods create an object from a string representing the time and a corresponding format string.\\n\\nThe table below provides a high-level comparison of strftime() versus strptime():\\n\\nstrftime strptime Usage Convert object to a string according to a given format Parse a string into an object given a corresponding format Type of method Instance method Class method Signature strftime(format) strptime(date_string, format)\\n\\nstrftime() and strptime() format codes¶\\n\\nThese methods accept format codes that can be used to parse and format dates:\\n\\n>>> import datetime as dt\\n>>> dt.datetime.strptime(\\'31/01/22 23:59:59.999999\\',\\n... \\'%d/%m/%y %H:%M:%S.%f\\')\\ndatetime.datetime(2022, 1, 31, 23, 59, 59, 999999)\\n>>> _.strftime(\\'%a %d %b %Y, %I:%M%p\\')\\n\\'Mon 31 Jan 2022, 11:59PM\\'\\n\\nThe following is a list of all the format codes that the 2011 C standard requires, and these work on all supported platforms.\\n\\nDirective Meaning Example Notes %a Weekday as locale’s\\nabbreviated name. Sun, Mon, …, Sat\\n(en_US); So, Mo, …, Sa\\n(de_DE) (1) %A Weekday as locale’s full name. Sunday, Monday, …,\\nSaturday (en_US); Sonntag, Montag, …,\\nSamstag (de_DE) (1) %b Month as locale’s abbreviated\\nname. Jan, Feb, …, Dec\\n(en_US); Jan, Feb, …, Dez\\n(de_DE) (1) %B Month as locale’s full name. January, February,\\n…, December (en_US); Januar, Februar, …,\\nDezember (de_DE) (1) %c Locale’s appropriate date and\\ntime representation. Tue Aug 16 21:30:00\\n1988 (en_US); Di 16 Aug 21:30:00\\n1988 (de_DE) (1) %C The year divided by 100 and\\ntruncated to an integer as a\\nzero-padded decimal number. 01, 02, …, 99 (0) %d Day of the month as a\\nzero-padded decimal number. 01, 02, …, 31 (9) %D Equivalent to %m/%d/%y . 11/28/25 (9) %e The day of the month as a\\nspace-padded decimal number. ␣1, ␣2, …, 31 %F Equivalent to %Y-%m-%d ,\\nthe ISO 8601 format. 2025-10-11,\\n1001-12-30 %g Last 2 digits of ISO 8601 year\\nrepresenting the year that\\ncontains the greater part of\\nthe ISO week ( %V ). 00, 01, …, 99 (0) %G ISO 8601 year with century\\nrepresenting the year that\\ncontains the greater part of\\nthe ISO week ( %V ). 0001, 0002, …, 2013,\\n2014, …, 9998, 9999 (8) %h Equivalent to %b . See %b . (0) %H Hour (24-hour clock) as a\\nzero-padded decimal number. 00, 01, …, 23 (9) %I Hour (12-hour clock) as a\\nzero-padded decimal number. 01, 02, …, 12 (9) %j Day of the year as a\\nzero-padded decimal number. 001, 002, …, 366 (9) %m Month as a zero-padded\\ndecimal number. 01, 02, …, 12 (9) %M Minute as a zero-padded\\ndecimal number. 00, 01, …, 59 (9) %n The newline character\\n( \\'\\\\n\\' ). \\\\n (0) %p Locale’s equivalent of either\\nAM or PM. AM, PM (en_US); am, pm (de_DE) (1),\\n(3) %r Locale’s 12-hour clock time. 12:00:00 AM (1),\\n(0) %R Equivalent to %H:%M . 10:01 %S Second as a zero-padded\\ndecimal number. 00, 01, …, 59 (4),\\n(9) %t The tab character\\n( \\'\\\\t\\' ). \\\\t (0) %T ISO 8601 time format,\\nequivalent to %H:%M:%S . 10:01:59 %u ISO 8601 weekday as a decimal\\nnumber where 1 is Monday. 1, 2, …, 7 %U Week number of the year\\n(Sunday as the first day of\\nthe week) as a zero-padded\\ndecimal number. All days in a\\nnew year preceding the first\\nSunday are considered to be in\\nweek 0. 00, 01, …, 53 (7),\\n(9) %V ISO 8601 week as a decimal\\nnumber with Monday as\\nthe first day of the week.\\nWeek 01 is the week containing\\nJan 4. 01, 02, …, 53 (8),\\n(9) %w Weekday as a decimal number,\\nwhere 0 is Sunday and 6 is\\nSaturday. 0, 1, …, 6 %W Week number of the year\\n(Monday as the first day of\\nthe week) as a zero-padded\\ndecimal number. All days in a\\nnew year preceding the first\\nMonday are considered to be in\\nweek 0. 00, 01, …, 53 (7),\\n(9) %x Locale’s appropriate date\\nrepresentation. 08/16/88 (None); 08/16/1988 (en_US); 16.08.1988 (de_DE) (1) %X Locale’s appropriate time\\nrepresentation. 21:30:00 (en_US); 21:30:00 (de_DE) (1) %y Year without century as a\\nzero-padded decimal number. 00, 01, …, 99 (9) %Y Year with century as a decimal\\nnumber. 0001, 0002, …, 2013,\\n2014, …, 9998, 9999 (2) %z UTC offset in the form ±HHMM[SS[.ffffff]] (empty\\nstring if the object is\\nnaive). (empty), +0000,\\n-0400, +1030,\\n+063415,\\n-030712.345216 (6) %Z Time zone name (empty string\\nif the object is naive). (empty), UTC, GMT (6) %% A literal \\'%\\' character. %\\n\\nThe ISO 8601 year and ISO 8601 week directives are not interchangeable with the year and week number directives above. Calling strptime() with incomplete or ambiguous ISO 8601 directives will raise a ValueError.\\n\\nSeveral additional directives not required by the C11 standard are included for convenience.\\n\\nDirective Meaning Example Notes %f Microsecond as a decimal\\nnumber, zero-padded to 6\\ndigits. 000000, 000001, …,\\n999999 (5) %:z UTC offset in the form ±HH:MM[:SS[.ffffff]] (empty string if the object is\\nnaive). (empty), +00:00,\\n-04:00, +10:30,\\n+06:34:15,\\n-03:07:12.345216 (6)\\n\\nThe full set of format codes supported varies across platforms, because Python calls the platform C library’s strftime() function, and platform variations are common. To see the full set of format codes supported on your platform, consult the strftime(3) documentation. There are also differences between platforms in handling of unsupported format specifiers.\\n\\nAdded in version 3.6: %G, %u and %V were added.\\n\\nAdded in version 3.12: %:z was added for strftime().\\n\\nAdded in version 3.15: %:z, %F, and %D were added for strptime().\\n\\nTechnical detail¶\\n\\nBroadly speaking, d.strftime(fmt) acts like the time module’s time.strftime(fmt, d.timetuple()) although not all objects support a timetuple() method.\\n\\nFor the datetime.strptime() and date.strptime() class methods, the default value is 1900-01-01T00:00:00.000: any components not specified in the format string will be pulled from the default value.\\n\\nNote\\n\\nFormat strings without separators can be ambiguous for parsing. For example, with %Y%m%d, the string 2026111 may be parsed either as 2026-11-01 or as 2026-01-11. Use separators to ensure the input is parsed as intended.\\n\\nNote\\n\\nWhen used to parse partial dates lacking a year, datetime.strptime() and 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.\\n\\n>>> import datetime as dt\\n>>> value = \"2/29\"\\n>>> dt.datetime.strptime(value, \"%m/%d\")\\nTraceback (most recent call last):\\n...\\nValueError: day 29 must be in range 1..28 for month 2 in year 1900\\n>>> dt.datetime.strptime(f\"1904 {value}\", \"%Y %m/%d\")\\ndatetime.datetime(1904, 2, 29, 0, 0)\\n\\nUsing datetime.strptime(date_string, format) is equivalent to:\\n\\ndatetime(*(time.strptime(date_string, format)[0:6]))\\n\\nexcept when the format includes sub-second components or time zone offset information, which are supported in datetime.strptime but are discarded by time.strptime.\\n\\nFor time objects, the format codes for year, month, and day should not be used, as time objects have no such values. If they’re used anyway, 1900 is substituted for the year, and 1 for the month and day.\\n\\nFor date objects, the format codes for hours, minutes, seconds, and microseconds should not be used, as date objects have no such values. If they’re used anyway, 0 is substituted for them.\\n\\nFor the same reason, handling of format strings containing Unicode code points that can’t be represented in the charset of the current locale is also platform-dependent. On some platforms such code points are preserved intact in the output, while on others strftime may raise UnicodeError or return an empty string instead.\\n\\nNotes:\\n\\nThis format code is currently unsupported by strptime().\\n\\nBecause 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.\\n\\nThe strptime() method can parse years in the full [1, 9999] range, but years < 1000 must be zero-filled to 4-digit width.\\n\\nChanged in version 3.2: In previous versions, strftime() method was restricted to years >= 1900.\\n\\nChanged in version 3.3: In version 3.2, strftime() method was restricted to years >= 1000.\\n\\nWhen used with the strptime() method, the %p directive only affects the output hour field if the %I directive is used to parse the hour.\\n\\nUnlike the time module, the datetime module does not support leap seconds.\\n\\nWhen used with the strptime() method, the %f directive accepts from one to six digits and zero pads on the right. %f is an extension to the set of format characters in the C standard (but implemented separately in datetime objects, and therefore always available).\\n\\nFor a naive object, the %z, %:z and %Z format codes are replaced by empty strings.\\n\\nFor an aware object:\\n\\nChanged in version 3.7: The UTC offset is not restricted to a whole number of minutes.\\n\\nChanged in version 3.7: When the %z directive is provided to the strptime() method, the UTC offsets can have a colon as a separator between hours, minutes and seconds. For example, both \\'+010000\\' and \\'+01:00:00\\' will be parsed as an offset of one hour. In addition, providing \\'Z\\' is identical to \\'+00:00\\'.\\n\\nChanged in version 3.2: When the %z directive is provided to the strptime() method, an aware datetime object will be produced. The tzinfo of the result will be set to a timezone instance.\\n\\nWhen used with the strptime() method, %U and %W are only used in calculations when the day of the week and the calendar year (%Y) are specified.\\n\\nSimilar to %U and %W, %V is only used in calculations when the day of the week and the ISO year (%G) are specified in a strptime() format string. Also note that %G and %Y are not interchangeable.\\n\\nWhen used with the strptime() method, the leading zero is optional for formats %d, %m, %H, %I, %M, %S, %j, %U, %W, and %V. Format %y does require a leading zero.\\n\\nWhen parsing a month and day using 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.\\n\\n>>> month_day = \"02/29\"\\n>>> dt.datetime.strptime(f\"{month_day};1984\", \"%m/%d;%Y\") # No leap year bug.\\ndatetime.datetime(1984, 2, 29, 0, 0)\\n\\nDeprecated since version 3.13, removed in version 3.15: strptime() calls using a format string containing a day of month without a year now emit a 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.\\n\\nFootnotes\\n\\n[1]\\n\\nIf, that is, we ignore the effects of relativity.\\n\\n[2]\\n\\nThis matches the definition of the “proleptic Gregorian” calendar in Dershowitz and Reingold’s book Calendrical Calculations, where it’s the base calendar for all computations. See the book for algorithms for converting between proleptic Gregorian ordinals and many other calendar systems.\\n\\n[3]\\n\\nSee R. H. van Gent’s guide to the mathematics of the ISO 8601 calendar for a good explanation.\\n\\nTable of Contents\\n\\ndatetime — Basic date and time types\\n\\nAware and naive objects\\n\\nConstants\\n\\nAvailable types\\n\\nCommon properties\\n\\nDetermining if an object is aware or naive\\n\\ntimedelta objects\\n\\nExamples of usage: timedelta\\n\\ndate objects\\n\\nExamples of usage: date\\n\\ndatetime objects\\n\\nExamples of usage: datetime\\n\\ntime objects\\n\\nExamples of usage: time\\n\\ntzinfo objects\\n\\ntimezone objects\\n\\nstrftime() and strptime() behavior\\n\\nstrftime() and strptime() format codes\\n\\nTechnical detail\\n\\nPrevious topic\\n\\nData Types\\n\\nNext topic\\n\\nzoneinfo — IANA time zone support\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Types »\\n\\ndatetime — Basic date and time types\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\dbm.html'}, page_content=\"Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Persistence »\\n\\ndbm — Interfaces to Unix “databases”\\n\\n|\\n\\ndbm — Interfaces to Unix “databases”¶\\n\\nSource code: Lib/dbm/__init__.py\\n\\ndbm is a generic interface to variants of the DBM database:\\n\\ndbm.sqlite3\\n\\ndbm.gnu\\n\\ndbm.ndbm\\n\\nIf none of these modules are installed, the slow-but-simple implementation in module dbm.dumb will be used. There is a third party interface to the Oracle Berkeley DB.\\n\\nNote\\n\\nNone of the underlying modules will automatically shrink the disk space used by the database file. However, dbm.sqlite3, dbm.gnu and dbm.dumb provide a reorganize() method that can be used for this purpose.\\n\\nThe object returned by open() supports the basic functionality of mutable mappings; keys and their corresponding values can be stored, retrieved, and deleted, and iteration, the in operator and methods keys(), get(), setdefault() and clear() are available. The keys() method returns a list instead of a view object. The setdefault() method requires two arguments.\\n\\nKey and values are always stored as bytes. This means that when strings are used they are implicitly converted to the default encoding before being stored.\\n\\nThese objects also support being used in a with statement, which will automatically close them when done.\\n\\nChanged in version 3.2: get() and setdefault() methods are now available for all dbm backends.\\n\\nChanged in version 3.4: Added native support for the context management protocol to the objects returned by open().\\n\\nChanged in version 3.8: Deleting a key from a read-only database raises a database module specific exception instead of KeyError.\\n\\nChanged in version 3.13: clear() methods are now available for all dbm backends.\\n\\nThe following example records some hostnames and a corresponding title, and then prints out the contents of the database:\\n\\nimport dbm\\n\\n# Open database, creating it if necessary.\\nwith dbm.open('cache', 'c') as db:\\n\\n # Record some values\\n db[b'hello'] = b'there'\\n db['www.python.org'] = 'Python Website'\\n db['www.cnn.com'] = 'Cable News Network'\\n\\n # Note that the keys are considered bytes now.\\n assert db[b'www.python.org'] == b'Python Website'\\n # Notice how the value is now in bytes.\\n assert db['www.cnn.com'] == b'Cable News Network'\\n\\n # Often-used methods of the dict interface work too.\\n print(db.get('python.org', b'not present'))\\n\\n # Storing a non-string key or value will raise an exception (most\\n # likely a TypeError).\\n db['www.yahoo.com'] = 4\\n\\n# db is automatically closed when leaving the with statement.\\n\\nSee also\\n\\nThe individual submodules are described in the following sections.\\n\\ndbm.sqlite3 — SQLite backend for dbm¶\\n\\nAdded in version 3.13.\\n\\nSource code: Lib/dbm/sqlite3.py\\n\\nThis module uses the standard library sqlite3 module to provide an SQLite backend for the dbm module. The files created by dbm.sqlite3 can thus be opened by sqlite3, or any other SQLite browser, including the SQLite CLI.\\n\\nAvailability: not WASI.\\n\\nThis module does not work or is not available on WebAssembly. See WebAssembly platforms for more information.\\n\\ndbm.gnu — GNU database manager¶\\n\\nSource code: Lib/dbm/gnu.py\\n\\nThe dbm.gnu module provides an interface to the GDBM library, similar to the dbm.ndbm module, but with additional functionality like crash tolerance.\\n\\nNote\\n\\nThe file formats created by dbm.gnu and dbm.ndbm are incompatible and can not be used interchangeably.\\n\\nAvailability: not Android, not iOS, not WASI.\\n\\nThis module is not supported on mobile platforms or WebAssembly platforms.\\n\\nAvailability: Unix.\\n\\ndbm.ndbm — New Database Manager¶\\n\\nSource code: Lib/dbm/ndbm.py\\n\\nThe dbm.ndbm module provides an interface to the NDBM library. This module can be used with the “classic” NDBM interface or the GDBM compatibility interface.\\n\\nNote\\n\\nThe file formats created by dbm.gnu and dbm.ndbm are incompatible and can not be used interchangeably.\\n\\nWarning\\n\\nThe 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).\\n\\nAvailability: not Android, not iOS, not WASI.\\n\\nThis module is not supported on mobile platforms or WebAssembly platforms.\\n\\nAvailability: Unix.\\n\\ndbm.dumb — Portable DBM implementation¶\\n\\nSource code: Lib/dbm/dumb.py\\n\\nNote\\n\\nThe dbm.dumb module is intended as a last resort fallback for the dbm module when a more robust module is not available. The dbm.dumb module is not written for speed and is not nearly as heavily used as the other database modules.\\n\\nThe dbm.dumb module provides a persistent dict-like interface which is written entirely in Python. Unlike other dbm backends, such as dbm.gnu, no external library is required.\\n\\nThe dbm.dumb module defines the following:\\n\\nTable of Contents\\n\\ndbm — Interfaces to Unix “databases”\\n\\ndbm.sqlite3 — SQLite backend for dbm\\n\\ndbm.gnu — GNU database manager\\n\\ndbm.ndbm — New Database Manager\\n\\ndbm.dumb — Portable DBM implementation\\n\\nPrevious topic\\n\\nmarshal — Internal Python object serialization\\n\\nNext topic\\n\\nsqlite3 — DB-API 2.0 interface for SQLite databases\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Persistence »\\n\\ndbm — Interfaces to Unix “databases”\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.\"), Document(metadata={'source': '..\\\\..\\\\docs\\\\debug.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nDebugging and profiling\\n\\n|\\n\\nDebugging and profiling¶\\n\\nThese libraries help you with Python development: the debugger enables you to step through code, analyze stack frames and set breakpoints etc., and the profilers run code and give you a detailed breakdown of execution times, allowing you to identify bottlenecks in your programs. Auditing events provide visibility into runtime behaviors that would otherwise require intrusive debugging or patching.\\n\\nAudit events table\\n\\nbdb — Debugger framework\\n\\nfaulthandler — Dump the Python traceback\\n\\nDumping the traceback\\n\\nDumping the C stack\\n\\nC Stack Compatibility\\n\\nFault handler state\\n\\nDumping the tracebacks after a timeout\\n\\nDumping the traceback on a user signal\\n\\nIssue with file descriptors\\n\\nExample\\n\\npdb — The Python Debugger\\n\\nCommand-line interface\\n\\nDebugger commands\\n\\nprofiling — Python profilers\\n\\nIntroduction to profiling\\n\\nChoosing a profiler\\n\\nWhen to use statistical sampling\\n\\nWhen to use deterministic tracing\\n\\nQuick start\\n\\nStatistical profiling\\n\\nDeterministic profiling\\n\\nUnderstanding profile output\\n\\nLegacy compatibility\\n\\nprofiling.tracing — Deterministic profiler\\n\\nWhat is deterministic profiling?\\n\\nCommand-line interface\\n\\nProgrammatic usage examples\\n\\nBasic profiling\\n\\nUsing the Profile class\\n\\nModule reference\\n\\nUsing a custom timer\\n\\nLimitations\\n\\nprofiling.sampling — Statistical profiler\\n\\nWhat is statistical profiling?\\n\\nHow time is estimated\\n\\nWhen to use a different approach\\n\\nQuick examples\\n\\nCommands\\n\\nThe run command\\n\\nThe attach command\\n\\nThe replay command\\n\\nProfiling in production\\n\\nPlatform requirements\\n\\nVersion compatibility\\n\\nSampling configuration\\n\\nSampling rate and duration\\n\\nThread selection\\n\\nBlocking mode\\n\\nSpecial frames\\n\\nOpcode-aware profiling\\n\\nReal-time statistics\\n\\nSubprocess profiling\\n\\nSampling efficiency\\n\\nProfiling modes\\n\\nWall-clock mode\\n\\nCPU mode\\n\\nComparing wall-clock and CPU profiles\\n\\nGIL mode\\n\\nException mode\\n\\nOutput formats\\n\\npstats format\\n\\nCollapsed stacks format\\n\\nFlame graph format\\n\\nGecko format\\n\\nHeatmap format\\n\\nBinary format\\n\\nRecord and replay workflow\\n\\nLive mode\\n\\nKeyboard commands\\n\\nAsync-aware profiling\\n\\nAsync modes\\n\\nTask markers and stack reconstruction\\n\\nOption restrictions\\n\\nCommand-line interface\\n\\nGlobal options\\n\\nSampling options\\n\\nMode options\\n\\nOutput options\\n\\npstats display options\\n\\nRun command options\\n\\npstats — Statistics for profilers\\n\\nReading and displaying profile data\\n\\nWorking with statistics\\n\\nFiltering output\\n\\nAnalyzing call relationships\\n\\nCombining multiple profiles\\n\\nThe Stats class\\n\\nCommand-line interface\\n\\ntimeit — Measure execution time of small code snippets\\n\\nBasic Examples\\n\\nPython Interface\\n\\nCommand-Line Interface\\n\\nExamples\\n\\ntrace — Trace or track Python statement execution\\n\\nCommand-Line Usage\\n\\nMain options\\n\\nModifiers\\n\\nFilters\\n\\nProgrammatic Interface\\n\\ntracemalloc — Trace memory allocations\\n\\nExamples\\n\\nDisplay the top 10\\n\\nCompute differences\\n\\nGet the traceback of a memory block\\n\\nPretty top\\n\\nRecord the current and peak size of all traced memory blocks\\n\\nAPI\\n\\nFunctions\\n\\nDomainFilter\\n\\nFilter\\n\\nFrame\\n\\nSnapshot\\n\\nStatistic\\n\\nStatisticDiff\\n\\nTrace\\n\\nTraceback\\n\\nPrevious topic\\n\\ntest — Regression tests package for Python\\n\\nNext topic\\n\\nAudit events table\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nDebugging and profiling\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\decimal.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNumeric and Mathematical Modules »\\n\\ndecimal — Decimal fixed-point and floating-point arithmetic\\n\\n|\\n\\ndecimal — Decimal fixed-point and floating-point arithmetic¶\\n\\nSource code: Lib/decimal.py\\n\\nThe decimal module provides support for fast correctly rounded decimal floating-point arithmetic. It offers several advantages over the float datatype:\\n\\nDecimal “is based on a floating-point model 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.\\n\\nDecimal numbers can be represented exactly. In contrast, numbers like 1.1 and 2.2 do not have exact representations in binary floating point. End users typically would not expect 1.1 + 2.2 to display as 3.3000000000000003 as it does with binary floating point.\\n\\nThe exactness carries over into arithmetic. In decimal floating point, 0.1 + 0.1 + 0.1 - 0.3 is exactly equal to zero. In binary floating point, the result is 5.5511151231257827e-017. While near to zero, the differences prevent reliable equality testing and differences can accumulate. For this reason, decimal is preferred in accounting applications which have strict equality invariants.\\n\\nThe decimal module incorporates a notion of significant places so that 1.30 + 1.20 is 2.50. The trailing zero is kept to indicate significance. This is the customary presentation for monetary applications. For multiplication, the “schoolbook” approach uses all the figures in the multiplicands. For instance, 1.3 * 1.2 gives 1.56 while 1.30 * 1.20 gives 1.5600.\\n\\nUnlike hardware based binary floating point, the decimal module has a user alterable precision (defaulting to 28 places) which can be as large as needed for a given problem:\\n\\n>>> from decimal import *\\n>>> getcontext().prec = 6\\n>>> Decimal(1) / Decimal(7)\\nDecimal(\\'0.142857\\')\\n>>> getcontext().prec = 28\\n>>> Decimal(1) / Decimal(7)\\nDecimal(\\'0.1428571428571428571428571429\\')\\n\\nBoth binary and decimal floating point are implemented in terms of published standards. While the built-in float type exposes only a modest portion of its capabilities, the decimal module exposes all required parts of the standard. When needed, the programmer has full control over rounding and signal handling. This includes an option to enforce exact arithmetic by using exceptions to block any inexact operations.\\n\\nThe decimal module was designed to support “without prejudice, both exact unrounded decimal arithmetic (sometimes called fixed-point arithmetic) and rounded floating-point arithmetic.” – excerpt from the decimal arithmetic specification.\\n\\nThe module design is centered around three concepts: the decimal number, the context for arithmetic, and signals.\\n\\nA decimal number is immutable. It has a sign, coefficient digits, and an exponent. To preserve significance, the coefficient digits do not truncate trailing zeros. Decimals also include special values such as Infinity, -Infinity, and NaN. The standard also differentiates -0 from +0.\\n\\nThe context for arithmetic is an environment specifying precision, rounding rules, limits on exponents, flags indicating the results of operations, and trap enablers which determine whether signals are treated as exceptions. Rounding options include ROUND_CEILING, ROUND_DOWN, ROUND_FLOOR, ROUND_HALF_DOWN, ROUND_HALF_EVEN, ROUND_HALF_UP, ROUND_UP, and ROUND_05UP.\\n\\nSignals are groups of exceptional conditions arising during the course of computation. Depending on the needs of the application, signals may be ignored, considered as informational, or treated as exceptions. The signals in the decimal module are: Clamped, InvalidOperation, DivisionByZero, Inexact, Rounded, Subnormal, Overflow, Underflow and FloatOperation.\\n\\nFor each signal there is a flag and a trap enabler. When a signal is encountered, its flag is set to one, then, if the trap enabler is set to one, an exception is raised. Flags are sticky, so the user needs to reset them before monitoring a calculation.\\n\\nSee also\\n\\nIBM’s General Decimal Arithmetic Specification, The General Decimal Arithmetic Specification.\\n\\nQuick-start tutorial¶\\n\\nThe usual start to using decimals is importing the module, viewing the current context with getcontext() and, if necessary, setting new values for precision, rounding, or enabled traps:\\n\\n>>> from decimal import *\\n>>> getcontext()\\nContext(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,\\n capitals=1, clamp=0, flags=[], traps=[Overflow, DivisionByZero,\\n InvalidOperation])\\n\\n>>> getcontext().prec = 7 # Set a new precision\\n\\nDecimal instances can be constructed from integers, strings, floats, or tuples. Construction from an integer or a float performs an exact conversion of the value of that integer or float. Decimal numbers include special values such as NaN which stands for “Not a number”, positive and negative Infinity, and -0:\\n\\n>>> getcontext().prec = 28\\n>>> Decimal(10)\\nDecimal(\\'10\\')\\n>>> Decimal(\\'3.14\\')\\nDecimal(\\'3.14\\')\\n>>> Decimal(3.14)\\nDecimal(\\'3.140000000000000124344978758017532527446746826171875\\')\\n>>> Decimal((0, (3, 1, 4), -2))\\nDecimal(\\'3.14\\')\\n>>> Decimal(str(2.0 ** 0.5))\\nDecimal(\\'1.4142135623730951\\')\\n>>> Decimal(2) ** Decimal(\\'0.5\\')\\nDecimal(\\'1.414213562373095048801688724\\')\\n>>> Decimal(\\'NaN\\')\\nDecimal(\\'NaN\\')\\n>>> Decimal(\\'-Infinity\\')\\nDecimal(\\'-Infinity\\')\\n\\nIf the FloatOperation signal is trapped, accidental mixing of decimals and floats in constructors or ordering comparisons raises an exception:\\n\\n>>> c = getcontext()\\n>>> c.traps[FloatOperation] = True\\n>>> Decimal(3.14)\\nTraceback (most recent call last):\\n File \"\", line 1, in \\ndecimal.FloatOperation: []\\n>>> Decimal(\\'3.5\\') < 3.7\\nTraceback (most recent call last):\\n File \"\", line 1, in \\ndecimal.FloatOperation: []\\n>>> Decimal(\\'3.5\\') == 3.5\\nTrue\\n\\nAdded in version 3.3.\\n\\nThe significance of a new Decimal is determined solely by the number of digits input. Context precision and rounding only come into play during arithmetic operations.\\n\\n>>> getcontext().prec = 6\\n>>> Decimal(\\'3.0\\')\\nDecimal(\\'3.0\\')\\n>>> Decimal(\\'3.1415926535\\')\\nDecimal(\\'3.1415926535\\')\\n>>> Decimal(\\'3.1415926535\\') + Decimal(\\'2.7182818285\\')\\nDecimal(\\'5.85987\\')\\n>>> getcontext().rounding = ROUND_UP\\n>>> Decimal(\\'3.1415926535\\') + Decimal(\\'2.7182818285\\')\\nDecimal(\\'5.85988\\')\\n\\nIf the internal limits of the C version are exceeded, constructing a decimal raises InvalidOperation:\\n\\n>>> Decimal(\"1e9999999999999999999\")\\nTraceback (most recent call last):\\n File \"\", line 1, in \\ndecimal.InvalidOperation: []\\n\\nChanged in version 3.3.\\n\\nDecimals interact well with much of the rest of Python. Here is a small decimal floating-point flying circus:\\n\\n>>> data = list(map(Decimal, \\'1.34 1.87 3.45 2.35 1.00 0.03 9.25\\'.split()))\\n>>> max(data)\\nDecimal(\\'9.25\\')\\n>>> min(data)\\nDecimal(\\'0.03\\')\\n>>> sorted(data)\\n[Decimal(\\'0.03\\'), Decimal(\\'1.00\\'), Decimal(\\'1.34\\'), Decimal(\\'1.87\\'),\\n Decimal(\\'2.35\\'), Decimal(\\'3.45\\'), Decimal(\\'9.25\\')]\\n>>> sum(data)\\nDecimal(\\'19.29\\')\\n>>> a,b,c = data[:3]\\n>>> str(a)\\n\\'1.34\\'\\n>>> float(a)\\n1.34\\n>>> round(a, 1)\\nDecimal(\\'1.3\\')\\n>>> int(a)\\n1\\n>>> a * 5\\nDecimal(\\'6.70\\')\\n>>> a * b\\nDecimal(\\'2.5058\\')\\n>>> c % a\\nDecimal(\\'0.77\\')\\n\\nDecimals can be formatted (with format() built-in or f-strings) in fixed-point or scientific notation, using the same formatting syntax (see Format Specification Mini-Language) as builtin float type:\\n\\n>>> format(Decimal(\\'2.675\\'), \"f\")\\n\\'2.675\\'\\n>>> format(Decimal(\\'2.675\\'), \".2f\")\\n\\'2.68\\'\\n>>> f\"{Decimal(\\'2.675\\'):.2f}\"\\n\\'2.68\\'\\n>>> format(Decimal(\\'2.675\\'), \".2e\")\\n\\'2.68e+0\\'\\n>>> with localcontext() as ctx:\\n... ctx.rounding = ROUND_DOWN\\n... print(format(Decimal(\\'2.675\\'), \".2f\"))\\n...\\n2.67\\n\\nAnd some mathematical functions are also available to Decimal:\\n\\n>>> getcontext().prec = 28\\n>>> Decimal(2).sqrt()\\nDecimal(\\'1.414213562373095048801688724\\')\\n>>> Decimal(1).exp()\\nDecimal(\\'2.718281828459045235360287471\\')\\n>>> Decimal(\\'10\\').ln()\\nDecimal(\\'2.302585092994045684017991455\\')\\n>>> Decimal(\\'10\\').log10()\\nDecimal(\\'1\\')\\n\\nThe quantize() method rounds a number to a fixed exponent. This method is useful for monetary applications that often round results to a fixed number of places:\\n\\n>>> Decimal(\\'7.325\\').quantize(Decimal(\\'.01\\'), rounding=ROUND_DOWN)\\nDecimal(\\'7.32\\')\\n>>> Decimal(\\'7.325\\').quantize(Decimal(\\'1.\\'), rounding=ROUND_UP)\\nDecimal(\\'8\\')\\n\\nAs shown above, the getcontext() function accesses the current context and allows the settings to be changed. This approach meets the needs of most applications.\\n\\nFor more advanced work, it may be useful to create alternate contexts using the Context() constructor. To make an alternate active, use the setcontext() function.\\n\\nIn accordance with the standard, the decimal module provides two ready to use standard contexts, BasicContext and ExtendedContext. The former is especially useful for debugging because many of the traps are enabled:\\n\\n>>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)\\n>>> setcontext(myothercontext)\\n>>> Decimal(1) / Decimal(7)\\nDecimal(\\'0.142857142857142857142857142857142857142857142857142857142857\\')\\n\\n>>> ExtendedContext\\nContext(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,\\n capitals=1, clamp=0, flags=[], traps=[])\\n>>> setcontext(ExtendedContext)\\n>>> Decimal(1) / Decimal(7)\\nDecimal(\\'0.142857143\\')\\n>>> Decimal(42) / Decimal(0)\\nDecimal(\\'Infinity\\')\\n\\n>>> setcontext(BasicContext)\\n>>> Decimal(42) / Decimal(0)\\nTraceback (most recent call last):\\n File \"\", line 1, in -toplevel-\\n Decimal(42) / Decimal(0)\\nDivisionByZero: x / 0\\n\\nContexts also have signal flags for monitoring exceptional conditions encountered during computations. The flags remain set until explicitly cleared, so it is best to clear the flags before each set of monitored computations by using the clear_flags() method.\\n\\n>>> setcontext(ExtendedContext)\\n>>> getcontext().clear_flags()\\n>>> Decimal(355) / Decimal(113)\\nDecimal(\\'3.14159292\\')\\n>>> getcontext()\\nContext(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,\\n capitals=1, clamp=0, flags=[Inexact, Rounded], traps=[])\\n\\nThe flags entry shows that the rational approximation to pi was rounded (digits beyond the context precision were thrown away) and that the result is inexact (some of the discarded digits were non-zero).\\n\\nIndividual traps are set using the dictionary in the traps attribute of a context:\\n\\n>>> setcontext(ExtendedContext)\\n>>> Decimal(1) / Decimal(0)\\nDecimal(\\'Infinity\\')\\n>>> getcontext().traps[DivisionByZero] = 1\\n>>> Decimal(1) / Decimal(0)\\nTraceback (most recent call last):\\n File \"\", line 1, in -toplevel-\\n Decimal(1) / Decimal(0)\\nDivisionByZero: x / 0\\n\\nMost programs adjust the current context only once, at the beginning of the program. And, in many applications, data is converted to Decimal with a single cast inside a loop. With context set and decimals created, the bulk of the program manipulates the data no differently than with other Python numeric types.\\n\\nDecimal objects¶\\n\\nLogical operands¶\\n\\nThe logical_and(), logical_invert(), logical_or(), and logical_xor() methods expect their arguments to be logical operands. A logical operand is a Decimal instance whose exponent and sign are both zero, and whose digits are all either 0 or 1.\\n\\nContext objects¶\\n\\nContexts are environments for arithmetic operations. They govern precision, set rules for rounding, determine which signals are treated as exceptions, and limit the range for exponents.\\n\\nEach thread has its own current context which is accessed or changed using the getcontext() and setcontext() functions:\\n\\nYou can also use the with statement and the localcontext() function to temporarily change the active context.\\n\\nNew contexts can also be created using the Context constructor described below. In addition, the module provides three pre-made contexts:\\n\\nIn addition to the three supplied contexts, new contexts can be created with the Context constructor.\\n\\nConstants¶\\n\\nThe following constants are only relevant for the C module. They are also included in the pure Python version for compatibility.\\n\\n32-bit 64-bit decimal. MAX_PREC ¶ 425000000 999999999999999999 decimal. MAX_EMAX ¶ 425000000 999999999999999999 decimal. MIN_EMIN ¶ -425000000 -999999999999999999 decimal. MIN_ETINY ¶ -849999999 -1999999999999999997 decimal. IEEE_CONTEXT_MAX_BITS ¶ 256 512\\n\\nRounding modes¶\\n\\nSignals¶\\n\\nSignals represent conditions that arise during computation. Each corresponds to one context flag and one context trap enabler.\\n\\nThe context flag is set whenever the condition is encountered. After the computation, flags may be checked for informational purposes (for instance, to determine whether a computation was exact). After checking the flags, be sure to clear all flags before starting the next computation.\\n\\nIf the context’s trap enabler is set for the signal, then the condition causes a Python exception to be raised. For example, if the DivisionByZero trap is set, then a DivisionByZero exception is raised upon encountering the condition.\\n\\nThe following table summarizes the hierarchy of signals:\\n\\nexceptions.ArithmeticError(exceptions.Exception)\\n DecimalException\\n Clamped\\n DivisionByZero(DecimalException, exceptions.ZeroDivisionError)\\n Inexact\\n Overflow(Inexact, Rounded)\\n Underflow(Inexact, Rounded, Subnormal)\\n InvalidOperation\\n Rounded\\n Subnormal\\n FloatOperation(DecimalException, exceptions.TypeError)\\n\\nFloating-point notes¶\\n\\nMitigating round-off error with increased precision¶\\n\\nThe use of decimal floating point eliminates decimal representation error (making it possible to represent 0.1 exactly); however, some operations can still incur round-off error when non-zero digits exceed the fixed precision.\\n\\nThe 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:\\n\\n# Examples from Seminumerical Algorithms, Section 4.2.2.\\n>>> from decimal import Decimal, getcontext\\n>>> getcontext().prec = 8\\n\\n>>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal(\\'7.51111111\\')\\n>>> (u + v) + w\\nDecimal(\\'9.5111111\\')\\n>>> u + (v + w)\\nDecimal(\\'10\\')\\n\\n>>> u, v, w = Decimal(20000), Decimal(-6), Decimal(\\'6.0000003\\')\\n>>> (u*v) + (u*w)\\nDecimal(\\'0.01\\')\\n>>> u * (v+w)\\nDecimal(\\'0.0060000\\')\\n\\nThe decimal module makes it possible to restore the identities by expanding the precision sufficiently to avoid loss of significance:\\n\\n>>> getcontext().prec = 20\\n>>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal(\\'7.51111111\\')\\n>>> (u + v) + w\\nDecimal(\\'9.51111111\\')\\n>>> u + (v + w)\\nDecimal(\\'9.51111111\\')\\n>>>\\n>>> u, v, w = Decimal(20000), Decimal(-6), Decimal(\\'6.0000003\\')\\n>>> (u*v) + (u*w)\\nDecimal(\\'0.0060000\\')\\n>>> u * (v+w)\\nDecimal(\\'0.0060000\\')\\n\\nSpecial values¶\\n\\nThe number system for the decimal module provides special values including NaN, sNaN, -Infinity, Infinity, and two zeros, +0 and -0.\\n\\nInfinities can be constructed directly with: Decimal(\\'Infinity\\'). Also, they can arise from dividing by zero when the DivisionByZero signal is not trapped. Likewise, when the Overflow signal is not trapped, infinity can result from rounding beyond the limits of the largest representable number.\\n\\nThe infinities are signed (affine) and can be used in arithmetic operations where they get treated as very large, indeterminate numbers. For instance, adding a constant to infinity gives another infinite result.\\n\\nSome operations are indeterminate and return NaN, or if the InvalidOperation signal is trapped, raise an exception. For example, 0/0 returns NaN which means “not a number”. This variety of NaN is quiet and, once created, will flow through other computations always resulting in another NaN. This behavior can be useful for a series of computations that occasionally have missing inputs — it allows the calculation to proceed while flagging specific results as invalid.\\n\\nA variant is sNaN which signals rather than remaining quiet after every operation. This is a useful return value when an invalid result needs to interrupt a calculation for special handling.\\n\\nThe behavior of Python’s comparison operators can be a little surprising where a NaN is involved. A test for equality where one of the operands is a quiet or signaling NaN always returns False (even when doing Decimal(\\'NaN\\')==Decimal(\\'NaN\\')), while a test for inequality always returns True. An attempt to compare two Decimals using any of the <, <=, > or >= operators will raise the InvalidOperation signal if either operand is a NaN, and return False if this signal is not trapped. Note that the General Decimal Arithmetic specification does not specify the behavior of direct comparisons; these rules for comparisons involving a NaN were taken from the IEEE 854 standard (see Table 3 in section 5.7). To ensure strict standards-compliance, use the compare() and compare_signal() methods instead.\\n\\nThe signed zeros can result from calculations that underflow. They keep the sign that would have resulted if the calculation had been carried out to greater precision. Since their magnitude is zero, both positive and negative zeros are treated as equal and their sign is informational.\\n\\nIn 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:\\n\\n>>> 1 / Decimal(\\'Infinity\\')\\nDecimal(\\'0E-1000026\\')\\n\\nWorking with threads¶\\n\\nThe getcontext() function accesses a different Context object for each thread. Having separate thread contexts means that threads may make changes (such as getcontext().prec=10) without interfering with other threads.\\n\\nLikewise, the setcontext() function automatically assigns its target to the current thread.\\n\\nIf setcontext() has not been called before getcontext(), then getcontext() will automatically create a new context for use in the current thread. New context objects have default values set from the decimal.DefaultContext object.\\n\\nThe 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, 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 threading.Thread.start().\\n\\nTo 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 getcontext(). For example:\\n\\n# Set applicationwide defaults for all threads about to be launched\\nDefaultContext.prec = 12\\nDefaultContext.rounding = ROUND_DOWN\\nDefaultContext.traps = ExtendedContext.traps.copy()\\nDefaultContext.traps[InvalidOperation] = 1\\nsetcontext(DefaultContext)\\n\\n# Afterwards, the threads can be started\\nt1.start()\\nt2.start()\\nt3.start()\\n . . .\\n\\nRecipes¶\\n\\nHere are a few recipes that serve as utility functions and that demonstrate ways to work with the Decimal class:\\n\\ndef moneyfmt(value, places=2, curr=\\'\\', sep=\\',\\', dp=\\'.\\',\\n pos=\\'\\', neg=\\'-\\', trailneg=\\'\\'):\\n \"\"\"Convert Decimal to a money formatted string.\\n\\n places: required number of places after the decimal point\\n curr: optional currency symbol before the sign (may be blank)\\n sep: optional grouping separator (comma, period, space, or blank)\\n dp: decimal point indicator (comma or period)\\n only specify as blank when places is zero\\n pos: optional sign for positive numbers: \\'+\\', space or blank\\n neg: optional sign for negative numbers: \\'-\\', \\'(\\', space or blank\\n trailneg:optional trailing minus indicator: \\'-\\', \\')\\', space or blank\\n\\n >>> d = Decimal(\\'-1234567.8901\\')\\n >>> moneyfmt(d, curr=\\'$\\')\\n \\'-$1,234,567.89\\'\\n >>> moneyfmt(d, places=0, sep=\\'.\\', dp=\\'\\', neg=\\'\\', trailneg=\\'-\\')\\n \\'1.234.568-\\'\\n >>> moneyfmt(d, curr=\\'$\\', neg=\\'(\\', trailneg=\\')\\')\\n \\'($1,234,567.89)\\'\\n >>> moneyfmt(Decimal(123456789), sep=\\' \\')\\n \\'123 456 789.00\\'\\n >>> moneyfmt(Decimal(\\'-0.02\\'), neg=\\'<\\', trailneg=\\'>\\')\\n \\'<0.02>\\'\\n\\n \"\"\"\\n q = Decimal(10) ** -places # 2 places --> \\'0.01\\'\\n sign, digits, exp = value.quantize(q).as_tuple()\\n result = []\\n digits = list(map(str, digits))\\n build, next = result.append, digits.pop\\n if sign:\\n build(trailneg)\\n for i in range(places):\\n build(next() if digits else \\'0\\')\\n if places:\\n build(dp)\\n if not digits:\\n build(\\'0\\')\\n i = 0\\n while digits:\\n build(next())\\n i += 1\\n if i == 3 and digits:\\n i = 0\\n build(sep)\\n build(curr)\\n build(neg if sign else pos)\\n return \\'\\'.join(reversed(result))\\n\\ndef pi():\\n \"\"\"Compute Pi to the current precision.\\n\\n >>> print(pi())\\n 3.141592653589793238462643383\\n\\n \"\"\"\\n getcontext().prec += 2 # extra digits for intermediate steps\\n three = Decimal(3) # substitute \"three=3.0\" for regular floats\\n lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24\\n while s != lasts:\\n lasts = s\\n n, na = n+na, na+8\\n d, da = d+da, da+32\\n t = (t * n) / d\\n s += t\\n getcontext().prec -= 2\\n return +s # unary plus applies the new precision\\n\\ndef exp(x):\\n \"\"\"Return e raised to the power of x. Result type matches input type.\\n\\n >>> print(exp(Decimal(1)))\\n 2.718281828459045235360287471\\n >>> print(exp(Decimal(2)))\\n 7.389056098930650227230427461\\n >>> print(exp(2.0))\\n 7.38905609893\\n >>> print(exp(2+0j))\\n (7.38905609893+0j)\\n\\n \"\"\"\\n getcontext().prec += 2\\n i, lasts, s, fact, num = 0, 0, 1, 1, 1\\n while s != lasts:\\n lasts = s\\n i += 1\\n fact *= i\\n num *= x\\n s += num / fact\\n getcontext().prec -= 2\\n return +s\\n\\ndef cos(x):\\n \"\"\"Return the cosine of x as measured in radians.\\n\\n The Taylor series approximation works best for a small value of x.\\n For larger values, first compute x = x % (2 * pi).\\n\\n >>> print(cos(Decimal(\\'0.5\\')))\\n 0.8775825618903727161162815826\\n >>> print(cos(0.5))\\n 0.87758256189\\n >>> print(cos(0.5+0j))\\n (0.87758256189+0j)\\n\\n \"\"\"\\n getcontext().prec += 2\\n i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1\\n while s != lasts:\\n lasts = s\\n i += 2\\n fact *= i * (i-1)\\n num *= x * x\\n sign *= -1\\n s += num / fact * sign\\n getcontext().prec -= 2\\n return +s\\n\\ndef sin(x):\\n \"\"\"Return the sine of x as measured in radians.\\n\\n The Taylor series approximation works best for a small value of x.\\n For larger values, first compute x = x % (2 * pi).\\n\\n >>> print(sin(Decimal(\\'0.5\\')))\\n 0.4794255386042030002732879352\\n >>> print(sin(0.5))\\n 0.479425538604\\n >>> print(sin(0.5+0j))\\n (0.479425538604+0j)\\n\\n \"\"\"\\n getcontext().prec += 2\\n i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1\\n while s != lasts:\\n lasts = s\\n i += 2\\n fact *= i * (i-1)\\n num *= x * x\\n sign *= -1\\n s += num / fact * sign\\n getcontext().prec -= 2\\n return +s\\n\\nDecimal FAQ¶\\n\\nQ: It is cumbersome to type decimal.Decimal(\\'1234.5\\'). Is there a way to minimize typing when using the interactive interpreter?\\n\\nA: Some users abbreviate the constructor to just a single letter:\\n\\n>>> D = decimal.Decimal\\n>>> D(\\'1.23\\') + D(\\'3.45\\')\\nDecimal(\\'4.68\\')\\n\\nQ: 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?\\n\\nA: The quantize() method rounds to a fixed number of decimal places. If the Inexact trap is set, it is also useful for validation:\\n\\n>>> TWOPLACES = Decimal(10) ** -2 # same as Decimal(\\'0.01\\')\\n\\n>>> # Round to two places\\n>>> Decimal(\\'3.214\\').quantize(TWOPLACES)\\nDecimal(\\'3.21\\')\\n\\n>>> # Validate that a number does not exceed two places\\n>>> Decimal(\\'3.21\\').quantize(TWOPLACES, context=Context(traps=[Inexact]))\\nDecimal(\\'3.21\\')\\n\\n>>> Decimal(\\'3.214\\').quantize(TWOPLACES, context=Context(traps=[Inexact]))\\nTraceback (most recent call last):\\n ...\\nInexact: None\\n\\nQ: Once I have valid two place inputs, how do I maintain that invariant throughout an application?\\n\\nA: 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 quantize() step:\\n\\n>>> a = Decimal(\\'102.72\\') # Initial fixed-point values\\n>>> b = Decimal(\\'3.17\\')\\n>>> a + b # Addition preserves fixed-point\\nDecimal(\\'105.89\\')\\n>>> a - b\\nDecimal(\\'99.55\\')\\n>>> a * 42 # So does integer multiplication\\nDecimal(\\'4314.24\\')\\n>>> (a * b).quantize(TWOPLACES) # Must quantize non-integer multiplication\\nDecimal(\\'325.62\\')\\n>>> (b / a).quantize(TWOPLACES) # And quantize division\\nDecimal(\\'0.03\\')\\n\\nIn developing fixed-point applications, it is convenient to define functions to handle the quantize() step:\\n\\n>>> def mul(x, y, fp=TWOPLACES):\\n... return (x * y).quantize(fp)\\n...\\n>>> def div(x, y, fp=TWOPLACES):\\n... return (x / y).quantize(fp)\\n\\n>>> mul(a, b) # Automatically preserve fixed-point\\nDecimal(\\'325.62\\')\\n>>> div(b, a)\\nDecimal(\\'0.03\\')\\n\\nQ: There are many ways to express the same value. The numbers 200, 200.000, 2E2, and .02E+4 all have the same value at various precisions. Is there a way to transform them to a single recognizable canonical value?\\n\\nA: The normalize() method maps all equivalent values to a single representative:\\n\\n>>> values = map(Decimal, \\'200 200.000 2E2 .02E+4\\'.split())\\n>>> [v.normalize() for v in values]\\n[Decimal(\\'2E+2\\'), Decimal(\\'2E+2\\'), Decimal(\\'2E+2\\'), Decimal(\\'2E+2\\')]\\n\\nQ: When does rounding occur in a computation?\\n\\nA: 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:\\n\\n>>> getcontext().prec = 5\\n>>> pi = Decimal(\\'3.1415926535\\') # More than 5 digits\\n>>> pi # All digits are retained\\nDecimal(\\'3.1415926535\\')\\n>>> pi + 0 # Rounded after an addition\\nDecimal(\\'3.1416\\')\\n>>> pi - Decimal(\\'0.00005\\') # Subtract unrounded numbers, then round\\nDecimal(\\'3.1415\\')\\n>>> pi + 0 - Decimal(\\'0.00005\\'). # Intermediate values are rounded\\nDecimal(\\'3.1416\\')\\n\\nQ: Some decimal values always print with exponential notation. Is there a way to get a non-exponential representation?\\n\\nA: For some values, exponential notation is the only way to express the number of significant places in the coefficient. For example, expressing 5.0E+3 as 5000 keeps the value constant but cannot show the original’s two-place significance.\\n\\nIf an application does not care about tracking significance, it is easy to remove the exponent and trailing zeroes, losing significance, but keeping the value unchanged:\\n\\n>>> def remove_exponent(d):\\n... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()\\n\\n>>> remove_exponent(Decimal(\\'5E+3\\'))\\nDecimal(\\'5000\\')\\n\\nQ: Is there a way to convert a regular float to a Decimal?\\n\\nA: 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:\\n\\n>>> Decimal(math.pi)\\nDecimal(\\'3.141592653589793115997963468544185161590576171875\\')\\n\\nQ: Within a complex calculation, how can I make sure that I haven’t gotten a spurious result because of insufficient precision or rounding anomalies.\\n\\nA: 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.\\n\\nQ: 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?\\n\\nA: 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:\\n\\n>>> getcontext().prec = 3\\n>>> Decimal(\\'3.104\\') + Decimal(\\'2.104\\')\\nDecimal(\\'5.21\\')\\n>>> Decimal(\\'3.104\\') + Decimal(\\'0.000\\') + Decimal(\\'2.104\\')\\nDecimal(\\'5.20\\')\\n\\nThe solution is either to increase precision or to force rounding of inputs using the unary plus operation:\\n\\n>>> getcontext().prec = 3\\n>>> +Decimal(\\'1.23456789\\') # unary plus triggers rounding\\nDecimal(\\'1.23\\')\\n\\nAlternatively, inputs can be rounded upon creation using the Context.create_decimal() method:\\n\\n>>> Context(prec=5, rounding=ROUND_DOWN).create_decimal(\\'1.2345678\\')\\nDecimal(\\'1.2345\\')\\n\\nQ: Is the CPython implementation fast for large numbers?\\n\\nA: Yes. In the CPython and PyPy3 implementations, the C/CFFI versions of the decimal module integrate the high speed libmpdec library for arbitrary precision correctly rounded decimal floating-point arithmetic [1]. libmpdec uses Karatsuba multiplication for medium-sized numbers and the Number Theoretic Transform for very large numbers.\\n\\nThe context must be adapted for exact arbitrary precision arithmetic. Emin and Emax should always be set to the maximum values, clamp should always be 0 (the default). Setting prec requires some care.\\n\\nThe easiest approach for trying out bignum arithmetic is to use the maximum value for prec as well [2]:\\n\\n>>> setcontext(Context(prec=MAX_PREC, Emax=MAX_EMAX, Emin=MIN_EMIN))\\n>>> x = Decimal(2) ** 256\\n>>> x / 128\\nDecimal(\\'904625697166532776746648320380374280103671755200316906558262375061821325312\\')\\n\\nFor inexact results, MAX_PREC is far too large on 64-bit platforms and the available memory will be insufficient:\\n\\n>>> Decimal(1) / 3\\nTraceback (most recent call last):\\n File \"\", line 1, in \\nMemoryError\\n\\nOn systems with overallocation (e.g. Linux), a more sophisticated approach is to adjust 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:\\n\\n>>> import sys\\n>>>\\n>>> # Maximum number of digits for a single operand using 500MB in 8-byte words\\n>>> # with 19 digits per word (4-byte and 9 digits for the 32-bit build):\\n>>> maxdigits = 19 * ((500 * 1024**2) // 8)\\n>>>\\n>>> # Check that this works:\\n>>> c = Context(prec=maxdigits, Emax=MAX_EMAX, Emin=MIN_EMIN)\\n>>> c.traps[Inexact] = True\\n>>> setcontext(c)\\n>>>\\n>>> # Fill the available precision with nines:\\n>>> x = Decimal(0).logical_invert() * 9\\n>>> sys.getsizeof(x)\\n524288112\\n>>> x + 2\\nTraceback (most recent call last):\\n File \"\", line 1, in \\n decimal.Inexact: []\\n\\nIn general (and especially on systems without overallocation), it is recommended to estimate even tighter bounds and set the Inexact trap if all calculations are expected to be exact.\\n\\n[1]\\n\\nAdded in version 3.3.\\n\\n[2]\\n\\nChanged in version 3.9: This approach now works for all exact results except for non-integer powers.\\n\\nTable of Contents\\n\\ndecimal — Decimal fixed-point and floating-point arithmetic\\n\\nQuick-start tutorial\\n\\nDecimal objects\\n\\nLogical operands\\n\\nContext objects\\n\\nConstants\\n\\nRounding modes\\n\\nSignals\\n\\nFloating-point notes\\n\\nMitigating round-off error with increased precision\\n\\nSpecial values\\n\\nWorking with threads\\n\\nRecipes\\n\\nDecimal FAQ\\n\\nPrevious topic\\n\\ncmath — Mathematical functions for complex numbers\\n\\nNext topic\\n\\nfractions — Rational numbers\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNumeric and Mathematical Modules »\\n\\ndecimal — Decimal fixed-point and floating-point arithmetic\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\development.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nDevelopment Tools\\n\\n|\\n\\nDevelopment Tools¶\\n\\nThe modules described in this chapter help you write software. For example, the pydoc module takes a module and generates documentation based on the module’s contents. The doctest and unittest modules contains frameworks for writing unit tests that automatically exercise code and verify that the expected output is produced.\\n\\nThe list of modules described in this chapter is:\\n\\ntyping — Support for type hints\\n\\nSpecification for the Python Type System\\n\\nType aliases\\n\\nNewType\\n\\nAnnotating callable objects\\n\\nGenerics\\n\\nAnnotating tuples\\n\\nThe type of class objects\\n\\nAnnotating generators and coroutines\\n\\nUser-defined generic types\\n\\nThe Any type\\n\\nNominal vs structural subtyping\\n\\nModule contents\\n\\nSpecial typing primitives\\n\\nSpecial types\\n\\nSpecial forms\\n\\nBuilding generic types and type aliases\\n\\nOther special directives\\n\\nProtocols\\n\\nABCs and Protocols for working with I/O\\n\\nFunctions and decorators\\n\\nIntrospection helpers\\n\\nConstant\\n\\nDeprecated aliases\\n\\nAliases to built-in types\\n\\nAliases to types in collections\\n\\nAliases to other concrete types\\n\\nAliases to container ABCs in collections.abc\\n\\nAliases to asynchronous ABCs in collections.abc\\n\\nAliases to other ABCs in collections.abc\\n\\nAliases to contextlib ABCs\\n\\nDeprecation Timeline of Major Features\\n\\npydoc — Documentation generator and online help system\\n\\nPython Development Mode\\n\\nEffects of the Python Development Mode\\n\\nResourceWarning Example\\n\\nBad file descriptor error example\\n\\ndoctest — Test interactive Python examples\\n\\nSimple Usage: Checking Examples in Docstrings\\n\\nSimple Usage: Checking Examples in a Text File\\n\\nCommand-line Usage\\n\\nHow It Works\\n\\nWhich Docstrings Are Examined?\\n\\nHow are Docstring Examples Recognized?\\n\\nWhat’s the Execution Context?\\n\\nWhat About Exceptions?\\n\\nOption Flags\\n\\nDirectives\\n\\nWarnings\\n\\nBasic API\\n\\nUnittest API\\n\\nAdvanced API\\n\\nDocTest Objects\\n\\nExample Objects\\n\\nDocTestFinder objects\\n\\nDocTestParser objects\\n\\nTestResults objects\\n\\nDocTestRunner objects\\n\\nOutputChecker objects\\n\\nDebugging\\n\\nSoapbox\\n\\nunittest — Unit testing framework\\n\\nBasic example\\n\\nCommand-Line Interface\\n\\nCommand-line options\\n\\nTest Discovery\\n\\nOrganizing test code\\n\\nRe-using old test code\\n\\nSkipping tests and expected failures\\n\\nDistinguishing test iterations using subtests\\n\\nClasses and functions\\n\\nTest cases\\n\\nGrouping tests\\n\\nLoading and running tests\\n\\nload_tests Protocol\\n\\nClass and Module Fixtures\\n\\nsetUpClass and tearDownClass\\n\\nsetUpModule and tearDownModule\\n\\nSignal Handling\\n\\nunittest.mock — mock object library\\n\\nQuick Guide\\n\\nThe Mock Class\\n\\nCalling\\n\\nDeleting Attributes\\n\\nMock names and the name attribute\\n\\nAttaching Mocks as Attributes\\n\\nThe patchers\\n\\npatch\\n\\npatch.object\\n\\npatch.dict\\n\\npatch.multiple\\n\\npatch methods: start and stop\\n\\npatch builtins\\n\\nTEST_PREFIX\\n\\nNesting Patch Decorators\\n\\nWhere to patch\\n\\nPatching Descriptors and Proxy Objects\\n\\nMagicMock and magic method support\\n\\nMocking Magic Methods\\n\\nMagic Mock\\n\\nHelpers\\n\\nsentinel\\n\\nDEFAULT\\n\\ncall\\n\\ncreate_autospec\\n\\nANY\\n\\nFILTER_DIR\\n\\nmock_open\\n\\nAutospeccing\\n\\nSealing mocks\\n\\nOrder of precedence of side_effect, return_value and wraps\\n\\nunittest.mock — getting started\\n\\nUsing Mock\\n\\nMock Patching Methods\\n\\nMock for Method Calls on an Object\\n\\nMocking Classes\\n\\nNaming your mocks\\n\\nTracking all Calls\\n\\nSetting Return Values and Attributes\\n\\nRaising exceptions with mocks\\n\\nSide effect functions and iterables\\n\\nMocking asynchronous iterators\\n\\nMocking asynchronous context manager\\n\\nCreating a Mock from an Existing Object\\n\\nUsing side_effect to return per file content\\n\\nPatch Decorators\\n\\nFurther Examples\\n\\nMocking chained calls\\n\\nPartial mocking\\n\\nMocking a Generator Method\\n\\nApplying the same patch to every test method\\n\\nMocking Unbound Methods\\n\\nChecking multiple calls with mock\\n\\nCoping with mutable arguments\\n\\nNesting Patches\\n\\nMocking a dictionary with MagicMock\\n\\nMock subclasses and their attributes\\n\\nMocking imports with patch.dict\\n\\nTracking order of calls and less verbose call assertions\\n\\nMore complex argument matching\\n\\ntest — Regression tests package for Python\\n\\nWriting Unit Tests for the test package\\n\\nRunning tests using the command-line interface\\n\\ntest.support — Utilities for the Python test suite\\n\\ntest.support.socket_helper — Utilities for socket tests\\n\\ntest.support.script_helper — Utilities for the Python execution tests\\n\\ntest.support.bytecode_helper — Support tools for testing correct bytecode generation\\n\\ntest.support.threading_helper — Utilities for threading tests\\n\\ntest.support.os_helper — Utilities for os tests\\n\\ntest.support.import_helper — Utilities for import tests\\n\\ntest.support.warnings_helper — Utilities for warnings tests\\n\\nPrevious topic\\n\\nturtle — Turtle graphics\\n\\nNext topic\\n\\ntyping — Support for type hints\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nDevelopment Tools\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\devmode.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nDevelopment Tools »\\n\\nPython Development Mode\\n\\n|\\n\\nPython Development Mode¶\\n\\nAdded in version 3.7.\\n\\nThe 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.\\n\\nIt can be enabled using the -X dev command line option or by setting the PYTHONDEVMODE environment variable to 1.\\n\\nSee also Python debug build.\\n\\nEffects of the Python Development Mode¶\\n\\nEnabling the Python Development Mode is similar to the following command, but with additional effects described below:\\n\\nPYTHONMALLOC=debug PYTHONASYNCIODEBUG=1 python -W default -X faulthandler\\n\\nEffects of the Python Development Mode:\\n\\nAdd default warning filter. The following warnings are shown:\\n\\nDeprecationWarning\\n\\nImportWarning\\n\\nPendingDeprecationWarning\\n\\nResourceWarning\\n\\nNormally, the above warnings are filtered by the default warning filters.\\n\\nIt behaves as if the -W default command line option is used.\\n\\nUse the -W error command line option or set the PYTHONWARNINGS environment variable to error to treat warnings as errors.\\n\\nInstall debug hooks on memory allocators to check for:\\n\\nBuffer underflow\\n\\nBuffer overflow\\n\\nMemory allocator API violation\\n\\nUnsafe usage of the GIL\\n\\nSee the PyMem_SetupDebugHooks() C function.\\n\\nIt behaves as if the PYTHONMALLOC environment variable is set to debug.\\n\\nTo enable the Python Development Mode without installing debug hooks on memory allocators, set the PYTHONMALLOC environment variable to default.\\n\\nCall faulthandler.enable() at Python startup to install handlers for the SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL signals to dump the Python traceback on a crash.\\n\\nIt behaves as if the -X faulthandler command line option is used or if the PYTHONFAULTHANDLER environment variable is set to 1.\\n\\nEnable asyncio debug mode. For example, asyncio checks for coroutines that were not awaited and logs them.\\n\\nIt behaves as if the PYTHONASYNCIODEBUG environment variable is set to 1.\\n\\nCheck the encoding and errors arguments for string encoding and decoding operations. Examples: open(), str.encode() and bytes.decode().\\n\\nBy 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.\\n\\nThe io.IOBase destructor logs close() exceptions.\\n\\nSet the dev_mode attribute of sys.flags to True.\\n\\nThe Python Development Mode does not enable the tracemalloc module by default, because the overhead cost (to performance and memory) would be too large. Enabling the tracemalloc module provides additional information on the origin of some errors. For example, ResourceWarning logs the traceback where the resource was allocated, and a buffer overflow error logs the traceback where the memory block was allocated.\\n\\nThe Python Development Mode does not prevent the -O command line option from removing assert statements nor from setting __debug__ to False.\\n\\nThe Python Development Mode can only be enabled at the Python startup. Its value can be read from sys.flags.dev_mode.\\n\\nChanged in version 3.8: The io.IOBase destructor now logs close() exceptions.\\n\\nChanged in version 3.9: The encoding and errors arguments are now checked for string encoding and decoding operations.\\n\\nResourceWarning Example¶\\n\\nExample of a script counting the number of lines of the text file specified in the command line:\\n\\nimport sys\\n\\ndef main():\\n fp = open(sys.argv[1])\\n nlines = len(fp.readlines())\\n print(nlines)\\n # The file is closed implicitly\\n\\nif __name__ == \"__main__\":\\n main()\\n\\nThe script does not close the file explicitly. By default, Python does not emit any warning. Example using README.txt, which has 269 lines:\\n\\n$ python script.py README.txt\\n269\\n\\nEnabling the Python Development Mode displays a ResourceWarning warning:\\n\\n$ python -X dev script.py README.txt\\n269\\nscript.py:10: ResourceWarning: unclosed file <_io.TextIOWrapper name=\\'README.rst\\' mode=\\'r\\' encoding=\\'UTF-8\\'>\\n main()\\nResourceWarning: Enable tracemalloc to get the object allocation traceback\\n\\nIn addition, enabling tracemalloc shows the line where the file was opened:\\n\\n$ python -X dev -X tracemalloc=5 script.py README.rst\\n269\\nscript.py:10: ResourceWarning: unclosed file <_io.TextIOWrapper name=\\'README.rst\\' mode=\\'r\\' encoding=\\'UTF-8\\'>\\n main()\\nObject allocated at (most recent call last):\\n File \"script.py\", lineno 10\\n main()\\n File \"script.py\", lineno 4\\n fp = open(sys.argv[1])\\n\\nThe fix is to close explicitly the file. Example using a context manager:\\n\\ndef main():\\n # Close the file explicitly when exiting the with block\\n with open(sys.argv[1]) as fp:\\n nlines = len(fp.readlines())\\n print(nlines)\\n\\nNot 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.\\n\\nBad file descriptor error example¶\\n\\nScript displaying the first line of itself:\\n\\nimport os\\n\\ndef main():\\n fp = open(__file__)\\n firstline = fp.readline()\\n print(firstline.rstrip())\\n os.close(fp.fileno())\\n # The file is closed implicitly\\n\\nmain()\\n\\nBy default, Python does not emit any warning:\\n\\n$ python script.py\\nimport os\\n\\nThe Python Development Mode shows a ResourceWarning and logs a “Bad file descriptor” error when finalizing the file object:\\n\\n$ python -X dev script.py\\nimport os\\nscript.py:10: ResourceWarning: unclosed file <_io.TextIOWrapper name=\\'script.py\\' mode=\\'r\\' encoding=\\'UTF-8\\'>\\n main()\\nResourceWarning: Enable tracemalloc to get the object allocation traceback\\nException ignored in: <_io.TextIOWrapper name=\\'script.py\\' mode=\\'r\\' encoding=\\'UTF-8\\'>\\nTraceback (most recent call last):\\n File \"script.py\", line 10, in \\n main()\\nOSError: [Errno 9] Bad file descriptor\\n\\nos.close(fp.fileno()) closes the file descriptor. When the file object finalizer tries to close the file descriptor again, it fails with the 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 for an example).\\n\\nThe fix is to remove the os.close(fp.fileno()) line, or open the file with closefd=False.\\n\\nTable of Contents\\n\\nPython Development Mode\\n\\nEffects of the Python Development Mode\\n\\nResourceWarning Example\\n\\nBad file descriptor error example\\n\\nPrevious topic\\n\\npydoc — Documentation generator and online help system\\n\\nNext topic\\n\\ndoctest — Test interactive Python examples\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nDevelopment Tools »\\n\\nPython Development Mode\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\dialog.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nGraphical user interfaces with Tk »\\n\\nTkinter Dialogs\\n\\n|\\n\\nTkinter Dialogs¶\\n\\ntkinter.simpledialog — Standard Tkinter input dialogs¶\\n\\nSource code: Lib/tkinter/simpledialog.py\\n\\nThe tkinter.simpledialog module contains convenience classes and functions for creating simple modal dialogs to get a value from the user.\\n\\ntkinter.filedialog — File selection dialogs¶\\n\\nSource code: Lib/tkinter/filedialog.py\\n\\nThe tkinter.filedialog module provides classes and factory functions for creating file/directory selection windows.\\n\\nNative Load/Save Dialogs¶\\n\\nThe following classes and functions provide file dialog windows that combine a native look-and-feel with configuration options to customize behaviour. The following keyword arguments are applicable to the classes and functions listed below:\\n\\nparent - the window to place the dialog on top of\\n\\ntitle - the title of the window\\n\\ninitialdir - the directory that the dialog starts in\\n\\ninitialfile - the file selected upon opening of the dialog\\n\\nfiletypes - a sequence of (label, pattern) tuples, ‘*’ wildcard is allowed\\n\\ndefaultextension - default extension to append to file (save dialogs)\\n\\nmultiple - when true, selection of multiple items is allowed\\n\\nStatic factory functions\\n\\nThe 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 None to the caller.\\n\\nConvenience classes\\n\\nThe below classes are used for creating file/directory windows from scratch. These do not emulate the native look-and-feel of the platform.\\n\\nNote\\n\\nThe FileDialog class should be subclassed for custom event handling and behaviour.\\n\\ntkinter.commondialog — Dialog window templates¶\\n\\nSource code: Lib/tkinter/commondialog.py\\n\\nThe tkinter.commondialog module provides the Dialog class that is the base class for dialogs defined in other supporting modules.\\n\\nSee also\\n\\nModules tkinter.messagebox, Reading and Writing Files\\n\\nTable of Contents\\n\\nTkinter Dialogs\\n\\ntkinter.simpledialog — Standard Tkinter input dialogs\\n\\ntkinter.filedialog — File selection dialogs\\n\\nNative Load/Save Dialogs\\n\\ntkinter.commondialog — Dialog window templates\\n\\nPrevious topic\\n\\ntkinter.font — Tkinter font wrapper\\n\\nNext topic\\n\\ntkinter.messagebox — Tkinter message prompts\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nGraphical user interfaces with Tk »\\n\\nTkinter Dialogs\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\difflib.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nText Processing Services »\\n\\ndifflib — Helpers for computing deltas\\n\\n|\\n\\ndifflib — Helpers for computing deltas¶\\n\\nSource code: Lib/difflib.py\\n\\nThis module provides classes and functions for comparing sequences. It can be used for example, for comparing files, and can produce information about file differences in various formats, including HTML and context and unified diffs. For comparing directories and files, see also, the filecmp module.\\n\\nSee also\\n\\nSequenceMatcher Objects¶\\n\\nThe SequenceMatcher class has this constructor:\\n\\nThe three methods that return the ratio of matching to total characters can give different results due to differing levels of approximation, although quick_ratio() and real_quick_ratio() are always at least as large as ratio():\\n\\n>>> s = SequenceMatcher(None, \"abcd\", \"bcde\")\\n>>> s.ratio()\\n0.75\\n>>> s.quick_ratio()\\n0.75\\n>>> s.real_quick_ratio()\\n1.0\\n\\nSequenceMatcher Examples¶\\n\\nThis example compares two strings, considering blanks to be “junk”:\\n\\n>>> s = SequenceMatcher(lambda x: x == \" \",\\n... \"private Thread currentThread;\",\\n... \"private volatile Thread currentThread;\")\\n\\nratio() returns a float in [0, 1], measuring the similarity of the sequences. As a rule of thumb, a ratio() value over 0.6 means the sequences are close matches:\\n\\n>>> print(round(s.ratio(), 3))\\n0.866\\n\\nIf you’re only interested in where the sequences match, get_matching_blocks() is handy:\\n\\n>>> for block in s.get_matching_blocks():\\n... print(\"a[%d] and b[%d] match for %d elements\" % block)\\na[0] and b[0] match for 8 elements\\na[8] and b[17] match for 21 elements\\na[29] and b[38] match for 0 elements\\n\\nNote that the last tuple returned by get_matching_blocks() is always a dummy, (len(a), len(b), 0), and this is the only case in which the last tuple element (number of elements matched) is 0.\\n\\nIf you want to know how to change the first sequence into the second, use get_opcodes():\\n\\n>>> for opcode in s.get_opcodes():\\n... print(\"%6s a[%d:%d] b[%d:%d]\" % opcode)\\n equal a[0:8] b[0:8]\\ninsert a[8:8] b[8:17]\\n equal a[8:29] b[17:38]\\n\\nSee also\\n\\nThe get_close_matches() function in this module which shows how simple code building on SequenceMatcher can be used to do useful work.\\n\\nSimple version control recipe for a small application built with SequenceMatcher.\\n\\nDiffer Objects¶\\n\\nNote that Differ-generated deltas make no claim to be minimal diffs. To the contrary, minimal diffs are often counter-intuitive, because they synch up anywhere possible, sometimes accidental matches 100 pages apart. Restricting synch points to contiguous matches preserves some notion of locality, at the occasional cost of producing a longer diff.\\n\\nThe Differ class has this constructor:\\n\\nDiffer Example¶\\n\\nThis 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 readlines() method of file-like objects):\\n\\n>>> text1 = \\'\\'\\' 1. Beautiful is better than ugly.\\n... 2. Explicit is better than implicit.\\n... 3. Simple is better than complex.\\n... 4. Complex is better than complicated.\\n... \\'\\'\\'.splitlines(keepends=True)\\n>>> len(text1)\\n4\\n>>> text1[0][-1]\\n\\'\\\\n\\'\\n>>> text2 = \\'\\'\\' 1. Beautiful is better than ugly.\\n... 3. Simple is better than complex.\\n... 4. Complicated is better than complex.\\n... 5. Flat is better than nested.\\n... \\'\\'\\'.splitlines(keepends=True)\\n\\nNext we instantiate a Differ object:\\n\\n>>> d = Differ()\\n\\nNote that when instantiating a Differ object we may pass functions to filter out line and character “junk.” See the Differ() constructor for details.\\n\\nFinally, we compare the two:\\n\\n>>> result = list(d.compare(text1, text2))\\n\\nresult is a list of strings, so let’s pretty-print it:\\n\\n>>> from pprint import pprint\\n>>> pprint(result)\\n[\\' 1. Beautiful is better than ugly.\\\\n\\',\\n \\'- 2. Explicit is better than implicit.\\\\n\\',\\n \\'- 3. Simple is better than complex.\\\\n\\',\\n \\'+ 3. Simple is better than complex.\\\\n\\',\\n \\'? ++\\\\n\\',\\n \\'- 4. Complex is better than complicated.\\\\n\\',\\n \\'? ^ ---- ^\\\\n\\',\\n \\'+ 4. Complicated is better than complex.\\\\n\\',\\n \\'? ++++ ^ ^\\\\n\\',\\n \\'+ 5. Flat is better than nested.\\\\n\\']\\n\\nAs a single multi-line string it looks like this:\\n\\n>>> import sys\\n>>> sys.stdout.writelines(result)\\n 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\\nA command-line interface to difflib¶\\n\\nThis example shows how to use difflib to create a diff-like utility.\\n\\n\"\"\" Command line interface to difflib.py providing diffs in four formats:\\n\\n* ndiff: lists every line and highlights interline changes.\\n* context: highlights clusters of changes in a before/after format.\\n* unified: highlights clusters of changes in an inline format.\\n* html: generates side by side comparison with change highlights.\\n\\n\"\"\"\\n\\nimport sys, os, difflib, argparse\\nfrom datetime import datetime, timezone\\n\\ndef file_mtime(path):\\n t = datetime.fromtimestamp(os.stat(path).st_mtime,\\n timezone.utc)\\n return t.astimezone().isoformat()\\n\\ndef main():\\n\\n parser = argparse.ArgumentParser()\\n parser.add_argument(\\'-c\\', action=\\'store_true\\', default=False,\\n help=\\'Produce a context format diff (default)\\')\\n parser.add_argument(\\'-u\\', action=\\'store_true\\', default=False,\\n help=\\'Produce a unified format diff\\')\\n parser.add_argument(\\'-m\\', action=\\'store_true\\', default=False,\\n help=\\'Produce HTML side by side diff \\'\\n \\'(can use -c and -l in conjunction)\\')\\n parser.add_argument(\\'-n\\', action=\\'store_true\\', default=False,\\n help=\\'Produce a ndiff format diff\\')\\n parser.add_argument(\\'-l\\', \\'--lines\\', type=int, default=3,\\n help=\\'Set number of context lines (default 3)\\')\\n parser.add_argument(\\'fromfile\\')\\n parser.add_argument(\\'tofile\\')\\n options = parser.parse_args()\\n\\n n = options.lines\\n fromfile = options.fromfile\\n tofile = options.tofile\\n\\n fromdate = file_mtime(fromfile)\\n todate = file_mtime(tofile)\\n with open(fromfile) as ff:\\n fromlines = ff.readlines()\\n with open(tofile) as tf:\\n tolines = tf.readlines()\\n\\n if options.u:\\n diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n)\\n elif options.n:\\n diff = difflib.ndiff(fromlines, tolines)\\n elif options.m:\\n diff = difflib.HtmlDiff().make_file(fromlines,tolines,fromfile,tofile,context=options.c,numlines=n)\\n else:\\n diff = difflib.context_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n)\\n\\n sys.stdout.writelines(diff)\\n\\nif __name__ == \\'__main__\\':\\n main()\\n\\nndiff example¶\\n\\nThis example shows how to use difflib.ndiff().\\n\\n\"\"\"ndiff [-q] file1 file2\\n or\\nndiff (-r1 | -r2) < ndiff_output > file1_or_file2\\n\\nPrint a human-friendly file difference report to stdout. Both inter-\\nand intra-line differences are noted. In the second form, recreate file1\\n(-r1) or file2 (-r2) on stdout, from an ndiff report on stdin.\\n\\nIn the first form, if -q (\"quiet\") is not specified, the first two lines\\nof output are\\n\\n-: file1\\n+: file2\\n\\nEach remaining line begins with a two-letter code:\\n\\n \"- \" line unique to file1\\n \"+ \" line unique to file2\\n \" \" line common to both files\\n \"? \" line not present in either input file\\n\\nLines beginning with \"? \" attempt to guide the eye to intraline\\ndifferences, and were not present in either input file. These lines can be\\nconfusing if the source files contain tab characters.\\n\\nThe first file can be recovered by retaining only lines that begin with\\n\" \" or \"- \", and deleting those 2-character prefixes; use ndiff with -r1.\\n\\nThe second file can be recovered similarly, but by retaining only \" \" and\\n\"+ \" lines; use ndiff with -r2; or, on Unix, the second file can be\\nrecovered by piping the output through\\n\\n sed -n \\'/^[+ ] /s/^..//p\\'\\n\"\"\"\\n\\n__version__ = 1, 7, 0\\n\\nimport difflib, sys\\n\\ndef fail(msg):\\n out = sys.stderr.write\\n out(msg + \"\\\\n\\\\n\")\\n out(__doc__)\\n return 0\\n\\n# open a file & return the file object; gripe and return 0 if it\\n# couldn\\'t be opened\\ndef fopen(fname):\\n try:\\n return open(fname)\\n except IOError as detail:\\n return fail(\"couldn\\'t open \" + fname + \": \" + str(detail))\\n\\n# open two files & spray the diff to stdout; return false iff a problem\\ndef fcompare(f1name, f2name):\\n f1 = fopen(f1name)\\n f2 = fopen(f2name)\\n if not f1 or not f2:\\n return 0\\n\\n a = f1.readlines(); f1.close()\\n b = f2.readlines(); f2.close()\\n for line in difflib.ndiff(a, b):\\n print(line, end=\\' \\')\\n\\n return 1\\n\\n# crack args (sys.argv[1:] is normal) & compare;\\n# return false iff a problem\\n\\ndef main(args):\\n import getopt\\n try:\\n opts, args = getopt.getopt(args, \"qr:\")\\n except getopt.error as detail:\\n return fail(str(detail))\\n noisy = 1\\n qseen = rseen = 0\\n for opt, val in opts:\\n if opt == \"-q\":\\n qseen = 1\\n noisy = 0\\n elif opt == \"-r\":\\n rseen = 1\\n whichfile = val\\n if qseen and rseen:\\n return fail(\"can\\'t specify both -q and -r\")\\n if rseen:\\n if args:\\n return fail(\"no args allowed with -r option\")\\n if whichfile in (\"1\", \"2\"):\\n restore(whichfile)\\n return 1\\n return fail(\"-r value must be 1 or 2\")\\n if len(args) != 2:\\n return fail(\"need 2 filename args\")\\n f1name, f2name = args\\n if noisy:\\n print(\\'-:\\', f1name)\\n print(\\'+:\\', f2name)\\n return fcompare(f1name, f2name)\\n\\n# read ndiff output from stdin, and print file1 (which==\\'1\\') or\\n# file2 (which==\\'2\\') to stdout\\n\\ndef restore(which):\\n restored = difflib.restore(sys.stdin.readlines(), which)\\n sys.stdout.writelines(restored)\\n\\nif __name__ == \\'__main__\\':\\n main(sys.argv[1:])\\n\\nTable of Contents\\n\\ndifflib — Helpers for computing deltas\\n\\nSequenceMatcher Objects\\n\\nSequenceMatcher Examples\\n\\nDiffer Objects\\n\\nDiffer Example\\n\\nA command-line interface to difflib\\n\\nndiff example\\n\\nPrevious topic\\n\\nre — Regular expression operations\\n\\nNext topic\\n\\ntextwrap — Text wrapping and filling\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nText Processing Services »\\n\\ndifflib — Helpers for computing deltas\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\dis.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Language Services »\\n\\ndis — Disassembler for Python bytecode\\n\\n|\\n\\ndis — Disassembler for Python bytecode¶\\n\\nSource code: Lib/dis.py\\n\\nThe dis module supports the analysis of CPython bytecode by disassembling it. The CPython bytecode which this module takes as an input is defined in the file Include/opcode.h and used by the compiler and the interpreter.\\n\\nCPython implementation detail: Bytecode is an implementation detail of the CPython interpreter. No guarantees are made that bytecode will not be added, removed, or changed between versions of Python. Use of this module should not be considered to work across Python VMs or Python releases.\\n\\nChanged in version 3.6: Use 2 bytes for each instruction. Previously the number of bytes varied by instruction.\\n\\nChanged in version 3.10: The argument of jump, exception handling and loop instructions is now the instruction offset rather than the byte offset.\\n\\nChanged in version 3.11: Some instructions are accompanied by one or more inline cache entries, which take the form of CACHE instructions. These instructions are hidden by default, but can be shown by passing show_caches=True to any dis utility. Furthermore, the interpreter now adapts the bytecode to specialize it for different runtime conditions. The adaptive bytecode can be shown by passing adaptive=True.\\n\\nChanged in version 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 CACHE entries.\\n\\nAs a consequence, the presence of the CACHE instructions is transparent for forward jumps but needs to be taken into account when reasoning about backward jumps.\\n\\nChanged in version 3.13: The output shows logical labels rather than instruction offsets for jump targets and exception handlers. The -O command line option and the show_offsets argument were added.\\n\\nChanged in version 3.14: The -P command-line option and the show_positions argument were added.\\n\\nThe -S command-line option is added.\\n\\nExample: Given the function myfunc():\\n\\ndef myfunc(alist):\\n return len(alist)\\n\\nthe following command can be used to display the disassembly of myfunc():\\n\\n>>> dis.dis(myfunc)\\n 2 RESUME 0\\n\\n 3 LOAD_GLOBAL 1 (len + NULL)\\n LOAD_FAST_BORROW 0 (alist)\\n CALL 1\\n RETURN_VALUE\\n\\n(The “2” is a line number).\\n\\nCommand-line interface¶\\n\\nThe dis module can be invoked as a script from the command line:\\n\\npython -m dis [-h] [-C] [-O] [-P] [-S] [infile]\\n\\nThe following options are accepted:\\n\\nIf infile is specified, its disassembled code will be written to stdout. Otherwise, disassembly is performed on compiled source code received from stdin.\\n\\nBytecode analysis¶\\n\\nAdded in version 3.4.\\n\\nThe bytecode analysis API allows pieces of Python code to be wrapped in a Bytecode object that provides easy access to details of the compiled code.\\n\\nExample:\\n\\n>>> bytecode = dis.Bytecode(myfunc)\\n>>> for instr in bytecode:\\n... print(instr.opname)\\n...\\nRESUME\\nLOAD_GLOBAL\\nLOAD_FAST_BORROW\\nCALL\\nRETURN_VALUE\\n\\nAnalysis functions¶\\n\\nThe 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:\\n\\nPython Bytecode Instructions¶\\n\\nThe get_instructions() function and Bytecode class provide details of bytecode instructions as Instruction instances:\\n\\nThe Python compiler currently generates the following bytecode instructions.\\n\\nGeneral instructions\\n\\nIn the following, We will refer to the interpreter stack as STACK and describe operations on it as if it was a Python list. The top of the stack corresponds to STACK[-1] in this language.\\n\\nUnary operations\\n\\nUnary operations take the top of the stack, apply the operation, and push the result back on the stack.\\n\\nBinary and in-place operations\\n\\nBinary operations remove the top two items from the stack (STACK[-1] and STACK[-2]). They perform the operation, then put the result back on the stack.\\n\\nIn-place operations are like binary operations, but the operation is done in-place when STACK[-2] supports it, and the resulting STACK[-1] may be (but does not have to be) the original STACK[-2].\\n\\nCoroutine opcodes\\n\\nMiscellaneous opcodes\\n\\nFor all of the SET_ADD, LIST_APPEND and MAP_ADD instructions, while the added value or key/value pair is popped off, the container object remains on the stack so that it is available for further iterations of the loop.\\n\\nPseudo-instructions\\n\\nThese 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.\\n\\nOpcode collections¶\\n\\nThese collections are provided for automatic introspection of bytecode instructions:\\n\\nChanged in version 3.12: The collections now contain pseudo instructions and instrumented instructions as well. These are opcodes with values >= MIN_PSEUDO_OPCODE and >= MIN_INSTRUMENTED_OPCODE.\\n\\nTable of Contents\\n\\ndis — Disassembler for Python bytecode\\n\\nCommand-line interface\\n\\nBytecode analysis\\n\\nAnalysis functions\\n\\nPython Bytecode Instructions\\n\\nOpcode collections\\n\\nPrevious topic\\n\\ncompileall — Byte-compile Python libraries\\n\\nNext topic\\n\\npickletools — Tools for pickle developers\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Language Services »\\n\\ndis — Disassembler for Python bytecode\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\distribution.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nSoftware Packaging and Distribution\\n\\n|\\n\\nSoftware Packaging and Distribution¶\\n\\nThese libraries help you with publishing and installing Python software. While these modules are designed to work in conjunction with the Python Package Index, they can also be used with a local index server, or without any index server at all.\\n\\nensurepip — Bootstrapping the pip installer\\n\\nCommand-line interface\\n\\nModule API\\n\\nvenv — Creation of virtual environments\\n\\nCreating virtual environments\\n\\nHow venvs work\\n\\nAPI\\n\\nAn example of extending EnvBuilder\\n\\nzipapp — Manage executable Python zip archives\\n\\nBasic Example\\n\\nCommand-Line Interface\\n\\nPython API\\n\\nExamples\\n\\nSpecifying the Interpreter\\n\\nCreating Standalone Applications with zipapp\\n\\nCaveats\\n\\nThe Python Zip Application Archive Format\\n\\nPrevious topic\\n\\ntracemalloc — Trace memory allocations\\n\\nNext topic\\n\\nensurepip — Bootstrapping the pip installer\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nSoftware Packaging and Distribution\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\distutils.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nRemoved Modules »\\n\\ndistutils — Building and installing Python modules\\n\\n|\\n\\ndistutils — Building and installing Python modules¶\\n\\nDeprecated since version 3.10, removed in version 3.12.\\n\\nThis module is no longer part of the Python standard library. It was removed in Python 3.12 after being deprecated in Python 3.10. The removal was decided in PEP 632, which has migration advice.\\n\\nThe last version of Python that provided the distutils module was Python 3.11.\\n\\nPrevious topic\\n\\ncrypt — Function to check Unix passwords\\n\\nNext topic\\n\\nimghdr — Determine the type of an image\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nRemoved Modules »\\n\\ndistutils — Building and installing Python modules\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\doctest.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nDevelopment Tools »\\n\\ndoctest — Test interactive Python examples\\n\\n|\\n\\ndoctest — Test interactive Python examples¶\\n\\nSource code: Lib/doctest.py\\n\\nThe 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:\\n\\nTo check that a module’s docstrings are up-to-date by verifying that all interactive examples still work as documented.\\n\\nTo perform regression testing by verifying that interactive examples from a test file or a test object work as expected.\\n\\nTo write tutorial documentation for a package, liberally illustrated with input-output examples. Depending on whether the examples or the expository text are emphasized, this has the flavor of “literate testing” or “executable documentation”.\\n\\nHere’s a complete but small example module:\\n\\n\"\"\"\\nThis is the \"example\" module.\\n\\nThe example module supplies one function, factorial(). For example,\\n\\n>>> factorial(5)\\n120\\n\"\"\"\\n\\ndef factorial(n):\\n \"\"\"Return the factorial of n, an exact integer >= 0.\\n\\n >>> [factorial(n) for n in range(6)]\\n [1, 1, 2, 6, 24, 120]\\n >>> factorial(30)\\n 265252859812191058636308480000000\\n >>> factorial(-1)\\n Traceback (most recent call last):\\n ...\\n ValueError: n must be >= 0\\n\\n Factorials of floats are OK, but the float must be an exact integer:\\n >>> factorial(30.1)\\n Traceback (most recent call last):\\n ...\\n ValueError: n must be exact integer\\n >>> factorial(30.0)\\n 265252859812191058636308480000000\\n\\n It must also not be ridiculously large:\\n >>> factorial(1e100)\\n Traceback (most recent call last):\\n ...\\n OverflowError: n too large\\n \"\"\"\\n\\n import math\\n if not n >= 0:\\n raise ValueError(\"n must be >= 0\")\\n if math.floor(n) != n:\\n raise ValueError(\"n must be exact integer\")\\n if n+1 == n: # catch a value like 1e300\\n raise OverflowError(\"n too large\")\\n result = 1\\n factor = 2\\n while factor <= n:\\n result *= factor\\n factor += 1\\n return result\\n\\n\\nif __name__ == \"__main__\":\\n import doctest\\n doctest.testmod()\\n\\nIf you run example.py directly from the command line, doctest works its magic:\\n\\n$ python example.py\\n$\\n\\nThere’s no output! That’s normal, and it means all the examples worked. Pass -v to the script, and doctest prints a detailed log of what it’s trying, and prints a summary at the end:\\n\\n$ python example.py -v\\nTrying:\\n factorial(5)\\nExpecting:\\n 120\\nok\\nTrying:\\n [factorial(n) for n in range(6)]\\nExpecting:\\n [1, 1, 2, 6, 24, 120]\\nok\\n\\nAnd so on, eventually ending with:\\n\\nTrying:\\n factorial(1e100)\\nExpecting:\\n Traceback (most recent call last):\\n ...\\n OverflowError: n too large\\nok\\n2 items passed all tests:\\n 1 test in __main__\\n 6 tests in __main__.factorial\\n7 tests in 2 items.\\n7 passed.\\nTest passed.\\n$\\n\\nThat’s all you need to know to start making productive use of 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 Lib/test/test_doctest/test_doctest.py.\\n\\nAdded in version 3.13: Output is colorized by default and can be controlled using environment variables.\\n\\nSimple Usage: Checking Examples in Docstrings¶\\n\\nThe simplest way to start using doctest (but not necessarily the way you’ll continue to do it) is to end each module M with:\\n\\nif __name__ == \"__main__\":\\n import doctest\\n doctest.testmod()\\n\\ndoctest then examines docstrings in module M.\\n\\nRunning the module as a script causes the examples in the docstrings to get executed and verified:\\n\\npython M.py\\n\\nThis won’t display anything unless an example fails, in which case the failing example(s) and the cause(s) of the failure(s) are printed to stdout, and the final line of output is ***Test Failed*** N failures., where N is the number of examples that failed.\\n\\nRun it with the -v switch instead:\\n\\npython M.py -v\\n\\nand a detailed report of all examples tried is printed to standard output, along with assorted summaries at the end.\\n\\nYou can force verbose mode by passing verbose=True to testmod(), or prohibit it by passing verbose=False. In either of those cases, sys.argv is not examined by testmod() (so passing -v or not has no effect).\\n\\nThere is also a command line shortcut for running testmod(), see section Command-line Usage.\\n\\nFor more information on testmod(), see section Basic API.\\n\\nSimple Usage: Checking Examples in a Text File¶\\n\\nAnother simple application of doctest is testing interactive examples in a text file. This can be done with the testfile() function:\\n\\nimport doctest\\ndoctest.testfile(\"example.txt\")\\n\\nThat short script executes and verifies any interactive Python examples contained in the file example.txt. The file content is treated as if it were a single giant docstring; the file doesn’t need to contain a Python program! For example, perhaps example.txt contains this:\\n\\nThe ``example`` module\\n======================\\n\\nUsing ``factorial``\\n-------------------\\n\\nThis is an example text file in reStructuredText format. First import\\n``factorial`` from the ``example`` module:\\n\\n >>> from example import factorial\\n\\nNow use it:\\n\\n >>> factorial(6)\\n 120\\n\\nRunning doctest.testfile(\"example.txt\") then finds the error in this documentation:\\n\\nFile \"./example.txt\", line 14, in example.txt\\nFailed example:\\n factorial(6)\\nExpected:\\n 120\\nGot:\\n 720\\n\\nAs with testmod(), testfile() won’t display anything unless an example fails. If an example does fail, then the failing example(s) and the cause(s) of the failure(s) are printed to stdout, using the same format as testmod().\\n\\nBy default, testfile() looks for files in the calling module’s directory. See section Basic API for a description of the optional arguments that can be used to tell it to look for files in other locations.\\n\\nLike testmod(), testfile()’s verbosity can be set with the -v command-line switch or with the optional keyword argument verbose.\\n\\nThere is also a command line shortcut for running testfile(), see section Command-line Usage.\\n\\nFor more information on testfile(), see section Basic API.\\n\\nCommand-line Usage¶\\n\\nThe doctest module can be invoked as a script from the command line:\\n\\npython -m doctest [-v] [-o OPTION] [-f] file [file ...]\\n\\nHow It Works¶\\n\\nThis section examines in detail how doctest works: which docstrings it looks at, how it finds interactive examples, what execution context it uses, how it handles exceptions, and how option flags can be used to control its behavior. This is the information that you need to know to write doctest examples; for information about actually running doctest on these examples, see the following sections.\\n\\nWhich Docstrings Are Examined?¶\\n\\nThe module docstring, and all function, class and method docstrings are searched. Objects imported into the module are not searched.\\n\\nIn 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 __test__ and uses it to locate other tests. If 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 M.__test__ are searched, and strings are treated as if they were docstrings. In output, a key K in M.__test__ appears with name M.__test__.K.\\n\\nFor example, place this block of code at the top of example.py:\\n\\n__test__ = {\\n \\'numbers\\': \"\"\"\\n>>> factorial(6)\\n720\\n\\n>>> [factorial(n) for n in range(6)]\\n[1, 1, 2, 6, 24, 120]\\n\"\"\"\\n}\\n\\nThe value of 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, doctest searches them recursively for docstrings, which are then scanned for tests.\\n\\nAny classes found are recursively searched similarly, to test docstrings in their contained methods and nested classes.\\n\\nNote\\n\\ndoctest can only automatically discover classes and functions that are defined at the module level or inside other classes.\\n\\nSince nested classes and functions only exist when an outer function is called, they cannot be discovered. Define them outside to make them visible.\\n\\nHow are Docstring Examples Recognized?¶\\n\\nIn most cases a copy-and-paste of an interactive console session works fine, but doctest isn’t trying to do an exact emulation of any specific Python shell.\\n\\n>>> # comments are ignored\\n>>> x = 12\\n>>> x\\n12\\n>>> if x == 13:\\n... print(\"yes\")\\n... else:\\n... print(\"no\")\\n... print(\"NO\")\\n... print(\"NO!!!\")\\n...\\nno\\nNO\\nNO!!!\\n>>>\\n\\nAny expected output must immediately follow the final \\'>>> \\' or \\'... \\' line containing the code, and the expected output (if any) extends to the next \\'>>> \\' or all-whitespace line.\\n\\nThe fine print:\\n\\nExpected output cannot contain an all-whitespace line, since such a line is taken to signal the end of expected output. If expected output does contain a blank line, put in your doctest example each place a blank line is expected.\\n\\nAll hard tab characters are expanded to spaces, using 8-column tab stops. Tabs in output generated by the tested code are not modified. Because any hard tabs in the sample output are expanded, this means that if the code output includes hard tabs, the only way the doctest can pass is if the NORMALIZE_WHITESPACE option or directive is in effect. Alternatively, the test can be rewritten to capture the output and compare it to an expected value as part of the test. This handling of tabs in the source was arrived at through trial and error, and has proven to be the least error prone way of handling them. It is possible to use a different algorithm for handling tabs by writing a custom DocTestParser class.\\n\\nOutput to stdout is captured, but not output to stderr (exception tracebacks are captured via a different means).\\n\\nIf you continue a line via backslashing in an interactive session, or for any other reason use a backslash, you should use a raw docstring, which will preserve your backslashes exactly as you type them:\\n\\n>>> def f(x):\\n... r\\'\\'\\'Backslashes in a raw docstring: m\\\\n\\'\\'\\'\\n...\\n>>> print(f.__doc__)\\nBackslashes in a raw docstring: m\\\\n\\n\\nOtherwise, the backslash will be interpreted as part of the string. For example, the \\\\n above would be interpreted as a newline character. Alternatively, you can double each backslash in the doctest version (and not use a raw string):\\n\\n>>> def f(x):\\n... \\'\\'\\'Backslashes in a raw docstring: m\\\\\\\\n\\'\\'\\'\\n...\\n>>> print(f.__doc__)\\nBackslashes in a raw docstring: m\\\\n\\n\\nThe starting column doesn’t matter:\\n\\n>>> assert \"Easy!\"\\n >>> import math\\n >>> math.floor(1.9)\\n 1\\n\\nand as many leading whitespace characters are stripped from the expected output as appeared in the initial \\'>>> \\' line that started the example.\\n\\nWhat’s the Execution Context?¶\\n\\nBy default, each time doctest finds a docstring to test, it uses a shallow copy of M’s globals, so that running tests doesn’t change the module’s real globals, and so that one test in 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 M, and names defined earlier in the docstring being run. Examples cannot see names defined in other docstrings.\\n\\nYou can force use of your own dict as the execution context by passing globs=your_dict to testmod() or testfile() instead.\\n\\nWhat About Exceptions?¶\\n\\nNo problem, provided that the traceback is the only output produced by the example: just paste in the traceback. [1] Since tracebacks contain details that are likely to change rapidly (for example, exact file paths and line numbers), this is one case where doctest works hard to be flexible in what it accepts.\\n\\nSimple example:\\n\\n>>> [1, 2, 3].remove(42)\\nTraceback (most recent call last):\\n File \"\", line 1, in \\nValueError: list.remove(x): x not in list\\n\\nThat doctest succeeds if ValueError is raised, with the list.remove(x): x not in list detail as shown.\\n\\nThe expected output for an exception must start with a traceback header, which may be either of the following two lines, indented the same as the first line of the example:\\n\\nTraceback (most recent call last):\\nTraceback (innermost last):\\n\\nThe traceback header is followed by an optional traceback stack, whose contents are ignored by doctest. The traceback stack is typically omitted, or copied verbatim from an interactive session.\\n\\nThe traceback stack is followed by the most interesting part: the line(s) containing the exception type and detail. This is usually the last line of a traceback, but can extend across multiple lines if the exception has a multi-line detail:\\n\\n>>> raise ValueError(\\'multi\\\\n line\\\\ndetail\\')\\nTraceback (most recent call last):\\n File \"\", line 1, in \\nValueError: multi\\n line\\ndetail\\n\\nThe last three lines (starting with ValueError) are compared against the exception’s type and detail, and the rest are ignored.\\n\\nBest practice is to omit the traceback stack, unless it adds significant documentation value to the example. So the last example is probably better as:\\n\\n>>> raise ValueError(\\'multi\\\\n line\\\\ndetail\\')\\nTraceback (most recent call last):\\n ...\\nValueError: multi\\n line\\ndetail\\n\\nNote that tracebacks are treated very specially. In particular, in the rewritten example, the use of ... is independent of doctest’s ELLIPSIS option. The ellipsis in that example could be left out, or could just as well be three (or three hundred) commas or digits, or an indented transcript of a Monty Python skit.\\n\\nSome details you should read once, but won’t need to remember:\\n\\nDoctest can’t guess whether your expected output came from an exception traceback or from ordinary printing. So, e.g., an example that expects ValueError: 42 is prime will pass whether ValueError is actually raised or if the example merely prints that traceback text. In practice, ordinary output rarely begins with a traceback header line, so this doesn’t create real problems.\\n\\nEach line of the traceback stack (if present) must be indented further than the first line of the example, or start with a non-alphanumeric character. The first line following the traceback header indented the same and starting with an alphanumeric is taken to be the start of the exception detail. Of course this does the right thing for genuine tracebacks.\\n\\nWhen the IGNORE_EXCEPTION_DETAIL doctest option is specified, everything following the leftmost colon and any module information in the exception name is ignored.\\n\\nThe interactive shell omits the traceback header line for some SyntaxErrors. But doctest uses the traceback header line to distinguish exceptions from non-exceptions. So in the rare case where you need to test a SyntaxError that omits the traceback header, you will need to manually add the traceback header line to your test example.\\n\\nFor some exceptions, Python displays the position of the error using ^ markers and tildes:\\n\\n>>> 1 + None\\n File \"\", line 1\\n 1 + None\\n ~~^~~~~~\\nTypeError: unsupported operand type(s) for +: \\'int\\' and \\'NoneType\\'\\n\\nSince the lines showing the position of the error come before the exception type and detail, they are not checked by doctest. For example, the following test would pass, even though it puts the ^ marker in the wrong location:\\n\\n>>> 1 + None\\n File \"\", line 1\\n 1 + None\\n ^~~~~~~~\\nTypeError: unsupported operand type(s) for +: \\'int\\' and \\'NoneType\\'\\n\\nOption Flags¶\\n\\nA number of option flags control various aspects of doctest’s behavior. Symbolic names for the flags are supplied as module constants, which can be bitwise ORed together and passed to various functions. The names can also be used in doctest directives, and may be passed to the doctest command line interface via the -o option.\\n\\nThe first group of options define test semantics, controlling aspects of how doctest decides whether actual output matches an example’s expected output:\\n\\nThe second group of options controls how test failures are reported:\\n\\nThere is also a way to register new option flag names, though this isn’t useful unless you intend to extend doctest internals via subclassing:\\n\\nDirectives¶\\n\\nDoctest directives may be used to modify the option flags for an individual example. Doctest directives are special Python comments following an example’s source code:\\n\\ndirective: \"#\" \"doctest:\" directive_options\\ndirective_options: directive_option (\",\" directive_option)*\\ndirective_option: on_or_off directive_option_name\\non_or_off: \"+\" | \"-\"\\ndirective_option_name: \"DONT_ACCEPT_BLANKLINE\" | \"NORMALIZE_WHITESPACE\" | ...\\n\\nWhitespace is not allowed between the + or - and the directive option name. The directive option name can be any of the option flag names explained above.\\n\\nAn example’s doctest directives modify doctest’s behavior for that single example. Use + to enable the named behavior, or - to disable it.\\n\\nFor example, this test passes:\\n\\n>>> print(list(range(20))) # doctest: +NORMALIZE_WHITESPACE\\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9,\\n10, 11, 12, 13, 14, 15, 16, 17, 18, 19]\\n\\nWithout the directive it would fail, both because the actual output doesn’t have two blanks before the single-digit list elements, and because the actual output is on a single line. This test also passes, and also requires a directive to do so:\\n\\n>>> print(list(range(20))) # doctest: +ELLIPSIS\\n[0, 1, ..., 18, 19]\\n\\nMultiple directives can be used on a single physical line, separated by commas:\\n\\n>>> print(list(range(20))) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE\\n[0, 1, ..., 18, 19]\\n\\nIf multiple directive comments are used for a single example, then they are combined:\\n\\n>>> print(list(range(20))) # doctest: +ELLIPSIS\\n... # doctest: +NORMALIZE_WHITESPACE\\n[0, 1, ..., 18, 19]\\n\\nAs the previous example shows, you can add ... lines to your example containing only directives. This can be useful when an example is too long for a directive to comfortably fit on the same line:\\n\\n>>> print(list(range(5)) + list(range(10, 20)) + list(range(30, 40)))\\n... # doctest: +ELLIPSIS\\n[0, ..., 4, 10, ..., 19, 30, ..., 39]\\n\\nNote that since all options are disabled by default, and directives apply only to the example they appear in, enabling options (via + in a directive) is usually the only meaningful choice. However, option flags can also be passed to functions that run doctests, establishing different defaults. In such cases, disabling an option via - in a directive can be useful.\\n\\nWarnings¶\\n\\ndoctest 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\\n\\n>>> foo()\\n{\"spam\", \"eggs\"}\\n\\nis vulnerable! One workaround is to do\\n\\n>>> foo() == {\"spam\", \"eggs\"}\\nTrue\\n\\ninstead. Another is to do\\n\\n>>> d = sorted(foo())\\n>>> d\\n[\\'eggs\\', \\'spam\\']\\n\\nThere are others, but you get the idea.\\n\\nAnother bad idea is to print things that embed an object address, like\\n\\n>>> id(1.0) # certain to fail some of the time\\n7948648\\n>>> class C: pass\\n>>> C() # the default repr() for instances embeds an address\\n\\n\\nThe ELLIPSIS directive gives a nice approach for the last example:\\n\\n>>> C() # doctest: +ELLIPSIS\\n\\n\\nFloating-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.\\n\\n>>> 1000**0.1 # risky\\n1.9952623149688797\\n>>> round(1000**0.1, 9) # safer\\n1.995262315\\n>>> print(f\\'{1000**0.1:.4f}\\') # much safer\\n1.9953\\n\\nNumbers of the form I/2.**J are safe across all platforms, and I often contrive doctest examples to produce numbers of that form:\\n\\n>>> 3./4 # utterly safe\\n0.75\\n\\nSimple fractions are also easier for people to understand, and that makes for better documentation.\\n\\nBasic API¶\\n\\nThe functions testmod() and testfile() provide a simple interface to doctest that should be sufficient for most basic uses. For a less formal introduction to these two functions, see sections Simple Usage: Checking Examples in Docstrings and Simple Usage: Checking Examples in a Text File.\\n\\nUnittest API¶\\n\\nAs your collection of doctest’ed modules grows, you’ll want a way to run all their doctests systematically. doctest provides two functions that can be used to create unittest test suites from modules and text files containing doctests. To integrate with unittest test discovery, include a load_tests function in your test module:\\n\\nimport unittest\\nimport doctest\\nimport my_module_with_doctests\\n\\ndef load_tests(loader, tests, ignore):\\n tests.addTests(doctest.DocTestSuite(my_module_with_doctests))\\n return tests\\n\\nThere are two main functions for creating unittest.TestSuite instances from text files and modules with doctests:\\n\\nUnder the covers, DocTestSuite() creates a unittest.TestSuite out of doctest.DocTestCase instances, and DocTestCase is a subclass of unittest.TestCase. DocTestCase isn’t documented here (it’s an internal detail), but studying its code can answer questions about the exact details of unittest integration.\\n\\nSimilarly, DocFileSuite() creates a unittest.TestSuite out of doctest.DocFileCase instances, and DocFileCase is a subclass of DocTestCase.\\n\\nSo both ways of creating a unittest.TestSuite run instances of DocTestCase. This is important for a subtle reason: when you run doctest functions yourself, you can control the doctest options in use directly, by passing option flags to doctest functions. However, if you’re writing a unittest framework, unittest ultimately controls when and how tests get run. The framework author typically wants to control doctest reporting options (perhaps, e.g., specified by command line options), but there’s no way to pass options through unittest to doctest test runners.\\n\\nFor this reason, doctest also supports a notion of doctest reporting flags specific to unittest support, via this function:\\n\\nAdvanced API¶\\n\\nThe basic API is a simple wrapper that’s intended to make doctest easy to use. It is fairly flexible, and should meet most users’ needs; however, if you require more fine-grained control over testing, or wish to extend doctest’s capabilities, then you should use the advanced API.\\n\\nThe advanced API revolves around two container classes, which are used to store the interactive examples extracted from doctest cases:\\n\\nExample: A single Python statement, paired with its expected output.\\n\\nDocTest: A collection of Examples, typically extracted from a single docstring or text file.\\n\\nAdditional processing classes are defined to find, parse, and run, and check doctest examples:\\n\\nDocTestFinder: Finds all docstrings in a given module, and uses a DocTestParser to create a DocTest from every docstring that contains interactive examples.\\n\\nDocTestParser: Creates a DocTest object from a string (such as an object’s docstring).\\n\\nDocTestRunner: Executes the examples in a DocTest, and uses an OutputChecker to verify their output.\\n\\nOutputChecker: Compares the actual output from a doctest example with the expected output, and decides whether they match.\\n\\nThe relationships among these processing classes are summarized in the following diagram:\\n\\n list of:\\n+------+ +---------+\\n|module| --DocTestFinder-> | DocTest | --DocTestRunner-> results\\n+------+ | ^ +---------+ | ^ (printed)\\n | | | Example | | |\\n v | | ... | v |\\n DocTestParser | Example | OutputChecker\\n +---------+\\n\\nDocTest Objects¶\\n\\nExample Objects¶\\n\\nDocTestFinder objects¶\\n\\nDocTestParser objects¶\\n\\nTestResults objects¶\\n\\nDocTestRunner objects¶\\n\\nOutputChecker objects¶\\n\\nDebugging¶\\n\\nDoctest provides several mechanisms for debugging doctest examples:\\n\\nSeveral functions convert doctests to executable Python programs, which can be run under the Python debugger, pdb.\\n\\nThe DebugRunner class is a subclass of DocTestRunner that raises an exception for the first failing example, containing information about that example. This information can be used to perform post-mortem debugging on the example.\\n\\nThe unittest cases generated by DocTestSuite() support the debug() method defined by unittest.TestCase.\\n\\nYou can add a call to pdb.set_trace() in a doctest example, and you’ll drop into the Python debugger when that line is executed. Then you can inspect current values of variables, and so on. For example, suppose a.py contains just this module docstring:\\n\\n\"\"\"\\n>>> def f(x):\\n... g(x*2)\\n>>> def g(x):\\n... print(x+3)\\n... import pdb; pdb.set_trace()\\n>>> f(3)\\n9\\n\"\"\"\\n\\nThen an interactive Python session may look like this:\\n\\n>>> import a, doctest\\n>>> doctest.testmod(a)\\n--Return--\\n> (3)g()->None\\n-> import pdb; pdb.set_trace()\\n(Pdb) list\\n 1 def g(x):\\n 2 print(x+3)\\n 3 -> import pdb; pdb.set_trace()\\n[EOF]\\n(Pdb) p x\\n6\\n(Pdb) step\\n--Return--\\n> (2)f()->None\\n-> g(x*2)\\n(Pdb) list\\n 1 def f(x):\\n 2 -> g(x*2)\\n[EOF]\\n(Pdb) p x\\n3\\n(Pdb) step\\n--Return--\\n> (1)?()->None\\n-> f(3)\\n(Pdb) cont\\n(0, 3)\\n>>>\\n\\nFunctions that convert doctests to Python code, and possibly run the synthesized code under the debugger:\\n\\nThe DebugRunner class, and the special exceptions it may raise, are of most interest to testing framework authors, and will only be sketched here. See the source code, and especially DebugRunner’s docstring (which is a doctest!) for more details:\\n\\nThere are two exceptions that may be raised by DebugRunner instances:\\n\\nDocTestFailure defines the following attributes:\\n\\nUnexpectedException defines the following attributes:\\n\\nSoapbox¶\\n\\nAs mentioned in the introduction, doctest has grown to have three primary uses:\\n\\nChecking examples in docstrings.\\n\\nRegression testing.\\n\\nExecutable documentation / literate testing.\\n\\nThese uses have different requirements, and it is important to distinguish them. In particular, filling your docstrings with obscure test cases makes for bad documentation.\\n\\nWhen 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 doctest examples stops working after a “harmless” change.\\n\\nDoctest also makes an excellent tool for regression testing, especially if you don’t skimp on explanatory text. By interleaving prose and examples, it becomes much easier to keep track of what’s actually being tested, and why. When a test fails, good prose can make it much easier to figure out what the problem is, and how it should be fixed. It’s true that you could write extensive comments in code-based testing, but few programmers do. Many have found that using doctest approaches instead leads to much clearer tests. Perhaps this is simply because doctest makes writing prose a little easier than writing code, while writing comments in code is a little harder. I think it goes deeper than just that: the natural attitude when writing a doctest-based test is that you want to explain the fine points of your software, and illustrate them with examples. This in turn naturally leads to test files that start with the simplest features, and logically progress to complications and edge cases. A coherent narrative is the result, instead of a collection of isolated functions that test isolated bits of functionality seemingly at random. It’s a different attitude, and produces different results, blurring the distinction between testing and explaining.\\n\\nRegression testing is best confined to dedicated objects or files. There are several options for organizing tests:\\n\\nWrite text files containing test cases as interactive examples, and test the files using testfile() or DocFileSuite(). This is recommended, although is easiest to do for new projects, designed from the start to use doctest.\\n\\nDefine functions named _regrtest_topic that consist of single docstrings, containing test cases for the named topics. These functions can be included in the same file as the module, or separated out into a separate test file.\\n\\nDefine a __test__ dictionary mapping from regression test topics to docstrings containing test cases.\\n\\nWhen you have placed your tests in a module, the module can itself be the test runner. When a test fails, you can arrange for your test runner to re-run only the failing doctest while you debug the problem. Here is a minimal example of such a test runner:\\n\\nif __name__ == \\'__main__\\':\\n import doctest\\n flags = doctest.REPORT_NDIFF|doctest.FAIL_FAST\\n if len(sys.argv) > 1:\\n name = sys.argv[1]\\n if name in globals():\\n obj = globals()[name]\\n else:\\n obj = __test__[name]\\n doctest.run_docstring_examples(obj, globals(), name=name,\\n optionflags=flags)\\n else:\\n fail, total = doctest.testmod(optionflags=flags)\\n print(f\"{fail} failures out of {total} tests\")\\n\\nFootnotes\\n\\n[1]\\n\\nExamples containing both expected output and an exception are not supported. Trying to guess where one ends and the other begins is too error-prone, and that also makes for a confusing test.\\n\\nTable of Contents\\n\\ndoctest — Test interactive Python examples\\n\\nSimple Usage: Checking Examples in Docstrings\\n\\nSimple Usage: Checking Examples in a Text File\\n\\nCommand-line Usage\\n\\nHow It Works\\n\\nWhich Docstrings Are Examined?\\n\\nHow are Docstring Examples Recognized?\\n\\nWhat’s the Execution Context?\\n\\nWhat About Exceptions?\\n\\nOption Flags\\n\\nDirectives\\n\\nWarnings\\n\\nBasic API\\n\\nUnittest API\\n\\nAdvanced API\\n\\nDocTest Objects\\n\\nExample Objects\\n\\nDocTestFinder objects\\n\\nDocTestParser objects\\n\\nTestResults objects\\n\\nDocTestRunner objects\\n\\nOutputChecker objects\\n\\nDebugging\\n\\nSoapbox\\n\\nPrevious topic\\n\\nPython Development Mode\\n\\nNext topic\\n\\nunittest — Unit testing framework\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nDevelopment Tools »\\n\\ndoctest — Test interactive Python examples\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\email.charset.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nemail — An email and MIME handling package »\\n\\nemail.charset: Representing character sets\\n\\n|\\n\\nemail.charset: Representing character sets¶\\n\\nSource code: Lib/email/charset.py\\n\\nThis module is part of the legacy (Compat32) email API. In the new API only the aliases table is used.\\n\\nThe remaining text in this section is the original documentation of the module.\\n\\nThis module provides a class Charset for representing character sets and character set conversions in email messages, as well as a character set registry and several convenience methods for manipulating this registry. Instances of Charset are used in several other modules within the email package.\\n\\nImport this class from the email.charset module.\\n\\nThe email.charset module also provides the following functions for adding new entries to the global character set, alias, and codec registries:\\n\\nPrevious topic\\n\\nemail.header: Internationalized headers\\n\\nNext topic\\n\\nemail.encoders: Encoders\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nemail — An email and MIME handling package »\\n\\nemail.charset: Representing character sets\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\email.compat32-message.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nemail — An email and MIME handling package »\\n\\nemail.message.Message: Representing an email message using the compat32 API\\n\\n|\\n\\nemail.message.Message: Representing an email message using the compat32 API¶\\n\\nThe Message class is very similar to the 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 EmailMessage class, are not recommended unless you are dealing with legacy code.\\n\\nThe philosophy and structure of the two classes is otherwise the same.\\n\\nThis document describes the behavior under the default (for Message) policy Compat32. If you are going to use another policy, you should be using the EmailMessage class instead.\\n\\nAn email message consists of headers and a payload. Headers must be RFC 5322 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 multipart/* or message/rfc822.\\n\\nThe conceptual model provided by a 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.\\n\\nThe 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 From_ header. The payload is either a string or bytes, in the case of simple message objects, or a list of Message objects, for MIME container documents (e.g. multipart/* and message/rfc822).\\n\\nHere are the methods of the Message class:\\n\\nPrevious topic\\n\\nemail: Examples\\n\\nNext topic\\n\\nemail.mime: Creating email and MIME objects from scratch\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nemail — An email and MIME handling package »\\n\\nemail.message.Message: Representing an email message using the compat32 API\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\email.contentmanager.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nemail — An email and MIME handling package »\\n\\nemail.contentmanager: Managing MIME Content\\n\\n|\\n\\nemail.contentmanager: Managing MIME Content¶\\n\\nSource code: Lib/email/contentmanager.py\\n\\nAdded in version 3.6: [1]\\n\\nContent Manager Instances¶\\n\\nCurrently the email package provides only one concrete content manager, raw_data_manager, although more may be added in the future. raw_data_manager is the content_manager provided by EmailPolicy and its derivatives.\\n\\nFootnotes\\n\\n[1]\\n\\nOriginally added in 3.4 as a provisional module\\n\\nTable of Contents\\n\\nemail.contentmanager: Managing MIME Content\\n\\nContent Manager Instances\\n\\nPrevious topic\\n\\nemail.headerregistry: Custom Header Objects\\n\\nNext topic\\n\\nemail: Examples\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nemail — An email and MIME handling package »\\n\\nemail.contentmanager: Managing MIME Content\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\email.encoders.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nemail — An email and MIME handling package »\\n\\nemail.encoders: Encoders\\n\\n|\\n\\nemail.encoders: Encoders¶\\n\\nSource code: Lib/email/encoders.py\\n\\nThis module is part of the legacy (Compat32) email API. In the new API the functionality is provided by the cte parameter of the set_content() method.\\n\\nThis module is deprecated in Python 3. The functions provided here should not be called explicitly since the MIMEText class sets the content type and CTE header using the _subtype and _charset values passed during the instantiation of that class.\\n\\nThe remaining text in this section is the original documentation of the module.\\n\\nWhen creating Message objects from scratch, you often need to encode the payloads for transport through compliant mail servers. This is especially true for image/* and text/* type messages containing binary data.\\n\\nThe email package provides some convenient encoders in its encoders module. These encoders are actually used by the MIMEAudio and 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 Content-Transfer-Encoding header as appropriate.\\n\\nNote that these functions are not meaningful for a multipart message. They must be applied to individual subparts instead, and will raise a TypeError if passed a message whose type is multipart.\\n\\nHere are the encoding functions provided:\\n\\nFootnotes\\n\\n[1]\\n\\nNote that encoding with encode_quopri() also encodes all tabs and space characters in the data.\\n\\nPrevious topic\\n\\nemail.charset: Representing character sets\\n\\nNext topic\\n\\nemail.utils: Miscellaneous utilities\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nemail — An email and MIME handling package »\\n\\nemail.encoders: Encoders\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\email.errors.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nemail — An email and MIME handling package »\\n\\nemail.errors: Exception and Defect classes\\n\\n|\\n\\nemail.errors: Exception and Defect classes¶\\n\\nSource code: Lib/email/errors.py\\n\\nThe following exception classes are defined in the email.errors module:\\n\\nHere is the list of the defects that the FeedParser can find while parsing messages. Note that the defects are added to the message where the problem was found, so for example, if a message nested inside a multipart/alternative had a malformed header, that nested message object would have a defect, but the containing messages would not.\\n\\nAll defect classes are subclassed from email.errors.MessageDefect.\\n\\nPrevious topic\\n\\nemail.policy: Policy Objects\\n\\nNext topic\\n\\nemail.headerregistry: Custom Header Objects\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nemail — An email and MIME handling package »\\n\\nemail.errors: Exception and Defect classes\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\email.examples.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nemail — An email and MIME handling package »\\n\\nemail: Examples\\n\\n|\\n\\nemail: Examples¶\\n\\nHere are a few examples of how to use the email package to read, write, and send simple email messages, as well as more complex MIME messages.\\n\\nFirst, let’s see how to create and send a simple text message (both the text content and the addresses may contain unicode characters):\\n\\n# Import smtplib for the actual sending function\\nimport smtplib\\n\\n# Import the email modules we\\'ll need\\nfrom email.message import EmailMessage\\n\\n# Open the plain text file whose name is in textfile for reading.\\nwith open(textfile) as fp:\\n # Create a text/plain message\\n msg = EmailMessage()\\n msg.set_content(fp.read())\\n\\n# me == the sender\\'s email address\\n# you == the recipient\\'s email address\\nmsg[\\'Subject\\'] = f\\'The contents of {textfile}\\'\\nmsg[\\'From\\'] = me\\nmsg[\\'To\\'] = you\\n\\n# Send the message via our own SMTP server.\\ns = smtplib.SMTP(\\'localhost\\')\\ns.send_message(msg)\\ns.quit()\\n\\nParsing RFC 822 headers can easily be done by the using the classes from the parser module:\\n\\n# Import the email modules we\\'ll need\\n#from email.parser import BytesParser\\nfrom email.parser import Parser\\nfrom email.policy import default\\n\\n# If the e-mail headers are in a file, uncomment these two lines:\\n# with open(messagefile, \\'rb\\') as fp:\\n# headers = BytesParser(policy=default).parse(fp)\\n\\n# Or for parsing headers in a string (this is an uncommon operation), use:\\nheaders = Parser(policy=default).parsestr(\\n \\'From: Foo Bar \\\\n\\'\\n \\'To: \\\\n\\'\\n \\'Subject: Test message\\\\n\\'\\n \\'\\\\n\\'\\n \\'Body would go here\\\\n\\')\\n\\n# Now the header items can be accessed as a dictionary:\\nprint(\\'To: {}\\'.format(headers[\\'to\\']))\\nprint(\\'From: {}\\'.format(headers[\\'from\\']))\\nprint(\\'Subject: {}\\'.format(headers[\\'subject\\']))\\n\\n# You can also access the parts of the addresses:\\nprint(\\'Recipient username: {}\\'.format(headers[\\'to\\'].addresses[0].username))\\nprint(\\'Sender name: {}\\'.format(headers[\\'from\\'].addresses[0].display_name))\\n\\nHere’s an example of how to send a MIME message containing a bunch of family pictures that may be residing in a directory:\\n\\n# Import smtplib for the actual sending function.\\nimport smtplib\\n\\n# Here are the email package modules we\\'ll need.\\nfrom email.message import EmailMessage\\n\\n# Create the container email message.\\nmsg = EmailMessage()\\nmsg[\\'Subject\\'] = \\'Our family reunion\\'\\n# me == the sender\\'s email address\\n# family = the list of all recipients\\' email addresses\\nmsg[\\'From\\'] = me\\nmsg[\\'To\\'] = \\', \\'.join(family)\\nmsg.preamble = \\'You will not see this in a MIME-aware mail reader.\\\\n\\'\\n\\n# Open the files in binary mode. You can also omit the subtype\\n# if you want MIMEImage to guess it.\\nfor file in pngfiles:\\n with open(file, \\'rb\\') as fp:\\n img_data = fp.read()\\n msg.add_attachment(img_data, maintype=\\'image\\',\\n subtype=\\'png\\')\\n\\n# Send the email via our own SMTP server.\\nwith smtplib.SMTP(\\'localhost\\') as s:\\n s.send_message(msg)\\n\\nHere’s an example of how to send the entire contents of a directory as an email message: [1]\\n\\n#!/usr/bin/env python3\\n\\n\"\"\"Send the contents of a directory as a MIME message.\"\"\"\\n\\nimport os\\nimport smtplib\\n# For guessing MIME type based on file name extension\\nimport mimetypes\\n\\nfrom argparse import ArgumentParser\\n\\nfrom email.message import EmailMessage\\nfrom email.policy import SMTP\\n\\n\\ndef main():\\n parser = ArgumentParser(description=\"\"\"\\\\\\nSend the contents of a directory as a MIME message.\\nUnless the -o option is given, the email is sent by forwarding to your local\\nSMTP server, which then does the normal delivery process. Your local machine\\nmust be running an SMTP server.\\n\"\"\")\\n parser.add_argument(\\'-d\\', \\'--directory\\',\\n help=\"\"\"Mail the contents of the specified directory,\\n otherwise use the current directory. Only the regular\\n files in the directory are sent, and we don\\'t recurse to\\n subdirectories.\"\"\")\\n parser.add_argument(\\'-o\\', \\'--output\\',\\n metavar=\\'FILE\\',\\n help=\"\"\"Print the composed message to FILE instead of\\n sending the message to the SMTP server.\"\"\")\\n parser.add_argument(\\'-s\\', \\'--sender\\', required=True,\\n help=\\'The value of the From: header (required)\\')\\n parser.add_argument(\\'-r\\', \\'--recipient\\', required=True,\\n action=\\'append\\', metavar=\\'RECIPIENT\\',\\n default=[], dest=\\'recipients\\',\\n help=\\'A To: header value (at least one required)\\')\\n args = parser.parse_args()\\n directory = args.directory\\n if not directory:\\n directory = \\'.\\'\\n # Create the message\\n msg = EmailMessage()\\n msg[\\'Subject\\'] = f\\'Contents of directory {os.path.abspath(directory)}\\'\\n msg[\\'To\\'] = \\', \\'.join(args.recipients)\\n msg[\\'From\\'] = args.sender\\n msg.preamble = \\'You will not see this in a MIME-aware mail reader.\\\\n\\'\\n\\n for filename in os.listdir(directory):\\n path = os.path.join(directory, filename)\\n if not os.path.isfile(path):\\n continue\\n # Guess the content type based on the file\\'s extension. Encoding\\n # will be ignored, although we should check for simple things like\\n # gzip\\'d or compressed files.\\n ctype, encoding = mimetypes.guess_file_type(path)\\n if ctype is None or encoding is not None:\\n # No guess could be made, or the file is encoded (compressed), so\\n # use a generic bag-of-bits type.\\n ctype = \\'application/octet-stream\\'\\n maintype, subtype = ctype.split(\\'/\\', 1)\\n with open(path, \\'rb\\') as fp:\\n msg.add_attachment(fp.read(),\\n maintype=maintype,\\n subtype=subtype,\\n filename=filename)\\n # Now send or store the message\\n if args.output:\\n with open(args.output, \\'wb\\') as fp:\\n fp.write(msg.as_bytes(policy=SMTP))\\n else:\\n with smtplib.SMTP(\\'localhost\\') as s:\\n s.send_message(msg)\\n\\n\\nif __name__ == \\'__main__\\':\\n main()\\n\\nHere’s an example of how to unpack a MIME message like the one above, into a directory of files:\\n\\n#!/usr/bin/env python3\\n\\n\"\"\"Unpack a MIME message into a directory of files.\"\"\"\\n\\nimport os\\nimport email\\nimport mimetypes\\n\\nfrom email.policy import default\\n\\nfrom argparse import ArgumentParser\\n\\n\\ndef main():\\n parser = ArgumentParser(description=\"\"\"\\\\\\nUnpack a MIME message into a directory of files.\\n\"\"\")\\n parser.add_argument(\\'-d\\', \\'--directory\\', required=True,\\n help=\"\"\"Unpack the MIME message into the named\\n directory, which will be created if it doesn\\'t already\\n exist.\"\"\")\\n parser.add_argument(\\'msgfile\\')\\n args = parser.parse_args()\\n\\n with open(args.msgfile, \\'rb\\') as fp:\\n msg = email.message_from_binary_file(fp, policy=default)\\n\\n try:\\n os.mkdir(args.directory)\\n except FileExistsError:\\n pass\\n\\n counter = 1\\n for part in msg.walk():\\n # multipart/* are just containers\\n if part.get_content_maintype() == \\'multipart\\':\\n continue\\n # Applications should really sanitize the given filename so that an\\n # email message can\\'t be used to overwrite important files\\n filename = part.get_filename()\\n if not filename:\\n ext = mimetypes.guess_extension(part.get_content_type())\\n if not ext:\\n # Use a generic bag-of-bits extension\\n ext = \\'.bin\\'\\n filename = f\\'part-{counter:03d}{ext}\\'\\n counter += 1\\n with open(os.path.join(args.directory, filename), \\'wb\\') as fp:\\n fp.write(part.get_payload(decode=True))\\n\\n\\nif __name__ == \\'__main__\\':\\n main()\\n\\nHere’s an example of how to create an HTML message with an alternative plain text version. To make things a bit more interesting, we include a related image in the html part, and we save a copy of what we are going to send to disk, as well as sending it.\\n\\n#!/usr/bin/env python3\\n\\nimport smtplib\\n\\nfrom email.message import EmailMessage\\nfrom email.headerregistry import Address\\nfrom email.utils import make_msgid\\n\\n# Create the base text message.\\nmsg = EmailMessage()\\nmsg[\\'Subject\\'] = \"Pourquoi pas des asperges pour ce midi ?\"\\nmsg[\\'From\\'] = Address(\"Pepé Le Pew\", \"pepe\", \"example.com\")\\nmsg[\\'To\\'] = (Address(\"Penelope Pussycat\", \"penelope\", \"example.com\"),\\n Address(\"Fabrette Pussycat\", \"fabrette\", \"example.com\"))\\nmsg.set_content(\"\"\"\\\\\\nSalut!\\n\\nCette recette [1] sera sûrement un très bon repas.\\n\\n[1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718\\n\\n--Pepé\\n\"\"\")\\n\\n# Add the html version. This converts the message into a multipart/alternative\\n# container, with the original text message as the first part and the new html\\n# message as the second part.\\nasparagus_cid = make_msgid()\\nmsg.add_alternative(\"\"\"\\\\\\n\\n \\n \\n

Salut!

\\n

Cette\\n \\n recette\\n sera sûrement un très bon repas.\\n

\\n \\n \\n\\n\"\"\".format(asparagus_cid=asparagus_cid[1:-1]), subtype=\\'html\\')\\n# note that we needed to peel the <> off the msgid for use in the html.\\n\\n# Now add the related image to the html part.\\nwith open(\"roasted-asparagus.jpg\", \\'rb\\') as img:\\n msg.get_payload()[1].add_related(img.read(), \\'image\\', \\'jpeg\\',\\n cid=asparagus_cid)\\n\\n# Make a local copy of what we are going to send.\\nwith open(\\'outgoing.msg\\', \\'wb\\') as f:\\n f.write(bytes(msg))\\n\\n# Send the message via local SMTP server.\\nwith smtplib.SMTP(\\'localhost\\') as s:\\n s.send_message(msg)\\n\\nIf we were sent the message from the last example, here is one way we could process it:\\n\\nimport os\\nimport sys\\nimport tempfile\\nimport mimetypes\\nimport webbrowser\\n\\n# Import the email modules we\\'ll need\\nfrom email import policy\\nfrom email.parser import BytesParser\\n\\n\\ndef magic_html_parser(html_text, partfiles):\\n \"\"\"Return safety-sanitized html linked to partfiles.\\n\\n Rewrite the href=\"cid:....\" attributes to point to the filenames in partfiles.\\n Though not trivial, this should be possible using html.parser.\\n \"\"\"\\n raise NotImplementedError(\"Add the magic needed\")\\n\\n\\n# In a real program you\\'d get the filename from the arguments.\\nwith open(\\'outgoing.msg\\', \\'rb\\') as fp:\\n msg = BytesParser(policy=policy.default).parse(fp)\\n\\n# Now the header items can be accessed as a dictionary, and any non-ASCII will\\n# be converted to unicode:\\nprint(\\'To:\\', msg[\\'to\\'])\\nprint(\\'From:\\', msg[\\'from\\'])\\nprint(\\'Subject:\\', msg[\\'subject\\'])\\n\\n# If we want to print a preview of the message content, we can extract whatever\\n# the least formatted payload is and print the first three lines. Of course,\\n# if the message has no plain text part printing the first three lines of html\\n# is probably useless, but this is just a conceptual example.\\nsimplest = msg.get_body(preferencelist=(\\'plain\\', \\'html\\'))\\nprint()\\nprint(\\'\\'.join(simplest.get_content().splitlines(keepends=True)[:3]))\\n\\nans = input(\"View full message?\")\\nif ans.lower()[0] == \\'n\\':\\n sys.exit()\\n\\n# We can extract the richest alternative in order to display it:\\nrichest = msg.get_body()\\npartfiles = {}\\nif richest[\\'content-type\\'].maintype == \\'text\\':\\n if richest[\\'content-type\\'].subtype == \\'plain\\':\\n for line in richest.get_content().splitlines():\\n print(line)\\n sys.exit()\\n elif richest[\\'content-type\\'].subtype == \\'html\\':\\n body = richest\\n else:\\n print(\"Don\\'t know how to display {}\".format(richest.get_content_type()))\\n sys.exit()\\nelif richest[\\'content-type\\'].content_type == \\'multipart/related\\':\\n body = richest.get_body(preferencelist=(\\'html\\'))\\n for part in richest.iter_attachments():\\n fn = part.get_filename()\\n if fn:\\n extension = os.path.splitext(part.get_filename())[1]\\n else:\\n extension = mimetypes.guess_extension(part.get_content_type())\\n with tempfile.NamedTemporaryFile(suffix=extension, delete=False) as f:\\n f.write(part.get_content())\\n # again strip the <> to go from email form of cid to html form.\\n partfiles[part[\\'content-id\\'][1:-1]] = f.name\\nelse:\\n print(\"Don\\'t know how to display {}\".format(richest.get_content_type()))\\n sys.exit()\\nwith tempfile.NamedTemporaryFile(mode=\\'w\\', delete=False) as f:\\n f.write(magic_html_parser(body.get_content(), partfiles))\\nwebbrowser.open(f.name)\\nos.remove(f.name)\\nfor fn in partfiles.values():\\n os.remove(fn)\\n\\n# Of course, there are lots of email messages that could break this simple\\n# minded program, but it will handle the most common ones.\\n\\nUp to the prompt, the output from the above is:\\n\\nTo: Penelope Pussycat , Fabrette Pussycat \\nFrom: Pepé Le Pew \\nSubject: Pourquoi pas des asperges pour ce midi ?\\n\\nSalut!\\n\\nCette recette [1] sera sûrement un très bon repas.\\n\\nFootnotes\\n\\n[1]\\n\\nThanks to Matthew Dixon Cowles for the original inspiration and examples.\\n\\nPrevious topic\\n\\nemail.contentmanager: Managing MIME Content\\n\\nNext topic\\n\\nemail.message.Message: Representing an email message using the compat32 API\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nemail — An email and MIME handling package »\\n\\nemail: Examples\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\email.generator.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nemail — An email and MIME handling package »\\n\\nemail.generator: Generating MIME documents\\n\\n|\\n\\nemail.generator: Generating MIME documents¶\\n\\nSource code: Lib/email/generator.py\\n\\nOne 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 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.\\n\\nAs with the 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 policy is used for both. That is, parsing the serialized byte stream via the BytesParser class and then regenerating the serialized byte stream using BytesGenerator should produce output identical to the input [1]. (On the other hand, using the generator on an EmailMessage constructed by program may result in changes to the EmailMessage object as defaults are filled in.)\\n\\nThe 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”.\\n\\nTo accommodate reproducible processing of SMIME-signed messages Generator disables header folding for message parts of type multipart/signed and all subparts.\\n\\nAs a convenience, EmailMessage provides the methods as_bytes() and bytes(aMessage) (a.k.a. __bytes__()), which simplify the generation of a serialized binary representation of a message object. For more detail, see email.message.\\n\\nBecause strings cannot represent binary data, the Generator class must convert any binary data in any message it flattens to an ASCII compatible format, by converting them to an ASCII compatible Content-Transfer_Encoding. Using the terminology of the email RFCs, you can think of this as Generator serializing to an I/O stream that is not “8 bit clean”. In other words, most applications will want to be using BytesGenerator, and not Generator.\\n\\nAs a convenience, EmailMessage provides the methods as_string() and str(aMessage) (a.k.a. __str__()), which simplify the generation of a formatted string representation of a message object. For more detail, see email.message.\\n\\nThe email.generator module also provides a derived class, DecodedGenerator, which is like the Generator base class, except that non-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.\\n\\nFootnotes\\n\\n[1]\\n\\nThis statement assumes that you use the appropriate setting for unixfrom, and that there are no email.policy settings calling for automatic adjustments (for example, refold_source must be 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.\\n\\nPrevious topic\\n\\nemail.parser: Parsing email messages\\n\\nNext topic\\n\\nemail.policy: Policy Objects\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nemail — An email and MIME handling package »\\n\\nemail.generator: Generating MIME documents\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\email.header.html'}, page_content=\"Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nemail — An email and MIME handling package »\\n\\nemail.header: Internationalized headers\\n\\n|\\n\\nemail.header: Internationalized headers¶\\n\\nSource code: Lib/email/header.py\\n\\nThis module is part of the legacy (Compat32) email API. In the current API encoding and decoding of headers is handled transparently by the dictionary-like API of the EmailMessage class. In addition to uses in legacy code, this module can be useful in applications that need to completely control the character sets used when encoding headers.\\n\\nThe remaining text in this section is the original documentation of the module.\\n\\nRFC 2822 is the base standard that describes the format of email messages. It derives from the older RFC 822 standard which came into widespread use at a time when most email was composed of ASCII characters only. RFC 2822 is a specification written assuming email contains only 7-bit ASCII characters.\\n\\nOf 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 RFC 2822-compliant format. These RFCs include RFC 2045, RFC 2046, RFC 2047, and RFC 2231. The email package supports these standards in its email.header and email.charset modules.\\n\\nIf you want to include non-ASCII characters in your email headers, say in the Subject or To fields, you should use the Header class and assign the field in the Message object to an instance of Header instead of using a string for the header value. Import the Header class from the email.header module. For example:\\n\\n>>> from email.message import Message\\n>>> from email.header import Header\\n>>> msg = Message()\\n>>> h = Header('p\\\\xf6stal', 'iso-8859-1')\\n>>> msg['Subject'] = h\\n>>> msg.as_string()\\n'Subject: =?iso-8859-1?q?p=F6stal?=\\\\n\\\\n'\\n\\nNotice here how we wanted the Subject field to contain a non-ASCII character? We did this by creating a Header instance and passing in the character set that the byte string was encoded in. When the subsequent Message instance was flattened, the Subject field was properly RFC 2047 encoded. MIME-aware mail readers would show this header using the embedded ISO-8859-1 character.\\n\\nHere is the Header class description:\\n\\nThe email.header module also provides the following convenient functions.\\n\\nPrevious topic\\n\\nemail.mime: Creating email and MIME objects from scratch\\n\\nNext topic\\n\\nemail.charset: Representing character sets\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nemail — An email and MIME handling package »\\n\\nemail.header: Internationalized headers\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.\"), Document(metadata={'source': '..\\\\..\\\\docs\\\\email.headerregistry.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nemail — An email and MIME handling package »\\n\\nemail.headerregistry: Custom Header Objects\\n\\n|\\n\\nemail.headerregistry: Custom Header Objects¶\\n\\nSource code: Lib/email/headerregistry.py\\n\\nAdded in version 3.6: [1]\\n\\nHeaders are represented by customized subclasses of str. The particular class used to represent a given header is determined by the header_factory of the policy in effect when the headers are created. This section documents the particular header_factory implemented by the email package for handling RFC 5322 compliant email messages, which not only provides customized header objects for various header types, but also provides an extension mechanism for applications to add their own custom header types.\\n\\nWhen using any of the policy objects derived from EmailPolicy, all headers are produced by HeaderRegistry and have BaseHeader as their last base class. Each header class has an additional base class that is determined by the type of the header. For example, many headers have the class UnstructuredHeader as their other base class. The specialized second class for a header is determined by the name of the header, using a lookup table stored in the HeaderRegistry. All of this is managed transparently for the typical application program, but interfaces are provided for modifying the default behavior for use by more complex applications.\\n\\nThe sections below first document the header base classes and their attributes, followed by the API for modifying the behavior of HeaderRegistry, and finally the support classes used to represent the data parsed from structured headers.\\n\\nMany of the above classes also have a Unique variant (for example, UniqueUnstructuredHeader). The only difference is that in the Unique variant, max_count is set to 1.\\n\\nThe 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.\\n\\nFootnotes\\n\\n[1]\\n\\nOriginally added in 3.3 as a provisional module\\n\\nPrevious topic\\n\\nemail.errors: Exception and Defect classes\\n\\nNext topic\\n\\nemail.contentmanager: Managing MIME Content\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nemail — An email and MIME handling package »\\n\\nemail.headerregistry: Custom Header Objects\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\email.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nemail — An email and MIME handling package\\n\\n|\\n\\nemail — An email and MIME handling package¶\\n\\nSource code: Lib/email/__init__.py\\n\\nThe email package is a library for managing email messages. It is specifically not designed to do any sending of email messages to SMTP (RFC 2821), NNTP, or other servers; those are functions of modules such as smtplib. The email package attempts to be as RFC-compliant as possible, supporting RFC 5322 and RFC 6532, as well as such MIME-related RFCs as RFC 2045, RFC 2046, RFC 2047, RFC 2183, and RFC 2231.\\n\\nThe 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.\\n\\nThe 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 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 EmailMessage API.\\n\\nThe other two major components of the package are the parser and the generator. The parser takes the serialized version of an email message (a stream of bytes) and converts it into a tree of EmailMessage objects. The generator takes an 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.)\\n\\nThe control component is the policy module. Every EmailMessage, every generator, and every parser has an associated policy object that controls its behavior. Usually an application only needs to specify the policy when an EmailMessage is created, either by directly instantiating an EmailMessage to create a new email, or by parsing an input stream using a parser. But the policy can be changed when the message is serialized using a 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.\\n\\nThe 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.\\n\\nThe following sections describe the functionality of the email package. We start with the message object model, which is the primary interface an application will use, and follow that with the parser and generator components. Then we cover the policy controls, which completes the treatment of the main components of the library.\\n\\nThe next three sections cover the exceptions the package may raise and the defects (non-compliance with the RFCs) that the parser may detect. Then we cover the headerregistry and the 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.\\n\\nFollowing those is a set of examples of using the fundamental parts of the APIs covered in the preceding sections.\\n\\nThe foregoing represent the modern (unicode friendly) API of the email package. The remaining sections, starting with the Message class, cover the legacy compat32 API that deals much more directly with the details of how email messages are represented. The 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 compat32 API for backward compatibility reasons.\\n\\nChanged in version 3.6: Docs reorganized and rewritten to promote the new EmailMessage/EmailPolicy API.\\n\\nContents of the email package documentation:\\n\\nemail.message: Representing an email message\\n\\nemail.parser: Parsing email messages\\n\\nFeedParser API\\n\\nParser API\\n\\nAdditional notes\\n\\nemail.generator: Generating MIME documents\\n\\nemail.policy: Policy Objects\\n\\nemail.errors: Exception and Defect classes\\n\\nemail.headerregistry: Custom Header Objects\\n\\nemail.contentmanager: Managing MIME Content\\n\\nContent Manager Instances\\n\\nemail: Examples\\n\\nLegacy API:\\n\\nemail.message.Message: Representing an email message using the compat32 API\\n\\nemail.mime: Creating email and MIME objects from scratch\\n\\nemail.header: Internationalized headers\\n\\nemail.charset: Representing character sets\\n\\nemail.encoders: Encoders\\n\\nemail.utils: Miscellaneous utilities\\n\\nemail.iterators: Iterators\\n\\nSee also\\n\\nPrevious topic\\n\\nInternet Data Handling\\n\\nNext topic\\n\\nemail.message: Representing an email message\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nemail — An email and MIME handling package\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\email.iterators.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nemail — An email and MIME handling package »\\n\\nemail.iterators: Iterators\\n\\n|\\n\\nemail.iterators: Iterators¶\\n\\nSource code: Lib/email/iterators.py\\n\\nIterating over a message object tree is fairly easy with the Message.walk method. The email.iterators module provides some useful higher level iterations over message object trees.\\n\\nThe following function has been added as a useful debugging tool. It should not be considered part of the supported public interface for the package.\\n\\nPrevious topic\\n\\nemail.utils: Miscellaneous utilities\\n\\nNext topic\\n\\njson — JSON encoder and decoder\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nemail — An email and MIME handling package »\\n\\nemail.iterators: Iterators\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\email.message.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nemail — An email and MIME handling package »\\n\\nemail.message: Representing an email message\\n\\n|\\n\\nemail.message: Representing an email message¶\\n\\nSource code: Lib/email/message.py\\n\\nAdded in version 3.6: [1]\\n\\nThe central class in the email package is the EmailMessage class, imported from the email.message module. It is the base class for the email object model. EmailMessage provides the core functionality for setting and querying header fields, for accessing message bodies, and for creating or modifying structured messages.\\n\\nAn email message consists of headers and a payload (which is also referred to as the content). Headers are RFC 5322 or RFC 6532 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 multipart/* or message/rfc822.\\n\\nThe conceptual model provided by an EmailMessage object is that of an ordered dictionary of headers coupled with a payload that represents the RFC 5322 body of the message, which might be a list of sub-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.\\n\\nThe 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.\\n\\nThe payload is either a string or bytes object, in the case of simple message objects, or a list of EmailMessage objects, for MIME container documents such as multipart/* and message/rfc822 message objects.\\n\\nFootnotes\\n\\n[1]\\n\\nOriginally added in 3.4 as a provisional module. Docs for legacy message class moved to email.message.Message: Representing an email message using the compat32 API.\\n\\n[2]\\n\\nThe EmailMessage class requires a policy that provides a content_manager attribute for content management methods like set_content() and get_content() to work. The legacy compat32 policy does not support these methods and should not be used with EmailMessage.\\n\\nPrevious topic\\n\\nemail — An email and MIME handling package\\n\\nNext topic\\n\\nemail.parser: Parsing email messages\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nemail — An email and MIME handling package »\\n\\nemail.message: Representing an email message\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\email.mime.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nemail — An email and MIME handling package »\\n\\nemail.mime: Creating email and MIME objects from scratch\\n\\n|\\n\\nemail.mime: Creating email and MIME objects from scratch¶\\n\\nSource code: Lib/email/mime/\\n\\nThis module is part of the legacy (Compat32) email API. Its functionality is partially replaced by the contentmanager in the new API, but in certain applications these classes may still be useful, even in non-legacy code.\\n\\nOrdinarily, you get a message object structure by passing a file or some text to a parser, which parses the text and returns the root message object. However you can also build a complete message structure from scratch, or even individual Message objects by hand. In fact, you can also take an existing structure and add new Message objects, move them around, etc. This makes a very convenient interface for slicing-and-dicing MIME messages.\\n\\nYou can create a new object structure by creating Message instances, adding attachments and all the appropriate headers manually. For MIME messages though, the email package provides some convenient subclasses to make things easier.\\n\\nHere are the classes:\\n\\nPrevious topic\\n\\nemail.message.Message: Representing an email message using the compat32 API\\n\\nNext topic\\n\\nemail.header: Internationalized headers\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nemail — An email and MIME handling package »\\n\\nemail.mime: Creating email and MIME objects from scratch\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\email.parser.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nemail — An email and MIME handling package »\\n\\nemail.parser: Parsing email messages\\n\\n|\\n\\nemail.parser: Parsing email messages¶\\n\\nSource code: Lib/email/parser.py\\n\\nMessage object structures can be created in one of two ways: they can be created from whole cloth by creating an EmailMessage object, adding headers using the dictionary interface, and adding payload(s) using set_content() and related methods, or they can be created by parsing a serialized representation of the email message.\\n\\nThe 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 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 True from its is_multipart() method, and the subparts can be accessed via the payload manipulation methods, such as get_body(), iter_parts(), and walk().\\n\\nThere are actually two parser interfaces available for use, the Parser API and the incremental FeedParser API. The 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. 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 FeedParser can consume and parse the message incrementally, and only returns the root object when you close the parser.\\n\\nNote 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 email package’s bundled parser and the EmailMessage class is embodied in the Policy class, so a custom parser can create message object trees any way it finds necessary by implementing custom versions of the appropriate Policy methods.\\n\\nFeedParser API¶\\n\\nThe BytesFeedParser, imported from the 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 BytesFeedParser can of course be used to parse an email message fully contained in a bytes-like object, string, or file, but the BytesParser API may be more convenient for such use cases. The semantics and results of the two parser APIs are identical.\\n\\nThe BytesFeedParser’s API is simple; you create an instance, feed it a bunch of bytes until there’s no more to feed it, then close the parser to retrieve the root message object. The BytesFeedParser is extremely accurate when parsing standards-compliant messages, and it does a very good job of parsing non-compliant messages, providing information about how a message was deemed broken. It will populate a message object’s defects attribute with a list of any problems it found in a message. See the email.errors module for the list of defects that it can find.\\n\\nHere is the API for the BytesFeedParser:\\n\\nParser API¶\\n\\nThe BytesParser class, imported from the 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 bytes-like object or file. The email.parser module also provides Parser for parsing strings, and header-only parsers, BytesHeaderParser and HeaderParser, which can be used if you’re only interested in the headers of the message. BytesHeaderParser and 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.\\n\\nSince creating a message object structure from a string or a file object is such a common task, four functions are provided as a convenience. They are available in the top-level email package namespace.\\n\\nHere’s an example of how you might use message_from_bytes() at an interactive Python prompt:\\n\\n>>> import email\\n>>> msg = email.message_from_bytes(myBytes)\\n\\nAdditional notes¶\\n\\nHere are some notes on the parsing semantics:\\n\\nMost non-multipart type messages are parsed as a single message object with a string payload. These objects will return False for is_multipart(), and iter_parts() will yield an empty list.\\n\\nAll 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 True for is_multipart(), and iter_parts() will yield a list of subparts.\\n\\nMost messages with a content type of message/* (such as message/delivery-status and message/rfc822) will also be parsed as container object containing a list payload of length 1. Their is_multipart() method will return True. The single element yielded by iter_parts() will be a sub-message object.\\n\\nSome non-standards-compliant messages may not be internally consistent about their multipart-edness. Such messages may have a Content-Type header of type multipart, but their is_multipart() method may return False. If such messages were parsed with the FeedParser, they will have an instance of the MultipartInvariantViolationDefect class in their defects attribute list. See email.errors for details.\\n\\nTable of Contents\\n\\nemail.parser: Parsing email messages\\n\\nFeedParser API\\n\\nParser API\\n\\nAdditional notes\\n\\nPrevious topic\\n\\nemail.message: Representing an email message\\n\\nNext topic\\n\\nemail.generator: Generating MIME documents\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nemail — An email and MIME handling package »\\n\\nemail.parser: Parsing email messages\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\email.policy.html'}, page_content=\"Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nemail — An email and MIME handling package »\\n\\nemail.policy: Policy Objects\\n\\n|\\n\\nemail.policy: Policy Objects¶\\n\\nAdded in version 3.3.\\n\\nSource code: Lib/email/policy.py\\n\\nThe email package’s prime focus is the handling of email messages as described by the various email and MIME RFCs. However, the general format of email messages (a block of header fields each consisting of a name followed by a colon followed by a value, the whole block followed by a blank line and an arbitrary ‘body’), is a format that has found utility outside of the realm of email. Some of these uses conform fairly closely to the main email RFCs, some do not. Even when working with email, there are times when it is desirable to break strict compliance with the RFCs, such as generating emails that interoperate with email servers that do not themselves follow the standards, or that implement extensions you want to use in ways that violate the standards.\\n\\nPolicy objects give the email package the flexibility to handle all these disparate use cases.\\n\\nA Policy object encapsulates a set of attributes and methods that control the behavior of various components of the email package during use. 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.\\n\\nThere is a default policy used by all classes in the email package. For all of the parser classes and the related convenience functions, and for the Message class, this is the Compat32 policy, via its corresponding pre-defined instance compat32. This policy provides for complete backward compatibility (in some cases, including bug compatibility) with the pre-Python3.3 version of the email package.\\n\\nThis default value for the policy keyword to EmailMessage is the EmailPolicy policy, via its pre-defined instance default.\\n\\nWhen a Message or EmailMessage object is created, it acquires a policy. If the message is created by a 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 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.\\n\\nThe default value for the policy keyword for the 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 parser module.\\n\\nThe first part of this documentation covers the features of Policy, an abstract base class that defines the features that are common to all policy objects, including 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 EmailPolicy and Compat32, which implement the hooks that provide the standard behavior and the backward compatible behavior and features, respectively.\\n\\nPolicy instances are immutable, but they can be cloned, accepting the same keyword arguments as the class constructor and returning a new Policy instance that is a copy of the original but with the specified attributes values changed.\\n\\nAs an example, the following code could be used to read an email message from a file on disk and pass it to the system sendmail program on a Unix system:\\n\\n>>> from email import message_from_binary_file\\n>>> from email.generator import BytesGenerator\\n>>> from email import policy\\n>>> from subprocess import Popen, PIPE\\n>>> with open('mymsg.txt', 'rb') as f:\\n... msg = message_from_binary_file(f, policy=policy.default)\\n...\\n>>> p = Popen(['sendmail', msg['To'].addresses[0]], stdin=PIPE)\\n>>> g = BytesGenerator(p.stdin, policy=msg.policy.clone(linesep='\\\\r\\\\n'))\\n>>> g.flatten(msg)\\n>>> p.stdin.close()\\n>>> rc = p.wait()\\n\\nHere we are telling BytesGenerator to use the RFC correct line separator characters when creating the binary string to feed into sendmail's stdin, where the default policy would use \\\\n line separators.\\n\\nSome email package methods accept a policy keyword argument, allowing the policy to be overridden for that method. For example, the following code uses the 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:\\n\\n>>> import os\\n>>> with open('converted.txt', 'wb') as f:\\n... f.write(msg.as_bytes(policy=msg.policy.clone(linesep=os.linesep)))\\n17\\n\\nPolicy objects can also be combined using the addition operator, producing a policy object whose settings are a combination of the non-default values of the summed objects:\\n\\n>>> compat_SMTP = policy.compat32.clone(linesep='\\\\r\\\\n')\\n>>> compat_strict = policy.compat32.clone(raise_on_defect=True)\\n>>> compat_strict_SMTP = compat_SMTP + compat_strict\\n\\nThis operation is not commutative; that is, the order in which the objects are added matters. To illustrate:\\n\\n>>> policy100 = policy.compat32.clone(max_line_length=100)\\n>>> policy80 = policy.compat32.clone(max_line_length=80)\\n>>> apolicy = policy100 + policy80\\n>>> apolicy.max_line_length\\n80\\n>>> apolicy = policy80 + policy100\\n>>> apolicy.max_line_length\\n100\\n\\nThe following instances of EmailPolicy provide defaults suitable for specific application domains. Note that in the future the behavior of these instances (in particular the HTTP instance) may be adjusted to conform even more closely to the RFCs relevant to their domains.\\n\\nWith all of these EmailPolicies, the effective API of the email package is changed from the Python 3.2 API in the following ways:\\n\\nSetting a header on a Message results in that header being parsed and a header object created.\\n\\nFetching a header value from a Message results in that header being parsed and a header object created and returned.\\n\\nAny 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.\\n\\nFrom the application view, this means that any header obtained through the 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.\\n\\nThe header objects and their attributes are described in headerregistry.\\n\\nFootnotes\\n\\n[1]\\n\\nOriginally added in 3.3 as a provisional feature.\\n\\nPrevious topic\\n\\nemail.generator: Generating MIME documents\\n\\nNext topic\\n\\nemail.errors: Exception and Defect classes\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nemail — An email and MIME handling package »\\n\\nemail.policy: Policy Objects\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.\"), Document(metadata={'source': '..\\\\..\\\\docs\\\\email.utils.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nemail — An email and MIME handling package »\\n\\nemail.utils: Miscellaneous utilities\\n\\n|\\n\\nemail.utils: Miscellaneous utilities¶\\n\\nSource code: Lib/email/utils.py\\n\\nThere are a couple of useful utilities provided in the email.utils module:\\n\\nThe remaining functions are part of the legacy (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.\\n\\nFootnotes\\n\\n[1]\\n\\nNote that the sign of the timezone offset is the opposite of the sign of the time.timezone variable for the same timezone; the latter variable follows the POSIX standard while this module follows RFC 2822.\\n\\nPrevious topic\\n\\nemail.encoders: Encoders\\n\\nNext topic\\n\\nemail.iterators: Iterators\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Data Handling »\\n\\nemail — An email and MIME handling package »\\n\\nemail.utils: Miscellaneous utilities\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\ensurepip.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nSoftware Packaging and Distribution »\\n\\nensurepip — Bootstrapping the pip installer\\n\\n|\\n\\nensurepip — Bootstrapping the pip installer¶\\n\\nAdded in version 3.4.\\n\\nSource code: Lib/ensurepip\\n\\nThe ensurepip package provides support for bootstrapping the pip installer into an existing Python installation or virtual environment. This bootstrapping approach reflects the fact that pip is an independent project with its own release cycle, and the latest available stable version is bundled with maintenance and feature releases of the CPython reference interpreter.\\n\\nIn most cases, end users of Python shouldn’t need to invoke this module directly (as pip should be bootstrapped by default), but it may be needed if installing pip was skipped when installing Python (or when creating a virtual environment) or after explicitly uninstalling pip.\\n\\nNote\\n\\nThis module does not access the internet. All of the components needed to bootstrap pip are included as internal parts of the package.\\n\\nThis is an 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 Requirements for optional modules.\\n\\nSee also\\n\\nAvailability: not Android, not iOS, not WASI.\\n\\nThis module is not supported on mobile platforms or WebAssembly platforms.\\n\\nCommand-line interface¶\\n\\nThe command line interface is invoked using the interpreter’s -m switch.\\n\\nThe simplest possible invocation is:\\n\\npython -m ensurepip\\n\\nThis invocation will install pip if it is not already installed, but otherwise does nothing. To ensure the installed version of pip is at least as recent as the one available in ensurepip, pass the --upgrade option:\\n\\npython -m ensurepip --upgrade\\n\\nBy default, pip is installed into the current virtual environment (if one is active) or into the system site packages (if there is no active virtual environment). The installation location can be controlled through two additional command line options:\\n\\nBy default, the scripts pipX and pipX.Y will be installed (where X.Y stands for the version of Python used to invoke ensurepip). The scripts installed can be controlled through two additional command line options:\\n\\nProviding both of the script selection options will trigger an exception.\\n\\nModule API¶\\n\\nensurepip exposes two functions for programmatic use:\\n\\nTable of Contents\\n\\nensurepip — Bootstrapping the pip installer\\n\\nCommand-line interface\\n\\nModule API\\n\\nPrevious topic\\n\\nSoftware Packaging and Distribution\\n\\nNext topic\\n\\nvenv — Creation of virtual environments\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nSoftware Packaging and Distribution »\\n\\nensurepip — Bootstrapping the pip installer\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\enum.html'}, page_content=\"Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Types »\\n\\nenum — Support for enumerations\\n\\n|\\n\\nenum — Support for enumerations¶\\n\\nAdded in version 3.4.\\n\\nSource code: Lib/enum.py\\n\\nImportant\\n\\nThis page contains the API reference information. For tutorial information and discussion of more advanced topics, see\\n\\nBasic Tutorial\\n\\nAdvanced Tutorial\\n\\nEnum Cookbook\\n\\nAn enumeration:\\n\\nis a set of symbolic names (members) bound to unique values\\n\\ncan be iterated over to return its canonical (i.e. non-alias) members in definition order\\n\\nuses call syntax to return members by value\\n\\nuses index syntax to return members by name\\n\\nEnumerations are created either by using class syntax, or by using function-call syntax:\\n\\n>>> from enum import Enum\\n\\n>>> # class syntax\\n>>> class Color(Enum):\\n... RED = 1\\n... GREEN = 2\\n... BLUE = 3\\n\\n>>> # functional syntax\\n>>> Color = Enum('Color', [('RED', 1), ('GREEN', 2), ('BLUE', 3)])\\n\\nEven though we can use class syntax to create Enums, Enums are not normal Python classes. See How are Enums different? for more details.\\n\\nNote\\n\\nNomenclature\\n\\nThe class Color is an enumeration (or enum)\\n\\nThe attributes Color.RED, Color.GREEN, etc., are enumeration members (or members) and are functionally constants.\\n\\nThe enum members have names and values (the name of Color.RED is RED, the value of Color.BLUE is 3, etc.)\\n\\nModule Contents¶\\n\\nEnumType\\n\\nThe type for Enum and its subclasses.\\n\\nEnum\\n\\nBase class for creating enumerated constants.\\n\\nIntEnum\\n\\nBase class for creating enumerated constants that are also subclasses of int. (Notes)\\n\\nStrEnum\\n\\nBase class for creating enumerated constants that are also subclasses of str. (Notes)\\n\\nFlag\\n\\nBase class for creating enumerated constants that can be combined using the bitwise operations without losing their Flag membership.\\n\\nIntFlag\\n\\nBase class for creating enumerated constants that can be combined using the bitwise operators without losing their IntFlag membership. IntFlag members are also subclasses of int. (Notes)\\n\\nReprEnum\\n\\nUsed by IntEnum, StrEnum, and IntFlag to keep the str() of the mixed-in type.\\n\\nEnumCheck\\n\\nAn enumeration with the values CONTINUOUS, NAMED_FLAGS, and UNIQUE, for use with verify() to ensure various constraints are met by a given enumeration.\\n\\nFlagBoundary\\n\\nAn enumeration with the values STRICT, CONFORM, EJECT, and KEEP which allows for more fine-grained control over how invalid values are dealt with in an enumeration.\\n\\nEnumDict\\n\\nA subclass of dict for use when subclassing EnumType.\\n\\nauto\\n\\nInstances are replaced with an appropriate value for Enum members. StrEnum defaults to the lower-cased version of the member name, while other Enums default to 1 and increase from there.\\n\\nproperty()\\n\\nAllows Enum members to have attributes without conflicting with member names. The value and name attributes are implemented this way.\\n\\nunique()\\n\\nEnum class decorator that ensures only one name is bound to any one value.\\n\\nverify()\\n\\nEnum class decorator that checks user-selectable constraints on an enumeration.\\n\\nmember()\\n\\nMake obj a member. Can be used as a decorator.\\n\\nnonmember()\\n\\nDo not make obj a member. Can be used as a decorator.\\n\\nglobal_enum()\\n\\nModify the str() and 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.\\n\\nshow_flag_values()\\n\\nReturn a list of all power-of-two integers contained in a flag.\\n\\nenum.bin()\\n\\nLike built-in bin(), except negative values are represented in two’s complement, and the leading bit always indicates sign (0 implies positive, 1 implies negative).\\n\\nAdded in version 3.6: Flag, IntFlag, auto\\n\\nAdded in version 3.11: StrEnum, EnumCheck, ReprEnum, FlagBoundary, property, member, nonmember, global_enum, show_flag_values\\n\\nAdded in version 3.13: EnumDict\\n\\nData Types¶\\n\\nSupported __dunder__ names¶\\n\\n__members__ is a read-only ordered mapping of member_name:member items. It is only available on the class.\\n\\n__new__(), if specified, must create and return the enum members; it is also a very good idea to set the member’s _value_ appropriately. Once all the members are created it is no longer used.\\n\\nSupported _sunder_ names¶\\n\\n_name_ – name of the member\\n\\n_value_ – value of the member; can be set in __new__\\n\\n_missing_() – a lookup function used when a value is not found; may be overridden\\n\\n_ignore_ – a list of names, either as a list or a str, that will not be transformed into members, and will be removed from the final class\\n\\n_order_ – no longer used, kept for backward compatibility (class attribute, removed during class creation)\\n\\n_generate_next_value_() – used to get an appropriate value for an enum member; may be overridden\\n\\n_add_alias_() – adds a new name as an alias to an existing member.\\n\\n_add_value_alias_() – adds a new value as an alias to an existing member.\\n\\nWhile _sunder_ names are generally reserved for the further development of the Enum class and can not be used, some are explicitly allowed:\\n\\n_repr_* (e.g. _repr_html_), as used in IPython’s rich display\\n\\nAdded in version 3.6: _missing_, _order_, _generate_next_value_\\n\\nAdded in version 3.7: _ignore_\\n\\nAdded in version 3.13: _add_alias_, _add_value_alias_, _repr_*\\n\\nUtilities and Decorators¶\\n\\nNotes¶\\n\\nIntEnum, StrEnum, and IntFlag\\n\\nThese three enum types are designed to be drop-in replacements for existing integer- and string-based values; as such, they have extra limitations:\\n\\n__str__ uses the value and not the name of the enum member\\n\\n__format__, because it uses __str__, will also use the value of the enum member instead of its name\\n\\nIf you do not need/want those limitations, you can either create your own base class by mixing in the int or str type yourself:\\n\\n>>> from enum import Enum\\n>>> class MyIntEnum(int, Enum):\\n... pass\\n\\nor you can reassign the appropriate str(), etc., in your enum:\\n\\n>>> from enum import Enum, IntEnum\\n>>> class MyIntEnum(IntEnum):\\n... __str__ = Enum.__str__\\n\\nTable of Contents\\n\\nenum — Support for enumerations\\n\\nModule Contents\\n\\nData Types\\n\\nSupported __dunder__ names\\n\\nSupported _sunder_ names\\n\\nUtilities and Decorators\\n\\nNotes\\n\\nPrevious topic\\n\\nreprlib — Alternate repr() implementation\\n\\nNext topic\\n\\ngraphlib — Functionality to operate with graph-like structures\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Types »\\n\\nenum — Support for enumerations\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.\"), Document(metadata={'source': '..\\\\..\\\\docs\\\\errno.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nGeneric Operating System Services »\\n\\nerrno — Standard errno system symbols\\n\\n|\\n\\nerrno — Standard errno system symbols¶\\n\\nThis module makes available standard errno system symbols. The value of each symbol is the corresponding integer value. The names and descriptions are borrowed from linux/include/errno.h, which should be all-inclusive.\\n\\nTo translate a numeric error code to an error message, use os.strerror().\\n\\nOf the following list, symbols that are not used on the current platform are not defined by the module. The specific list of defined symbols is available as errno.errorcode.keys(). Symbols available can include:\\n\\nPrevious topic\\n\\nplatform — Access to underlying platform’s identifying data\\n\\nNext topic\\n\\nctypes — A foreign function library for Python\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nGeneric Operating System Services »\\n\\nerrno — Standard errno system symbols\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\exceptions.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nBuilt-in Exceptions\\n\\n|\\n\\nBuilt-in Exceptions¶\\n\\nIn Python, all exceptions must be instances of a class that derives from BaseException. In a try statement with an except clause that mentions a particular class, that clause also handles any exception classes derived from that class (but not exception classes from which it is derived). Two exception classes that are not related via subclassing are never equivalent, even if they have the same name.\\n\\nThe built-in exceptions listed in this chapter can be generated by the interpreter or built-in functions. Except where mentioned, they have an “associated value” indicating the detailed cause of the error. This may be a string or a tuple of several items of information (e.g., an error code and a string explaining the code). The associated value is usually passed as arguments to the exception class’s constructor.\\n\\nUser code can raise built-in exceptions. This can be used to test an exception handler or to report an error condition “just like” the situation in which the interpreter raises the same exception; but beware that there is nothing to prevent user code from raising an inappropriate error.\\n\\nThe built-in exception classes can be subclassed to define new exceptions; programmers are encouraged to derive new exceptions from the Exception class or one of its subclasses, and not from BaseException. More information on defining exceptions is available in the Python Tutorial under User-defined Exceptions.\\n\\nException context¶\\n\\nThree attributes on exception objects provide information about the context in which the exception was raised:\\n\\nInheriting from built-in exceptions¶\\n\\nUser code can create subclasses that inherit from an exception type. It’s recommended to only subclass one exception type at a time to avoid any possible conflicts between how the bases handle the args attribute, as well as due to possible memory layout incompatibilities.\\n\\nCPython implementation detail: Most built-in exceptions are implemented in C for efficiency, see: 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.\\n\\nBase classes¶\\n\\nThe following exceptions are used mostly as base classes for other exceptions.\\n\\nConcrete exceptions¶\\n\\nThe following exceptions are the exceptions that are usually raised.\\n\\nThe following exceptions are kept for compatibility with previous versions; starting from Python 3.3, they are aliases of OSError.\\n\\nOS exceptions¶\\n\\nThe following exceptions are subclasses of OSError, they get raised depending on the system error code.\\n\\nAdded in version 3.3: All the above OSError subclasses were added.\\n\\nSee also\\n\\nPEP 3151 - Reworking the OS and IO exception hierarchy\\n\\nWarnings¶\\n\\nThe following exceptions are used as warning categories; see the Warning Categories documentation for more details.\\n\\nException groups¶\\n\\nThe following are used when it is necessary to raise multiple unrelated exceptions. They are part of the exception hierarchy so they can be handled with except like all other exceptions. In addition, they are recognised by except*, which matches their subgroups based on the types of the contained exceptions.\\n\\nException hierarchy¶\\n\\nThe class hierarchy for built-in exceptions is:\\n\\nBaseException\\n ├── BaseExceptionGroup\\n ├── GeneratorExit\\n ├── KeyboardInterrupt\\n ├── SystemExit\\n └── Exception\\n ├── ArithmeticError\\n │ ├── FloatingPointError\\n │ ├── OverflowError\\n │ └── ZeroDivisionError\\n ├── AssertionError\\n ├── AttributeError\\n ├── BufferError\\n ├── EOFError\\n ├── ExceptionGroup [BaseExceptionGroup]\\n ├── ImportError\\n │ └── ImportCycleError\\n │ └── ModuleNotFoundError\\n ├── LookupError\\n │ ├── IndexError\\n │ └── KeyError\\n ├── MemoryError\\n ├── NameError\\n │ └── UnboundLocalError\\n ├── OSError\\n │ ├── BlockingIOError\\n │ ├── ChildProcessError\\n │ ├── ConnectionError\\n │ │ ├── BrokenPipeError\\n │ │ ├── ConnectionAbortedError\\n │ │ ├── ConnectionRefusedError\\n │ │ └── ConnectionResetError\\n │ ├── FileExistsError\\n │ ├── FileNotFoundError\\n │ ├── InterruptedError\\n │ ├── IsADirectoryError\\n │ ├── NotADirectoryError\\n │ ├── PermissionError\\n │ ├── ProcessLookupError\\n │ └── TimeoutError\\n ├── ReferenceError\\n ├── RuntimeError\\n │ ├── NotImplementedError\\n │ ├── PythonFinalizationError\\n │ └── RecursionError\\n ├── StopAsyncIteration\\n ├── StopIteration\\n ├── SyntaxError\\n │ └── IndentationError\\n │ └── TabError\\n ├── SystemError\\n ├── TypeError\\n ├── ValueError\\n │ └── UnicodeError\\n │ ├── UnicodeDecodeError\\n │ ├── UnicodeEncodeError\\n │ └── UnicodeTranslateError\\n └── Warning\\n ├── BytesWarning\\n ├── DeprecationWarning\\n ├── EncodingWarning\\n ├── FutureWarning\\n ├── ImportWarning\\n ├── PendingDeprecationWarning\\n ├── ResourceWarning\\n ├── RuntimeWarning\\n ├── SyntaxWarning\\n ├── UnicodeWarning\\n └── UserWarning\\n\\nTable of Contents\\n\\nBuilt-in Exceptions\\n\\nException context\\n\\nInheriting from built-in exceptions\\n\\nBase classes\\n\\nConcrete exceptions\\n\\nOS exceptions\\n\\nWarnings\\n\\nException groups\\n\\nException hierarchy\\n\\nPrevious topic\\n\\nBuilt-in Types\\n\\nNext topic\\n\\nThread Safety Guarantees\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nBuilt-in Exceptions\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\faulthandler.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nDebugging and profiling »\\n\\nfaulthandler — Dump the Python traceback\\n\\n|\\n\\nfaulthandler — Dump the Python traceback¶\\n\\nAdded in version 3.3.\\n\\nThis module contains functions to dump Python tracebacks explicitly, on a fault, after a timeout, or on a user signal. Call faulthandler.enable() to install fault handlers for the SIGSEGV, SIGFPE, SIGABRT, SIGBUS, and SIGILL signals. You can also enable them at startup by setting the PYTHONFAULTHANDLER environment variable or by using the -X faulthandler command line option.\\n\\nThe fault handler is compatible with system fault handlers like Apport or the Windows fault handler. The module uses an alternative stack for signal handlers if the sigaltstack() function is available. This allows it to dump the traceback even on a stack overflow.\\n\\nThe fault handler is called on catastrophic cases and therefore can only use signal-safe functions (e.g. it cannot allocate memory on the heap). Because of this limitation traceback dumping is minimal compared to normal Python tracebacks:\\n\\nOnly ASCII is supported. The backslashreplace error handler is used on encoding.\\n\\nEach string is limited to 500 characters.\\n\\nOnly the filename, the function name and the line number are displayed. (no source code)\\n\\nIt is limited to 100 frames and 100 threads.\\n\\nThe order is reversed: the most recent call is shown first.\\n\\nBy default, the Python traceback is written to sys.stderr. To see tracebacks, applications must be run in the terminal. A log file can alternatively be passed to faulthandler.enable().\\n\\nThe module is implemented in C, so tracebacks can be dumped on a crash or when Python is deadlocked.\\n\\nThe Python Development Mode calls faulthandler.enable() at Python startup.\\n\\nSee also\\n\\nDumping the traceback¶\\n\\nDumping the C stack¶\\n\\nAdded in version 3.14.\\n\\nC Stack Compatibility¶\\n\\nIf the system does not support the C-level backtrace(3) or dladdr1(3), then C stack dumps will not work. An error will be printed instead of the stack.\\n\\nAdditionally, some compilers do not support 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.\\n\\nNote\\n\\nDumping C stacks can be arbitrarily slow, depending on the DWARF level of the binaries in the call stack.\\n\\nFault handler state¶\\n\\nDumping the tracebacks after a timeout¶\\n\\nDumping the traceback on a user signal¶\\n\\nIssue with file descriptors¶\\n\\nenable(), dump_traceback_later() and register() keep the file descriptor of their file argument. If the file is closed and its file descriptor is reused by a new file, or if os.dup2() is used to replace the file descriptor, the traceback will be written into a different file. Call these functions again each time that the file is replaced.\\n\\nExample¶\\n\\nExample of a segmentation fault on Linux with and without enabling the fault handler:\\n\\n$ python -c \"import ctypes; ctypes.string_at(0)\"\\nSegmentation fault\\n\\n$ python -q -X faulthandler\\n>>> import ctypes\\n>>> ctypes.string_at(0)\\nFatal Python error: Segmentation fault\\n\\nCurrent thread 0x00007fb899f39700 (most recent call first):\\n File \"/opt/python/Lib/ctypes/__init__.py\", line 486 in string_at\\n File \"\", line 1 in \\n\\nCurrent thread\\'s C stack trace (most recent call first):\\n Binary file \"/opt/python/python\", at _Py_DumpStack+0x42 [0x5b27f7d7147e]\\n Binary file \"/opt/python/python\", at +0x32dcbd [0x5b27f7d85cbd]\\n Binary file \"/opt/python/python\", at +0x32df8a [0x5b27f7d85f8a]\\n Binary file \"/usr/lib/libc.so.6\", at +0x3def0 [0x77b73226bef0]\\n Binary file \"/usr/lib/libc.so.6\", at +0x17ef9c [0x77b7323acf9c]\\n Binary file \"/opt/python/build/lib.linux-x86_64-3.15/_ctypes.cpython-315d-x86_64-linux-gnu.so\", at +0xcdf6 [0x77b7315dddf6]\\n Binary file \"/usr/lib/libffi.so.8\", at +0x7976 [0x77b73158f976]\\n Binary file \"/usr/lib/libffi.so.8\", at +0x413c [0x77b73158c13c]\\n Binary file \"/usr/lib/libffi.so.8\", at ffi_call+0x12e [0x77b73158ef0e]\\n Binary file \"/opt/python/build/lib.linux-x86_64-3.15/_ctypes.cpython-315d-x86_64-linux-gnu.so\", at +0x15a33 [0x77b7315e6a33]\\n Binary file \"/opt/python/build/lib.linux-x86_64-3.15/_ctypes.cpython-315d-x86_64-linux-gnu.so\", at +0x164fa [0x77b7315e74fa]\\n Binary file \"/opt/python/build/lib.linux-x86_64-3.15/_ctypes.cpython-315d-x86_64-linux-gnu.so\", at +0xc624 [0x77b7315dd624]\\n Binary file \"/opt/python/python\", at _PyObject_MakeTpCall+0xce [0x5b27f7b73883]\\n Binary file \"/opt/python/python\", at +0x11bab6 [0x5b27f7b73ab6]\\n Binary file \"/opt/python/python\", at PyObject_Vectorcall+0x23 [0x5b27f7b73b04]\\n Binary file \"/opt/python/python\", at _PyEval_EvalFrameDefault+0x490c [0x5b27f7cbb302]\\n Binary file \"/opt/python/python\", at +0x2818e6 [0x5b27f7cd98e6]\\n Binary file \"/opt/python/python\", at +0x281aab [0x5b27f7cd9aab]\\n Binary file \"/opt/python/python\", at PyEval_EvalCode+0xc5 [0x5b27f7cd9ba3]\\n Binary file \"/opt/python/python\", at +0x255957 [0x5b27f7cad957]\\n Binary file \"/opt/python/python\", at +0x255ab4 [0x5b27f7cadab4]\\n Binary file \"/opt/python/python\", at _PyEval_EvalFrameDefault+0x6c3e [0x5b27f7cbd634]\\n Binary file \"/opt/python/python\", at +0x2818e6 [0x5b27f7cd98e6]\\n Binary file \"/opt/python/python\", at +0x281aab [0x5b27f7cd9aab]\\n Binary file \"/opt/python/python\", at +0x11b6e1 [0x5b27f7b736e1]\\n Binary file \"/opt/python/python\", at +0x11d348 [0x5b27f7b75348]\\n Binary file \"/opt/python/python\", at +0x11d626 [0x5b27f7b75626]\\n Binary file \"/opt/python/python\", at PyObject_Call+0x20 [0x5b27f7b7565e]\\n Binary file \"/opt/python/python\", at +0x32a67a [0x5b27f7d8267a]\\n Binary file \"/opt/python/python\", at +0x32a7f8 [0x5b27f7d827f8]\\n Binary file \"/opt/python/python\", at +0x32ac1b [0x5b27f7d82c1b]\\n Binary file \"/opt/python/python\", at Py_RunMain+0x31 [0x5b27f7d82ebe]\\n \\nSegmentation fault\\n\\nTable of Contents\\n\\nfaulthandler — Dump the Python traceback\\n\\nDumping the traceback\\n\\nDumping the C stack\\n\\nC Stack Compatibility\\n\\nFault handler state\\n\\nDumping the tracebacks after a timeout\\n\\nDumping the traceback on a user signal\\n\\nIssue with file descriptors\\n\\nExample\\n\\nPrevious topic\\n\\nbdb — Debugger framework\\n\\nNext topic\\n\\npdb — The Python Debugger\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nDebugging and profiling »\\n\\nfaulthandler — Dump the Python traceback\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\fcntl.html'}, page_content=\"Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nUnix-specific services »\\n\\nfcntl — The fcntl and ioctl system calls\\n\\n|\\n\\nfcntl — The fcntl and ioctl system calls¶\\n\\nThis module performs file and I/O control on file descriptors. It is an interface to the fcntl() and ioctl() Unix routines. See the fcntl(2) and ioctl(2) Unix manual pages for full details.\\n\\nAvailability: Unix, not WASI.\\n\\nAll functions in this module take a file descriptor fd as their first argument. This can be an integer file descriptor, such as returned by sys.stdin.fileno(), or an io.IOBase object, such as sys.stdin itself, which provides a fileno() that returns a genuine file descriptor.\\n\\nChanged in version 3.3: Operations in this module used to raise an IOError where they now raise an OSError.\\n\\nChanged in version 3.8: The fcntl module now contains F_ADD_SEALS, F_GET_SEALS, and F_SEAL_* constants for sealing of os.memfd_create() file descriptors.\\n\\nChanged in version 3.9: On macOS, the fcntl module exposes the F_GETPATH constant, which obtains the path of a file from a file descriptor. On Linux(>=3.15), the fcntl module exposes the F_OFD_GETLK, F_OFD_SETLK and F_OFD_SETLKW constants, which are used when working with open file description locks.\\n\\nChanged in version 3.10: On Linux >= 2.6.11, the fcntl module exposes the F_GETPIPE_SZ and F_SETPIPE_SZ constants, which allow to check and modify a pipe’s size respectively.\\n\\nChanged in version 3.11: On FreeBSD, the fcntl module exposes the F_DUP2FD and F_DUP2FD_CLOEXEC constants, which allow to duplicate a file descriptor, the latter setting FD_CLOEXEC flag in addition.\\n\\nChanged in version 3.12: On Linux >= 4.5, the fcntl module exposes the FICLONE and 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”.\\n\\nChanged in version 3.13: On Linux >= 2.6.32, the fcntl module exposes the F_GETOWN_EX, F_SETOWN_EX, F_OWNER_TID, F_OWNER_PID, 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 fcntl module exposes the F_GET_RW_HINT, F_SET_RW_HINT, F_GET_FILE_RW_HINT, F_SET_FILE_RW_HINT, and 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 fcntl module exposes the F_SEAL_FUTURE_WRITE constant for use with F_ADD_SEALS and F_GET_SEALS operations. On FreeBSD, the fcntl module exposes the F_READAHEAD, F_ISUNIONSTACK, and F_KINFO constants. On macOS and FreeBSD, the fcntl module exposes the F_RDAHEAD constant. On NetBSD and AIX, the fcntl module exposes the F_CLOSEM constant. On NetBSD, the fcntl module exposes the F_MAXFD constant. On macOS and NetBSD, the fcntl module exposes the F_GETNOSIGPIPE and F_SETNOSIGPIPE constant.\\n\\nChanged in version 3.14: On Linux >= 6.1, the fcntl module exposes the F_DUPFD_QUERY to query a file descriptor pointing to the same file.\\n\\nThe module defines the following functions:\\n\\nExamples (all on a SVR4 compliant system):\\n\\nimport struct, fcntl, os\\n\\nf = open(...)\\nrv = fcntl.fcntl(f, fcntl.F_SETFL, os.O_NDELAY)\\n\\nlockdata = struct.pack('hhllhh', fcntl.F_WRLCK, 0, 0, 0, 0, 0)\\nrv = fcntl.fcntl(f, fcntl.F_SETLKW, lockdata)\\n\\nNote that in the first example the return value variable rv will hold an integer value; in the second example it will hold a bytes object. The structure lay-out for the lockdata variable is system dependent — therefore using the flock() call may be better.\\n\\nSee also\\n\\nPrevious topic\\n\\npty — Pseudo-terminal utilities\\n\\nNext topic\\n\\nresource — Resource usage information\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nUnix-specific services »\\n\\nfcntl — The fcntl and ioctl system calls\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.\"), Document(metadata={'source': '..\\\\..\\\\docs\\\\filecmp.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nFile and Directory Access »\\n\\nfilecmp — File and Directory Comparisons\\n\\n|\\n\\nfilecmp — File and Directory Comparisons¶\\n\\nSource code: Lib/filecmp.py\\n\\nThe filecmp module defines functions to compare files and directories, with various optional time/correctness trade-offs. For comparing files, see also the difflib module.\\n\\nThe filecmp module defines the following functions:\\n\\nThe dircmp class¶\\n\\nHere is a simplified example of using the subdirs attribute to search recursively through two directories to show common different files:\\n\\n>>> from filecmp import dircmp\\n>>> def print_diff_files(dcmp):\\n... for name in dcmp.diff_files:\\n... print(\"diff_file %s found in %s and %s\" % (name, dcmp.left,\\n... dcmp.right))\\n... for sub_dcmp in dcmp.subdirs.values():\\n... print_diff_files(sub_dcmp)\\n...\\n>>> dcmp = dircmp(\\'dir1\\', \\'dir2\\')\\n>>> print_diff_files(dcmp)\\n\\nTable of Contents\\n\\nfilecmp — File and Directory Comparisons\\n\\nThe dircmp class\\n\\nPrevious topic\\n\\nstat — Interpreting stat() results\\n\\nNext topic\\n\\ntempfile — Generate temporary files and directories\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nFile and Directory Access »\\n\\nfilecmp — File and Directory Comparisons\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\fileformats.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nFile Formats\\n\\n|\\n\\nFile Formats¶\\n\\nThe modules described in this chapter parse various miscellaneous file formats that aren’t markup languages and are not related to e-mail.\\n\\ncsv — CSV File Reading and Writing\\n\\nModule Contents\\n\\nDialects and Formatting Parameters\\n\\nReader Objects\\n\\nWriter Objects\\n\\nExamples\\n\\nconfigparser — Configuration file parser\\n\\nQuick Start\\n\\nSupported Datatypes\\n\\nFallback Values\\n\\nSupported INI File Structure\\n\\nUnnamed Sections\\n\\nInterpolation of values\\n\\nMapping Protocol Access\\n\\nCustomizing Parser Behaviour\\n\\nLegacy API Examples\\n\\nConfigParser Objects\\n\\nRawConfigParser Objects\\n\\nExceptions\\n\\ntomllib — Parse TOML files\\n\\nExamples\\n\\nConversion Table\\n\\nnetrc — netrc file processing\\n\\nnetrc Objects\\n\\nplistlib — Generate and parse Apple .plist files\\n\\nExamples\\n\\nPrevious topic\\n\\ntarfile — Read and write tar archive files\\n\\nNext topic\\n\\ncsv — CSV File Reading and Writing\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nFile Formats\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\fileinput.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nCommand-line interface libraries »\\n\\nfileinput — Iterate over lines from multiple input streams\\n\\n|\\n\\nfileinput — Iterate over lines from multiple input streams¶\\n\\nSource code: Lib/fileinput.py\\n\\nThis module implements a helper class and functions to quickly write a loop over standard input or a list of files. If you just want to read or write one file see open().\\n\\nThe typical use is:\\n\\nimport fileinput\\nfor line in fileinput.input(encoding=\"utf-8\"):\\n process(line)\\n\\nThis iterates over the lines of all files listed in sys.argv[1:], defaulting to sys.stdin if the list is empty. If a filename is \\'-\\', it is also replaced by sys.stdin and the optional arguments mode and openhook are ignored. To specify an alternative list of filenames, pass it as the first argument to input(). A single file name is also allowed.\\n\\nAll files are opened in text mode by default, but you can override this by specifying the mode parameter in the call to input() or FileInput. If an I/O error occurs during opening or reading a file, OSError is raised.\\n\\nChanged in version 3.3: IOError used to be raised; it is now an alias of OSError.\\n\\nIf sys.stdin is used more than once, the second and further use will return no lines, except perhaps for interactive use, or if it has been explicitly reset (e.g. using sys.stdin.seek(0)).\\n\\nEmpty files are opened and immediately closed; the only time their presence in the list of filenames is noticeable at all is when the last file opened is empty.\\n\\nLines are returned with any newlines intact, which means that the last line in a file may not have one.\\n\\nYou can control how files are opened by providing an opening hook via the openhook parameter to fileinput.input() or 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 hook_compressed() to support compressed files.\\n\\nThe following function is the primary interface of this module:\\n\\nThe following functions use the global state created by fileinput.input(); if there is no active state, RuntimeError is raised.\\n\\nThe class which implements the sequence behavior provided by the module is available for subclassing as well:\\n\\nOptional in-place filtering: if the keyword argument inplace=True is passed to fileinput.input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently). This makes it possible to write a filter that rewrites its input file in place. If the backup parameter is given (typically as backup=\\'.\\'), it specifies the extension for the backup file, and the backup file remains around; by default, the extension is \\'.bak\\' and it is deleted when the output file is closed. In-place filtering is disabled when standard input is read.\\n\\nThe two following opening hooks are provided by this module:\\n\\nPrevious topic\\n\\ngetpass — Portable password input\\n\\nNext topic\\n\\ncurses — Terminal handling for character-cell displays\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nCommand-line interface libraries »\\n\\nfileinput — Iterate over lines from multiple input streams\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\filesys.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nFile and Directory Access\\n\\n|\\n\\nFile and Directory Access¶\\n\\nThe modules described in this chapter deal with disk files and directories. For example, there are modules for reading the properties of files, manipulating paths in a portable way, and creating temporary files. The full list of modules in this chapter is:\\n\\npathlib — Object-oriented filesystem paths\\n\\nBasic use\\n\\nExceptions\\n\\nPure paths\\n\\nGeneral properties\\n\\nOperators\\n\\nAccessing individual parts\\n\\nMethods and properties\\n\\nConcrete paths\\n\\nParsing and generating URIs\\n\\nExpanding and resolving paths\\n\\nQuerying file type and status\\n\\nReading and writing files\\n\\nReading directories\\n\\nCreating files and directories\\n\\nCopying, moving and deleting\\n\\nPermissions and ownership\\n\\nPattern language\\n\\nComparison to the glob module\\n\\nComparison to the os and os.path modules\\n\\nCorresponding tools\\n\\nProtocols\\n\\nos.path — Common pathname manipulations\\n\\nstat — Interpreting stat() results\\n\\nfilecmp — File and Directory Comparisons\\n\\nThe dircmp class\\n\\ntempfile — Generate temporary files and directories\\n\\nExamples\\n\\nDeprecated functions and variables\\n\\nglob — Unix style pathname pattern expansion\\n\\nExamples\\n\\nfnmatch — Unix filename pattern matching\\n\\nlinecache — Random access to text lines\\n\\nshutil — High-level file operations\\n\\nDirectory and files operations\\n\\nPlatform-dependent efficient copy operations\\n\\ncopytree example\\n\\nrmtree example\\n\\nArchiving operations\\n\\nArchiving example\\n\\nArchiving example with base_dir\\n\\nQuerying the size of the output terminal\\n\\nSee also\\n\\nPrevious topic\\n\\noperator — Standard operators as functions\\n\\nNext topic\\n\\npathlib — Object-oriented filesystem paths\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nFile and Directory Access\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\fnmatch.html'}, page_content=\"Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nFile and Directory Access »\\n\\nfnmatch — Unix filename pattern matching\\n\\n|\\n\\nfnmatch — Unix filename pattern matching¶\\n\\nSource code: Lib/fnmatch.py\\n\\nThis module provides support for Unix shell-style wildcards, which are not the same as regular expressions (which are documented in the re module). The special characters used in shell-style wildcards are:\\n\\nPattern Meaning * matches everything ? matches any single character [seq] matches any character in seq [!seq] matches any character not in seq\\n\\nFor a literal match, wrap the meta-characters in brackets. For example, '[?]' matches the character '?'.\\n\\nNote that the filename separator ('/' on Unix) is not special to this module. See module glob for pathname expansion (glob uses filter() to match pathname segments). Similarly, filenames starting with a period are not special for this module, and are matched by the * and ? patterns.\\n\\nUnless stated otherwise, “filename string” and “pattern string” either refer to str or ISO-8859-1 encoded bytes objects. Note that the functions documented below do not allow to mix a bytes pattern with a str filename, and vice-versa.\\n\\nFinally, note that functools.lru_cache() with a maxsize of 32768 is used to cache the (typed) compiled regex patterns in the following functions: fnmatch(), fnmatchcase(), filter(), filterfalse().\\n\\nSee also\\n\\nPrevious topic\\n\\nglob — Unix style pathname pattern expansion\\n\\nNext topic\\n\\nlinecache — Random access to text lines\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nFile and Directory Access »\\n\\nfnmatch — Unix filename pattern matching\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.\"), Document(metadata={'source': '..\\\\..\\\\docs\\\\fractions.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNumeric and Mathematical Modules »\\n\\nfractions — Rational numbers\\n\\n|\\n\\nfractions — Rational numbers¶\\n\\nSource code: Lib/fractions.py\\n\\nThe fractions module provides support for rational number arithmetic.\\n\\nA Fraction instance can be constructed from a pair of rational numbers, from a single number, or from a string.\\n\\nSee also\\n\\nPrevious topic\\n\\ndecimal — Decimal fixed-point and floating-point arithmetic\\n\\nNext topic\\n\\nrandom — Generate pseudo-random numbers\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNumeric and Mathematical Modules »\\n\\nfractions — Rational numbers\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\frameworks.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nProgram frameworks\\n\\n|\\n\\nProgram frameworks¶\\n\\nThis chapter is no longer maintained, and the modules it contained have been moved to their respective topical documentation.\\n\\ncmd — Command Line Interface Libraries\\n\\nshlex — Unix Specific Services\\n\\nturtle — Graphical User Interfaces with Tk\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nProgram frameworks\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\ftplib.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Protocols and Support »\\n\\nftplib — FTP protocol client\\n\\n|\\n\\nftplib — FTP protocol client¶\\n\\nSource code: Lib/ftplib.py\\n\\nThis module defines the class FTP and a few related items. The FTP class implements the client side of the FTP protocol. You can use this to write Python programs that perform a variety of automated FTP jobs, such as mirroring other FTP servers. It is also used by the module urllib.request to handle URLs that use FTP. For more information on FTP (File Transfer Protocol), see internet RFC 959.\\n\\nThe default encoding is UTF-8, following RFC 2640.\\n\\nAvailability: not WASI.\\n\\nThis module does not work or is not available on WebAssembly. See WebAssembly platforms for more information.\\n\\nHere’s a sample session using the ftplib module:\\n\\n>>> from ftplib import FTP\\n>>> ftp = FTP(\\'ftp.us.debian.org\\') # connect to host, default port\\n>>> ftp.login() # user anonymous, passwd anonymous@\\n\\'230 Login successful.\\'\\n>>> ftp.cwd(\\'debian\\') # change into \"debian\" directory\\n\\'250 Directory successfully changed.\\'\\n>>> ftp.retrlines(\\'LIST\\') # list directory contents\\n-rw-rw-r-- 1 1176 1176 1063 Jun 15 10:18 README\\n...\\ndrwxr-sr-x 5 1176 1176 4096 Dec 19 2000 pool\\ndrwxr-sr-x 4 1176 1176 4096 Nov 17 2008 project\\ndrwxr-xr-x 3 1176 1176 4096 Oct 10 2012 tools\\n\\'226 Directory send OK.\\'\\n>>> with open(\\'README\\', \\'wb\\') as fp:\\n>>> ftp.retrbinary(\\'RETR README\\', fp.write)\\n\\'226 Transfer complete.\\'\\n>>> ftp.quit()\\n\\'221 Goodbye.\\'\\n\\nReference¶\\n\\nFTP objects¶\\n\\nFTP_TLS objects¶\\n\\nModule variables¶\\n\\nSee also\\n\\nTable of Contents\\n\\nftplib — FTP protocol client\\n\\nReference\\n\\nFTP objects\\n\\nFTP_TLS objects\\n\\nModule variables\\n\\nPrevious topic\\n\\nhttp.client — HTTP protocol client\\n\\nNext topic\\n\\npoplib — POP3 protocol client\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Protocols and Support »\\n\\nftplib — FTP protocol client\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\functional.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nFunctional Programming Modules\\n\\n|\\n\\nFunctional Programming Modules¶\\n\\nThe modules described in this chapter provide functions and classes that support a functional programming style, and general operations on callables.\\n\\nThe following modules are documented in this chapter:\\n\\nitertools — Functions creating iterators for efficient looping\\n\\nItertool Functions\\n\\nItertools Recipes\\n\\nfunctools — Higher-order functions and operations on callable objects\\n\\npartial Objects\\n\\noperator — Standard operators as functions\\n\\nMapping Operators to Functions\\n\\nIn-place Operators\\n\\nPrevious topic\\n\\nstatistics — Mathematical statistics functions\\n\\nNext topic\\n\\nitertools — Functions creating iterators for efficient looping\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nFunctional Programming Modules\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\functions.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nBuilt-in Functions\\n\\n|\\n\\nBuilt-in Functions¶\\n\\nThe Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order.\\n\\nBuilt-in Functions A abs() aiter() all() anext() any() ascii() B bin() bool() breakpoint() bytearray() bytes() C callable() chr() classmethod() compile() complex() D delattr() dict() dir() divmod() E enumerate() eval() exec() F filter() float() format() frozenset() G getattr() globals() H hasattr() hash() help() hex() I id() input() int() isinstance() issubclass() iter() L len() list() locals() M map() max() memoryview() min() N next() O object() oct() open() ord() P pow() print() property() R range() repr() reversed() round() S set() setattr() slice() sorted() staticmethod() str() sum() super() T tuple() type() V vars() Z zip() _ __import__()\\n\\nFootnotes\\n\\n[1]\\n\\nNote that the parser only accepts the Unix-style end of line convention. If you are reading the code from a file, make sure to use newline conversion mode to convert Windows or Mac-style newlines.\\n\\nPrevious topic\\n\\nIntroduction\\n\\nNext topic\\n\\nBuilt-in Constants\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nBuilt-in Functions\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\functools.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nFunctional Programming Modules »\\n\\nfunctools — Higher-order functions and operations on callable objects\\n\\n|\\n\\nfunctools — Higher-order functions and operations on callable objects¶\\n\\nSource code: Lib/functools.py\\n\\nThe 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.\\n\\nThe functools module defines the following functions:\\n\\npartial Objects¶\\n\\npartial objects are callable objects created by partial(). They have three read-only attributes:\\n\\npartial objects are like function objects in that they are callable, weak referenceable, and can have attributes. There are some important differences. For instance, the __name__ and __doc__ attributes are not created automatically.\\n\\nTable of Contents\\n\\nfunctools — Higher-order functions and operations on callable objects\\n\\npartial Objects\\n\\nPrevious topic\\n\\nitertools — Functions creating iterators for efficient looping\\n\\nNext topic\\n\\noperator — Standard operators as functions\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nFunctional Programming Modules »\\n\\nfunctools — Higher-order functions and operations on callable objects\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\gc.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Runtime Services »\\n\\ngc — Garbage Collector interface\\n\\n|\\n\\ngc — Garbage Collector interface¶\\n\\nThis module provides an interface to the optional garbage collector. It provides the ability to disable the collector, tune the collection frequency, and set debugging options. It also provides access to unreachable objects that the collector found but cannot free. Since the collector supplements the reference counting already used in Python, you can disable the collector if you are sure your program does not create reference cycles. Automatic collection can be disabled by calling gc.disable(). To debug a leaking program call gc.set_debug(gc.DEBUG_LEAK). Notice that this includes gc.DEBUG_SAVEALL, causing garbage-collected objects to be saved in gc.garbage for inspection.\\n\\nThe gc module provides the following functions:\\n\\nThe following variables are provided for read-only access (you can mutate the values but should not rebind them):\\n\\nThe following constants are provided for use with set_debug():\\n\\nPrevious topic\\n\\n__future__ — Future statement definitions\\n\\nNext topic\\n\\ninspect — Inspect live objects\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Runtime Services »\\n\\ngc — Garbage Collector interface\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\getopt.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nSuperseded modules »\\n\\ngetopt — C-style parser for command line options\\n\\n|\\n\\ngetopt — C-style parser for command line options¶\\n\\nSource code: Lib/getopt.py\\n\\nNote\\n\\nThis module is considered feature complete. A more declarative and extensible alternative to this API is provided in the 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 argparse module.\\n\\nThis module helps scripts to parse the command line arguments in sys.argv. It supports the same conventions as the Unix getopt() function (including the special meanings of arguments of the form ‘-’ and ‘--‘). Long options similar to those supported by GNU software may be used as well via an optional third argument.\\n\\nUsers who are unfamiliar with the Unix getopt() function should consider using the argparse module instead. Users who are familiar with the Unix getopt() function, but would like to get equivalent behavior while writing less code and getting better help and error messages should consider using the optparse module. See Choosing an argument parsing library for additional details.\\n\\nThis module provides two functions and an exception:\\n\\nAn example using only Unix style options:\\n\\n>>> import getopt\\n>>> args = \\'-a -b -cfoo -d bar a1 a2\\'.split()\\n>>> args\\n[\\'-a\\', \\'-b\\', \\'-cfoo\\', \\'-d\\', \\'bar\\', \\'a1\\', \\'a2\\']\\n>>> optlist, args = getopt.getopt(args, \\'abc:d:\\')\\n>>> optlist\\n[(\\'-a\\', \\'\\'), (\\'-b\\', \\'\\'), (\\'-c\\', \\'foo\\'), (\\'-d\\', \\'bar\\')]\\n>>> args\\n[\\'a1\\', \\'a2\\']\\n\\nUsing long option names is equally easy:\\n\\n>>> s = \\'--condition=foo --testing --output-file abc.def -x a1 a2\\'\\n>>> args = s.split()\\n>>> args\\n[\\'--condition=foo\\', \\'--testing\\', \\'--output-file\\', \\'abc.def\\', \\'-x\\', \\'a1\\', \\'a2\\']\\n>>> optlist, args = getopt.getopt(args, \\'x\\', [\\n... \\'condition=\\', \\'output-file=\\', \\'testing\\'])\\n>>> optlist\\n[(\\'--condition\\', \\'foo\\'), (\\'--testing\\', \\'\\'), (\\'--output-file\\', \\'abc.def\\'), (\\'-x\\', \\'\\')]\\n>>> args\\n[\\'a1\\', \\'a2\\']\\n\\nOptional arguments should be specified explicitly:\\n\\n>>> s = \\'-Con -C --color=off --color a1 a2\\'\\n>>> args = s.split()\\n>>> args\\n[\\'-Con\\', \\'-C\\', \\'--color=off\\', \\'--color\\', \\'a1\\', \\'a2\\']\\n>>> optlist, args = getopt.getopt(args, \\'C::\\', [\\'color=?\\'])\\n>>> optlist\\n[(\\'-C\\', \\'on\\'), (\\'-C\\', \\'\\'), (\\'--color\\', \\'off\\'), (\\'--color\\', \\'\\')]\\n>>> args\\n[\\'a1\\', \\'a2\\']\\n\\nThe order of options and non-option arguments can be preserved:\\n\\n>>> s = \\'a1 -x a2 a3 a4 --long a5 a6\\'\\n>>> args = s.split()\\n>>> args\\n[\\'a1\\', \\'-x\\', \\'a2\\', \\'a3\\', \\'a4\\', \\'--long\\', \\'a5\\', \\'a6\\']\\n>>> optlist, args = getopt.gnu_getopt(args, \\'-x:\\', [\\'long=\\'])\\n>>> optlist\\n[(None, [\\'a1\\']), (\\'-x\\', \\'a2\\'), (None, [\\'a3\\', \\'a4\\']), (\\'--long\\', \\'a5\\')]\\n>>> args\\n[\\'a6\\']\\n\\nIn a script, typical usage is something like this:\\n\\nimport getopt, sys\\n\\ndef main():\\n try:\\n opts, args = getopt.getopt(sys.argv[1:], \"ho:v\", [\"help\", \"output=\"])\\n except getopt.GetoptError as err:\\n # print help information and exit:\\n print(err) # will print something like \"option -a not recognized\"\\n usage()\\n sys.exit(2)\\n output = None\\n verbose = False\\n for o, a in opts:\\n if o == \"-v\":\\n verbose = True\\n elif o in (\"-h\", \"--help\"):\\n usage()\\n sys.exit()\\n elif o in (\"-o\", \"--output\"):\\n output = a\\n else:\\n assert False, \"unhandled option\"\\n process(args, output=output, verbose=verbose)\\n\\nif __name__ == \"__main__\":\\n main()\\n\\nNote that an equivalent command line interface could be produced with less code and more informative help and error messages by using the optparse module:\\n\\nimport optparse\\n\\nif __name__ == \\'__main__\\':\\n parser = optparse.OptionParser()\\n parser.add_option(\\'-o\\', \\'--output\\')\\n parser.add_option(\\'-v\\', dest=\\'verbose\\', action=\\'store_true\\')\\n opts, args = parser.parse_args()\\n process(args, output=opts.output, verbose=opts.verbose)\\n\\nA roughly equivalent command line interface for this case can also be produced by using the argparse module:\\n\\nimport argparse\\n\\nif __name__ == \\'__main__\\':\\n parser = argparse.ArgumentParser()\\n parser.add_argument(\\'-o\\', \\'--output\\')\\n parser.add_argument(\\'-v\\', dest=\\'verbose\\', action=\\'store_true\\')\\n parser.add_argument(\\'rest\\', nargs=\\'*\\')\\n args = parser.parse_args()\\n process(args.rest, output=args.output, verbose=args.verbose)\\n\\nSee Choosing an argument parsing library for details on how the argparse version of this code differs in behaviour from the optparse (and getopt) version.\\n\\nSee also\\n\\nPrevious topic\\n\\nSuperseded modules\\n\\nNext topic\\n\\nprofile — Pure Python profiler\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nSuperseded modules »\\n\\ngetopt — C-style parser for command line options\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\getpass.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nCommand-line interface libraries »\\n\\ngetpass — Portable password input\\n\\n|\\n\\ngetpass — Portable password input¶\\n\\nSource code: Lib/getpass.py\\n\\nAvailability: not WASI.\\n\\nThis module does not work or is not available on WebAssembly. See WebAssembly platforms for more information.\\n\\nThe getpass module provides two functions:\\n\\nPrevious topic\\n\\noptparse — Parser for command line options\\n\\nNext topic\\n\\nfileinput — Iterate over lines from multiple input streams\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nCommand-line interface libraries »\\n\\ngetpass — Portable password input\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\gettext.html'}, page_content=\"Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternationalization »\\n\\ngettext — Multilingual internationalization services\\n\\n|\\n\\ngettext — Multilingual internationalization services¶\\n\\nSource code: Lib/gettext.py\\n\\nThe gettext module provides internationalization (I18N) and localization (L10N) services for your Python modules and applications. It supports both the GNU 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.\\n\\nSome hints on localizing your Python modules and applications are also given.\\n\\nGNU gettext API¶\\n\\nThe gettext module defines the following API, which is very similar to the GNU 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.\\n\\nNote that GNU gettext also defines a dcgettext() method, but this was deemed not useful and so it is currently unimplemented.\\n\\nHere’s an example of typical usage for this API:\\n\\nimport gettext\\ngettext.bindtextdomain('myapplication', '/path/to/my/language/directory')\\ngettext.textdomain('myapplication')\\n_ = gettext.gettext\\n# ...\\nprint(_('This is a translatable string.'))\\n\\nClass-based API¶\\n\\nThe class-based API of the gettext module gives you more flexibility and greater convenience than the GNU gettext API. It is the recommended way of localizing your Python applications and modules. gettext defines a GNUTranslations class which implements the parsing of GNU .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 _().\\n\\nThe NullTranslations class¶\\n\\nTranslation classes are what actually implement the translation of original source file message strings to translated message strings. The base class used by all translation classes is NullTranslations; this provides the basic interface you can use to write your own specialized translation classes. Here are the methods of NullTranslations:\\n\\nThe GNUTranslations class¶\\n\\nThe gettext module provides one additional class derived from NullTranslations: GNUTranslations. This class overrides _parse() to enable reading GNU gettext format .mo files in both big-endian and little-endian format.\\n\\nGNUTranslations parses optional metadata out of the translation catalog. It is convention with GNU gettext to include metadata as the translation for the empty string. This metadata is in RFC 822-style key: value pairs, and should contain the Project-Id-Version key. If the key Content-Type is found, then the charset property is used to initialize the “protected” _charset instance variable, defaulting to 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.\\n\\nSince message ids are read as Unicode strings too, all *gettext() methods will assume message ids as Unicode strings, not byte strings.\\n\\nThe entire set of key/value pairs are placed into a dictionary and set as the “protected” _info instance variable.\\n\\nIf the .mo file’s magic number is invalid, the major version number is unexpected, or if other problems occur while reading the file, instantiating a GNUTranslations class can raise OSError.\\n\\nSolaris message catalog support¶\\n\\nThe Solaris operating system defines its own binary .mo file format, but since no documentation can be found on this format, it is not supported at this time.\\n\\nThe Catalog constructor¶\\n\\nGNOME uses a version of the gettext module by James Henstridge, but this version has a slightly different API. Its documented usage was:\\n\\nimport gettext\\ncat = gettext.Catalog(domain, localedir)\\n_ = cat.gettext\\nprint(_('hello world'))\\n\\nFor compatibility with this older module, the function Catalog() is an alias for the translation() function described above.\\n\\nOne difference between this module and Henstridge’s: his catalog objects supported access through a mapping API, but this appears to be unused and so is not currently supported.\\n\\nInternationalizing your programs and modules¶\\n\\nInternationalization (I18N) refers to the operation by which a program is made aware of multiple languages. Localization (L10N) refers to the adaptation of your program, once internationalized, to the local language and cultural habits. In order to provide multilingual messages for your Python programs, you need to take the following steps:\\n\\nprepare your program or module by specially marking translatable strings\\n\\nrun a suite of tools over your marked files to generate raw messages catalogs\\n\\ncreate language-specific translations of the message catalogs\\n\\nuse the gettext module so that message strings are properly translated\\n\\nIn 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 _('...') — that is, a call to the function _. For example:\\n\\nfilename = 'mylog.txt'\\nmessage = _('writing a log message')\\nwith open(filename, 'w') as fp:\\n fp.write(message)\\n\\nIn this example, the string 'writing a log message' is marked as a candidate for translation, while the strings 'mylog.txt' and 'w' are not.\\n\\nThere are a few tools to extract the strings meant for translation. The original GNU gettext only supported C or C++ source code but its extended version xgettext scans code written in a number of languages, including Python, to find strings marked as translatable. Babel is a Python internationalization library that includes a pybabel script to extract and compile message catalogs. François Pinard’s program called xpot does a similar job and is available as part of his po-utils package.\\n\\n(Python also includes pure-Python versions of these programs, called pygettext.py and msgfmt.py; some Python distributions will install them for you. pygettext.py is similar to xgettext, but only understands Python source code and cannot handle other programming languages such as C or C++. pygettext.py supports a command-line interface similar to xgettext; for details on its use, run pygettext.py --help. msgfmt.py is binary compatible with GNU msgfmt. With these two programs, you may not need the GNU gettext package to internationalize your Python applications.)\\n\\nxgettext, pygettext, and similar tools generate .po files that are message catalogs. They are structured human-readable files that contain every marked string in the source code, along with a placeholder for the translated versions of these strings.\\n\\nCopies of these .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 .po file that’s compiled into a machine-readable .mo binary catalog file using the msgfmt program. The .mo files are used by the gettext module for the actual translation processing at run-time.\\n\\nHow you use the 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.\\n\\nLocalizing your module¶\\n\\nIf you are localizing your module, you must take care not to make global changes, e.g. to the built-in namespace. You should not use the GNU gettext API but instead the class-based API.\\n\\nLet’s say your module is called “spam” and the module’s various natural language translation .mo files reside in /usr/share/locale in GNU gettext format. Here’s what you would put at the top of your module:\\n\\nimport gettext\\nt = gettext.translation('spam', '/usr/share/locale')\\n_ = t.gettext\\n\\nLocalizing your application¶\\n\\nIf you are localizing your application, you can install the _() 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 _('...') without having to explicitly install it in each file.\\n\\nIn the simple case then, you need only add the following bit of code to the main driver file of your application:\\n\\nimport gettext\\ngettext.install('myapplication')\\n\\nIf you need to set the locale directory, you can pass it into the install() function:\\n\\nimport gettext\\ngettext.install('myapplication', '/usr/share/locale')\\n\\nChanging languages on the fly¶\\n\\nIf your program needs to support many languages at the same time, you may want to create multiple translation instances and then switch between them explicitly, like so:\\n\\nimport gettext\\n\\nlang1 = gettext.translation('myapplication', languages=['en'])\\nlang2 = gettext.translation('myapplication', languages=['fr'])\\nlang3 = gettext.translation('myapplication', languages=['de'])\\n\\n# start by using language1\\nlang1.install()\\n\\n# ... time goes by, user selects language 2\\nlang2.install()\\n\\n# ... more time goes by, user selects language 3\\nlang3.install()\\n\\nDeferred translations¶\\n\\nIn most coding situations, strings are translated where they are coded. Occasionally however, you need to mark strings for translation, but defer actual translation until later. A classic example is:\\n\\nanimals = ['mollusk',\\n 'albatross',\\n 'rat',\\n 'penguin',\\n 'python', ]\\n# ...\\nfor a in animals:\\n print(a)\\n\\nHere, you want to mark the strings in the animals list as being translatable, but you don’t actually want to translate them until they are printed.\\n\\nHere is one way you can handle this situation:\\n\\ndef _(message): return message\\n\\nanimals = [_('mollusk'),\\n _('albatross'),\\n _('rat'),\\n _('penguin'),\\n _('python'), ]\\n\\ndel _\\n\\n# ...\\nfor a in animals:\\n print(_(a))\\n\\nThis works because the dummy definition of _() simply returns the string unchanged. And this dummy definition will temporarily override any definition of _() in the built-in namespace (until the del command). Take care, though if you have a previous definition of _() in the local namespace.\\n\\nNote that the second use of _() will not identify “a” as being translatable to the gettext program, because the parameter is not a string literal.\\n\\nAnother way to handle this is with the following example:\\n\\ndef N_(message): return message\\n\\nanimals = [N_('mollusk'),\\n N_('albatross'),\\n N_('rat'),\\n N_('penguin'),\\n N_('python'), ]\\n\\n# ...\\nfor a in animals:\\n print(_(a))\\n\\nIn this case, you are marking translatable strings with the function N_(), which won’t conflict with any definition of _(). However, you will need to teach your message extraction program to look for translatable strings marked with N_(). xgettext, pygettext, pybabel extract, and xpot all support this through the use of the -k command-line switch. The choice of N_() here is totally arbitrary; it could have just as easily been MarkThisStringForTranslation().\\n\\nAcknowledgements¶\\n\\nThe following people contributed code, feedback, design suggestions, previous implementations, and valuable experience to the creation of this module:\\n\\nPeter Funk\\n\\nJames Henstridge\\n\\nJuan David Ibáñez Palomar\\n\\nMarc-André Lemburg\\n\\nMartin von Löwis\\n\\nFrançois Pinard\\n\\nBarry Warsaw\\n\\nGustavo Niemeyer\\n\\nFootnotes\\n\\n[1]\\n\\nThe default locale directory is system dependent; for example, on Red Hat Linux it is /usr/share/locale, but on Solaris it is /usr/lib/locale. The gettext module does not try to support these system dependent defaults; instead its default is sys.base_prefix/share/locale (see sys.base_prefix). For this reason, it is always best to call bindtextdomain() with an explicit absolute path at the start of your application.\\n\\n[2]\\n\\nSee the footnote for bindtextdomain() above.\\n\\nTable of Contents\\n\\ngettext — Multilingual internationalization services\\n\\nGNU gettext API\\n\\nClass-based API\\n\\nThe NullTranslations class\\n\\nThe GNUTranslations class\\n\\nSolaris message catalog support\\n\\nThe Catalog constructor\\n\\nInternationalizing your programs and modules\\n\\nLocalizing your module\\n\\nLocalizing your application\\n\\nChanging languages on the fly\\n\\nDeferred translations\\n\\nAcknowledgements\\n\\nPrevious topic\\n\\nInternationalization\\n\\nNext topic\\n\\nlocale — Internationalization services\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternationalization »\\n\\ngettext — Multilingual internationalization services\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.\"), Document(metadata={'source': '..\\\\..\\\\docs\\\\glob.html'}, page_content=\"Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nFile and Directory Access »\\n\\nglob — Unix style pathname pattern expansion\\n\\n|\\n\\nglob — Unix style pathname pattern expansion¶\\n\\nSource code: Lib/glob.py\\n\\nThe glob module finds pathnames using pattern matching rules similar to the Unix shell. No tilde expansion is done, but *, ?, and character ranges expressed with [] will be correctly matched. This is done by using the os.scandir() and fnmatch.fnmatch() functions in concert, and not by actually invoking a subshell.\\n\\nNote\\n\\nThe pathnames are returned in no particular order. If you need a specific order, sort the results.\\n\\nFiles beginning with a dot (.) can only be matched by patterns that also start with a dot, unlike fnmatch.fnmatch() or pathlib.Path.glob(). For tilde and shell variable expansion, use os.path.expanduser() and os.path.expandvars().\\n\\nFor a literal match, wrap the meta-characters in brackets. For example, '[?]' matches the character '?'.\\n\\nThe glob module defines the following functions:\\n\\nExamples¶\\n\\nConsider a directory containing the following files: 1.gif, 2.txt, card.gif and a subdirectory sub which contains only the file 3.txt. glob() will produce the following results. Notice how any leading components of the path are preserved.\\n\\n>>> import glob\\n>>> glob.glob('./[0-9].*')\\n['./1.gif', './2.txt']\\n>>> glob.glob('*.gif')\\n['1.gif', 'card.gif']\\n>>> glob.glob('?.gif')\\n['1.gif']\\n>>> glob.glob('**/*.txt', recursive=True)\\n['2.txt', 'sub/3.txt']\\n>>> glob.glob('./**/', recursive=True)\\n['./', './sub/']\\n\\nIf the directory contains files starting with . they won’t be matched by default. For example, consider a directory containing card.gif and .card.gif:\\n\\n>>> import glob\\n>>> glob.glob('*.gif')\\n['card.gif']\\n>>> glob.glob('.c*')\\n['.card.gif']\\n\\nSee also\\n\\nThe fnmatch module offers shell-style filename (not path) expansion.\\n\\nSee also\\n\\nThe pathlib module offers high-level path objects.\\n\\nTable of Contents\\n\\nglob — Unix style pathname pattern expansion\\n\\nExamples\\n\\nPrevious topic\\n\\ntempfile — Generate temporary files and directories\\n\\nNext topic\\n\\nfnmatch — Unix filename pattern matching\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nFile and Directory Access »\\n\\nglob — Unix style pathname pattern expansion\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.\"), Document(metadata={'source': '..\\\\..\\\\docs\\\\graphlib.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Types »\\n\\ngraphlib — Functionality to operate with graph-like structures\\n\\n|\\n\\ngraphlib — Functionality to operate with graph-like structures¶\\n\\nSource code: Lib/graphlib.py\\n\\nExceptions¶\\n\\nThe graphlib module defines the following exception classes:\\n\\nTable of Contents\\n\\ngraphlib — Functionality to operate with graph-like structures\\n\\nExceptions\\n\\nPrevious topic\\n\\nenum — Support for enumerations\\n\\nNext topic\\n\\nNumeric and Mathematical Modules\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Types »\\n\\ngraphlib — Functionality to operate with graph-like structures\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\grp.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nUnix-specific services »\\n\\ngrp — The group database\\n\\n|\\n\\ngrp — The group database¶\\n\\nThis module provides access to the Unix group database. It is available on all Unix versions.\\n\\nAvailability: Unix, not WASI, not Android, not iOS.\\n\\nGroup database entries are reported as a tuple-like object, whose attributes correspond to the members of the group structure (Attribute field below, see ):\\n\\nIndex Attribute Meaning 0 gr_name the name of the group 1 gr_passwd the (encrypted) group password;\\noften empty 2 gr_gid the numerical group ID 3 gr_mem all the group member’s user\\nnames\\n\\nThe gid is an integer, name and password are strings, and the member list is a list of strings. (Note that most users are not explicitly listed as members of the group they are in according to the password database. Check both databases to get complete membership information. Also note that a gr_name that starts with a + or - is likely to be a YP/NIS reference and may not be accessible via getgrnam() or getgrgid().)\\n\\nIt defines the following items:\\n\\nSee also\\n\\nPrevious topic\\n\\npwd — The password database\\n\\nNext topic\\n\\ntermios — POSIX style tty control\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nUnix-specific services »\\n\\ngrp — The group database\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\gzip.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Compression and Archiving »\\n\\ngzip — Support for gzip files\\n\\n|\\n\\ngzip — Support for gzip files¶\\n\\nSource code: Lib/gzip.py\\n\\nThis module provides a simple interface to compress and decompress files just like the GNU programs gzip and gunzip would.\\n\\nThis is an 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 Requirements for optional modules.\\n\\nThe data compression is provided by the zlib module.\\n\\nThe gzip module provides the GzipFile class, as well as the open(), compress() and decompress() convenience functions. The GzipFile class reads and writes gzip-format files, automatically compressing or decompressing the data so that it looks like an ordinary file object.\\n\\nNote that additional file formats which can be decompressed by the gzip and gunzip programs, such as those produced by compress and pack, are not supported by this module.\\n\\nThe module defines the following items:\\n\\nExamples of usage¶\\n\\nExample of how to read a compressed file:\\n\\nimport gzip\\nwith gzip.open(\\'/home/joe/file.txt.gz\\', \\'rb\\') as f:\\n file_content = f.read()\\n\\nExample of how to create a compressed GZIP file:\\n\\nimport gzip\\ncontent = b\"Lots of content here\"\\nwith gzip.open(\\'/home/joe/file.txt.gz\\', \\'wb\\') as f:\\n f.write(content)\\n\\nExample of how to GZIP compress an existing file:\\n\\nimport gzip\\nimport shutil\\nwith open(\\'/home/joe/file.txt\\', \\'rb\\') as f_in:\\n with gzip.open(\\'/home/joe/file.txt.gz\\', \\'wb\\') as f_out:\\n shutil.copyfileobj(f_in, f_out)\\n\\nExample of how to GZIP compress a binary string:\\n\\nimport gzip\\ns_in = b\"Lots of content here\"\\ns_out = gzip.compress(s_in)\\n\\nSee also\\n\\nIn case gzip (de)compression is a bottleneck, the python-isal package speeds up (de)compression with a mostly compatible API.\\n\\nCommand-line interface¶\\n\\nThe gzip module provides a simple command line interface to compress or decompress files.\\n\\nOnce executed the gzip module keeps the input file(s).\\n\\nChanged in version 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.\\n\\nCommand-line options¶\\n\\nTable of Contents\\n\\ngzip — Support for gzip files\\n\\nExamples of usage\\n\\nCommand-line interface\\n\\nCommand-line options\\n\\nPrevious topic\\n\\nzlib — Compression compatible with gzip\\n\\nNext topic\\n\\nbz2 — Support for bzip2 compression\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Compression and Archiving »\\n\\ngzip — Support for gzip files\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\hashlib.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nCryptographic Services »\\n\\nhashlib — Secure hashes and message digests\\n\\n|\\n\\nhashlib — Secure hashes and message digests¶\\n\\nSource code: Lib/hashlib.py\\n\\nThis 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), the SHA-3 series (defined in the FIPS 202 standard) as well as the legacy algorithms SHA1 (formerly part of FIPS) and the MD5 algorithm (defined in internet RFC 1321).\\n\\nNote\\n\\nIf you want the adler32 or crc32 hash functions, they are available in the zlib module.\\n\\nHash algorithms¶\\n\\nThere is one constructor method named for each type of hash. All return a hash object with the same simple interface. For example: use sha256() to create a SHA-256 hash object. You can now feed this object with bytes-like objects (normally bytes) using the update method. At any point you can ask it for the digest of the concatenation of the data fed to it so far using the digest() or hexdigest() methods.\\n\\nTo allow multithreading, the Python GIL is released while computing a hash supplied more than 2047 bytes of data at once in its constructor or .update method.\\n\\nConstructors for hash algorithms that are always present in this module are sha1(), sha224(), sha256(), sha384(), sha512(), sha3_224(), sha3_256(), sha3_384(), sha3_512(), shake_128(), shake_256(), blake2b(), and blake2s(). 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 algorithms_guaranteed.\\n\\nAdditional algorithms may also be available if your Python distribution’s 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 new(). See algorithms_available.\\n\\nWarning\\n\\nSome algorithms have known hash collision weaknesses (including MD5 and SHA1). Refer to Attacks on cryptographic hash algorithms and the hashlib-seealso section at the end of this document.\\n\\nAdded in version 3.6: SHA3 (Keccak) and SHAKE constructors sha3_224(), sha3_256(), sha3_384(), sha3_512(), shake_128(), shake_256() were added. blake2b() and blake2s() were added.\\n\\nChanged in version 3.9: All hashlib constructors take a keyword-only argument usedforsecurity with default value True. A false value allows the use of insecure and blocked hashing algorithms in restricted environments. False indicates that the hashing algorithm is not used in a security context, e.g. as a non-cryptographic one-way compression function.\\n\\nChanged in version 3.9: Hashlib now uses SHA3 and SHAKE from OpenSSL if it provides it.\\n\\nChanged in version 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.\\n\\nDeprecated since version 3.15, will be removed in version 3.19: The undocumented string keyword parameter in _hashlib.new() and hash-named constructors such as _md5.md5() is deprecated. Prefer passing the initial data as a positional argument for maximum backwards compatibility.\\n\\nUsage¶\\n\\nTo obtain the digest of the byte string b\"Nobody inspects the spammish repetition\":\\n\\n>>> import hashlib\\n>>> m = hashlib.sha256()\\n>>> m.update(b\"Nobody inspects\")\\n>>> m.update(b\" the spammish repetition\")\\n>>> m.digest()\\nb\\'\\\\x03\\\\x1e\\\\xdd}Ae\\\\x15\\\\x93\\\\xc5\\\\xfe\\\\\\\\\\\\x00o\\\\xa5u+7\\\\xfd\\\\xdf\\\\xf7\\\\xbcN\\\\x84:\\\\xa6\\\\xaf\\\\x0c\\\\x95\\\\x0fK\\\\x94\\\\x06\\'\\n>>> m.hexdigest()\\n\\'031edd7d41651593c5fe5c006fa5752b37fddff7bc4e843aa6af0c950f4b9406\\'\\n\\nMore condensed:\\n\\n>>> hashlib.sha256(b\"Nobody inspects the spammish repetition\").hexdigest()\\n\\'031edd7d41651593c5fe5c006fa5752b37fddff7bc4e843aa6af0c950f4b9406\\'\\n\\nConstructors¶\\n\\nUsing new() with an algorithm name:\\n\\n>>> h = hashlib.new(\\'sha256\\')\\n>>> h.update(b\"Nobody inspects the spammish repetition\")\\n>>> h.hexdigest()\\n\\'031edd7d41651593c5fe5c006fa5752b37fddff7bc4e843aa6af0c950f4b9406\\'\\n\\nNamed constructors such as these are faster than passing an algorithm name to new().\\n\\nAttributes¶\\n\\nHashlib provides the following constant module attributes:\\n\\nHash Objects¶\\n\\nThe following values are provided as constant attributes of the hash objects returned by the constructors:\\n\\nA hash object has the following attributes:\\n\\nA hash object has the following methods:\\n\\nSHAKE variable length digests¶\\n\\nThe shake_128() and 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.\\n\\nExample use:\\n\\n>>> h = hashlib.shake_256(b\\'Nobody inspects the spammish repetition\\')\\n>>> h.hexdigest(20)\\n\\'44709d6fcb83d92a76dcb0b668c98e1b1d3dafe7\\'\\n\\nFile hashing¶\\n\\nThe hashlib module provides a helper function for efficient hashing of a file or file-like object.\\n\\nKey derivation¶\\n\\nKey derivation and key stretching algorithms are designed for secure password hashing. Naive algorithms such as sha1(password) are not resistant against brute-force attacks. A good password hashing function must be tunable, slow, and include a salt.\\n\\nBLAKE2¶\\n\\nBLAKE2 is a cryptographic hash function defined in RFC 7693 that comes in two flavors:\\n\\nBLAKE2b, optimized for 64-bit platforms and produces digests of any size between 1 and 64 bytes,\\n\\nBLAKE2s, optimized for 8- to 32-bit platforms and produces digests of any size between 1 and 32 bytes.\\n\\nBLAKE2 supports keyed mode (a faster and simpler replacement for HMAC), salted hashing, personalization, and tree hashing.\\n\\nHash objects from this module follow the API of standard library’s hashlib objects.\\n\\nCreating hash objects¶\\n\\nNew hash objects are created by calling constructor functions:\\n\\nThese functions return the corresponding hash objects for calculating BLAKE2b or BLAKE2s. They optionally take these general parameters:\\n\\ndata: initial chunk of data to hash, which must be bytes-like object. It can be passed only as positional argument.\\n\\ndigest_size: size of output digest in bytes.\\n\\nkey: key for keyed hashing (up to 64 bytes for BLAKE2b, up to 32 bytes for BLAKE2s).\\n\\nsalt: salt for randomized hashing (up to 16 bytes for BLAKE2b, up to 8 bytes for BLAKE2s).\\n\\nperson: personalization string (up to 16 bytes for BLAKE2b, up to 8 bytes for BLAKE2s).\\n\\nThe following table shows limits for general parameters (in bytes):\\n\\nHash digest_size len(key) len(salt) len(person) BLAKE2b 64 64 16 16 BLAKE2s 32 32 8 8\\n\\nNote\\n\\nBLAKE2 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, b\\'salt\\' and b\\'salt\\\\x00\\' is the same value. (This is not the case for key.)\\n\\nThese sizes are available as module constants described below.\\n\\nConstructor functions also accept the following tree hashing parameters:\\n\\nfanout: fanout (0 to 255, 0 if unlimited, 1 in sequential mode).\\n\\ndepth: maximal depth of tree (1 to 255, 255 if unlimited, 1 in sequential mode).\\n\\nleaf_size: maximal byte length of leaf (0 to 2**32-1, 0 if unlimited or in sequential mode).\\n\\nnode_offset: node offset (0 to 2**64-1 for BLAKE2b, 0 to 2**48-1 for BLAKE2s, 0 for the first, leftmost, leaf, or in sequential mode).\\n\\nnode_depth: node depth (0 to 255, 0 for leaves, or in sequential mode).\\n\\ninner_size: inner digest size (0 to 64 for BLAKE2b, 0 to 32 for BLAKE2s, 0 in sequential mode).\\n\\nlast_node: boolean indicating whether the processed node is the last one (False for sequential mode).\\n\\nSee section 2.10 in BLAKE2 specification for comprehensive review of tree hashing.\\n\\nConstants¶\\n\\nSalt length (maximum length accepted by constructors).\\n\\nPersonalization string length (maximum length accepted by constructors).\\n\\nMaximum key size.\\n\\nMaximum digest size that the hash function can output.\\n\\nExamples¶\\n\\nSimple hashing¶\\n\\nTo calculate hash of some data, you should first construct a hash object by calling the appropriate constructor function (blake2b() or blake2s()), then update it with the data by calling update() on the object, and, finally, get the digest out of the object by calling digest() (or hexdigest() for hex-encoded string).\\n\\n>>> from hashlib import blake2b\\n>>> h = blake2b()\\n>>> h.update(b\\'Hello world\\')\\n>>> h.hexdigest()\\n\\'6ff843ba685842aa82031d3f53c48b66326df7639a63d128974c5c14f31a0f33343a8c65551134ed1ae0f2b0dd2bb495dc81039e3eeb0aa1bb0388bbeac29183\\'\\n\\nAs a shortcut, you can pass the first chunk of data to update directly to the constructor as the positional argument:\\n\\n>>> from hashlib import blake2b\\n>>> blake2b(b\\'Hello world\\').hexdigest()\\n\\'6ff843ba685842aa82031d3f53c48b66326df7639a63d128974c5c14f31a0f33343a8c65551134ed1ae0f2b0dd2bb495dc81039e3eeb0aa1bb0388bbeac29183\\'\\n\\nYou can call hash.update() as many times as you need to iteratively update the hash:\\n\\n>>> from hashlib import blake2b\\n>>> items = [b\\'Hello\\', b\\' \\', b\\'world\\']\\n>>> h = blake2b()\\n>>> for item in items:\\n... h.update(item)\\n...\\n>>> h.hexdigest()\\n\\'6ff843ba685842aa82031d3f53c48b66326df7639a63d128974c5c14f31a0f33343a8c65551134ed1ae0f2b0dd2bb495dc81039e3eeb0aa1bb0388bbeac29183\\'\\n\\nUsing different digest sizes¶\\n\\nBLAKE2 has configurable size of digests up to 64 bytes for BLAKE2b and up to 32 bytes for BLAKE2s. For example, to replace SHA-1 with BLAKE2b without changing the size of output, we can tell BLAKE2b to produce 20-byte digests:\\n\\n>>> from hashlib import blake2b\\n>>> h = blake2b(digest_size=20)\\n>>> h.update(b\\'Replacing SHA1 with the more secure function\\')\\n>>> h.hexdigest()\\n\\'d24f26cf8de66472d58d4e1b1774b4c9158b1f4c\\'\\n>>> h.digest_size\\n20\\n>>> len(h.digest())\\n20\\n\\nHash 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:\\n\\n>>> from hashlib import blake2b, blake2s\\n>>> blake2b(digest_size=10).hexdigest()\\n\\'6fa1d8fcfd719046d762\\'\\n>>> blake2b(digest_size=11).hexdigest()\\n\\'eb6ec15daf9546254f0809\\'\\n>>> blake2s(digest_size=10).hexdigest()\\n\\'1bf21a98c78a1c376ae9\\'\\n>>> blake2s(digest_size=11).hexdigest()\\n\\'567004bf96e4a25773ebf4\\'\\n\\nKeyed hashing¶\\n\\nKeyed hashing can be used for authentication as a faster and simpler replacement for Hash-based message authentication code (HMAC). BLAKE2 can be securely used in prefix-MAC mode thanks to the indifferentiability property inherited from BLAKE.\\n\\nThis example shows how to get a (hex-encoded) 128-bit authentication code for message b\\'message data\\' with key b\\'pseudorandom key\\':\\n\\n>>> from hashlib import blake2b\\n>>> h = blake2b(key=b\\'pseudorandom key\\', digest_size=16)\\n>>> h.update(b\\'message data\\')\\n>>> h.hexdigest()\\n\\'3d363ff7401e02026f4a4687d4863ced\\'\\n\\nAs 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:\\n\\n>>> from hashlib import blake2b\\n>>> from hmac import compare_digest\\n>>>\\n>>> SECRET_KEY = b\\'pseudorandomly generated server secret key\\'\\n>>> AUTH_SIZE = 16\\n>>>\\n>>> def sign(cookie):\\n... h = blake2b(digest_size=AUTH_SIZE, key=SECRET_KEY)\\n... h.update(cookie)\\n... return h.hexdigest().encode(\\'utf-8\\')\\n>>>\\n>>> def verify(cookie, sig):\\n... good_sig = sign(cookie)\\n... return compare_digest(good_sig, sig)\\n>>>\\n>>> cookie = b\\'user-alice\\'\\n>>> sig = sign(cookie)\\n>>> print(\"{0},{1}\".format(cookie.decode(\\'utf-8\\'), sig))\\nuser-alice,b\\'43b3c982cf697e0c5ab22172d1ca7421\\'\\n>>> verify(cookie, sig)\\nTrue\\n>>> verify(b\\'user-bob\\', sig)\\nFalse\\n>>> verify(cookie, b\\'0102030405060708090a0b0c0d0e0f00\\')\\nFalse\\n\\nEven though there’s a native keyed hashing mode, BLAKE2 can, of course, be used in HMAC construction with hmac module:\\n\\n>>> import hmac, hashlib\\n>>> m = hmac.new(b\\'secret key\\', digestmod=hashlib.blake2s)\\n>>> m.update(b\\'message\\')\\n>>> m.hexdigest()\\n\\'e3c8102868d28b5ff85fc35dda07329970d1a01e273c37481326fe0c861c8142\\'\\n\\nRandomized hashing¶\\n\\nBy 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.\\n\\nRandomized 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.\\n\\n(NIST SP-800-106 “Randomized Hashing for Digital Signatures”)\\n\\nIn 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.\\n\\nWarning\\n\\nSalted 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 for more information.\\n\\n>>> import os\\n>>> from hashlib import blake2b\\n>>> msg = b\\'some message\\'\\n>>> # Calculate the first hash with a random salt.\\n>>> salt1 = os.urandom(blake2b.SALT_SIZE)\\n>>> h1 = blake2b(salt=salt1)\\n>>> h1.update(msg)\\n>>> # Calculate the second hash with a different random salt.\\n>>> salt2 = os.urandom(blake2b.SALT_SIZE)\\n>>> h2 = blake2b(salt=salt2)\\n>>> h2.update(msg)\\n>>> # The digests are different.\\n>>> h1.digest() != h2.digest()\\nTrue\\n\\nPersonalization¶\\n\\nSometimes 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:\\n\\nWe 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.\\n\\n(The Skein Hash Function Family, p. 21)\\n\\nBLAKE2 can be personalized by passing bytes to the person argument:\\n\\n>>> from hashlib import blake2b\\n>>> FILES_HASH_PERSON = b\\'MyApp Files Hash\\'\\n>>> BLOCK_HASH_PERSON = b\\'MyApp Block Hash\\'\\n>>> h = blake2b(digest_size=32, person=FILES_HASH_PERSON)\\n>>> h.update(b\\'the same content\\')\\n>>> h.hexdigest()\\n\\'20d9cd024d4fb086aae819a1432dd2466de12947831b75c5a30cf2676095d3b4\\'\\n>>> h = blake2b(digest_size=32, person=BLOCK_HASH_PERSON)\\n>>> h.update(b\\'the same content\\')\\n>>> h.hexdigest()\\n\\'cf68fb5761b9c44e7878bfb2c4c9aea52264a80b75005e65619778de59f383a3\\'\\n\\nPersonalization together with the keyed mode can also be used to derive different keys from a single one.\\n\\n>>> from hashlib import blake2s\\n>>> from base64 import b64decode, b64encode\\n>>> orig_key = b64decode(b\\'Rm5EPJai72qcK3RGBpW3vPNfZy5OZothY+kHY6h21KM=\\')\\n>>> enc_key = blake2s(key=orig_key, person=b\\'kEncrypt\\').digest()\\n>>> mac_key = blake2s(key=orig_key, person=b\\'kMAC\\').digest()\\n>>> print(b64encode(enc_key).decode(\\'utf-8\\'))\\nrbPb15S/Z9t+agffno5wuhB77VbRi6F9Iv2qIxU7WHw=\\n>>> print(b64encode(mac_key).decode(\\'utf-8\\'))\\nG9GtHFE1YluXY1zWPlYk1e/nWfu0WSEb0KRcjhDeP/o=\\n\\nTree mode¶\\n\\nHere’s an example of hashing a minimal tree with two leaf nodes:\\n\\n 10\\n / \\\\\\n00 01\\n\\nThis example uses 64-byte internal digests, and returns the 32-byte final digest:\\n\\n>>> from hashlib import blake2b\\n>>>\\n>>> FANOUT = 2\\n>>> DEPTH = 2\\n>>> LEAF_SIZE = 4096\\n>>> INNER_SIZE = 64\\n>>>\\n>>> buf = bytearray(6000)\\n>>>\\n>>> # Left leaf\\n... h00 = blake2b(buf[0:LEAF_SIZE], fanout=FANOUT, depth=DEPTH,\\n... leaf_size=LEAF_SIZE, inner_size=INNER_SIZE,\\n... node_offset=0, node_depth=0, last_node=False)\\n>>> # Right leaf\\n... h01 = blake2b(buf[LEAF_SIZE:], fanout=FANOUT, depth=DEPTH,\\n... leaf_size=LEAF_SIZE, inner_size=INNER_SIZE,\\n... node_offset=1, node_depth=0, last_node=True)\\n>>> # Root node\\n... h10 = blake2b(digest_size=32, fanout=FANOUT, depth=DEPTH,\\n... leaf_size=LEAF_SIZE, inner_size=INNER_SIZE,\\n... node_offset=0, node_depth=1, last_node=True)\\n>>> h10.update(h00.digest())\\n>>> h10.update(h01.digest())\\n>>> h10.hexdigest()\\n\\'3ad2a9b37c6070e374c7a8c508fe20ca86b6ed54e286e93a0318e95e881db5aa\\'\\n\\nCredits¶\\n\\nBLAKE2 was designed by Jean-Philippe Aumasson, Samuel Neves, Zooko Wilcox-O’Hearn, and Christian Winnerlein based on SHA-3 finalist BLAKE created by Jean-Philippe Aumasson, Luca Henzen, Willi Meier, and Raphael C.-W. Phan.\\n\\nIt uses core algorithm from ChaCha cipher designed by Daniel J. Bernstein.\\n\\nThe stdlib implementation is based on pyblake2 module. It was written by Dmitry Chestnykh based on C implementation written by Samuel Neves. The documentation was copied from pyblake2 and written by Dmitry Chestnykh.\\n\\nThe C code was partly rewritten for Python by Christian Heimes.\\n\\nThe following public domain dedication applies for both C hash function implementation, extension code, and this documentation:\\n\\nTo 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.\\n\\nYou should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see https://creativecommons.org/publicdomain/zero/1.0/.\\n\\nThe 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:\\n\\nAlexandr Sokolovskiy\\n\\nSee also\\n\\nTable of Contents\\n\\nhashlib — Secure hashes and message digests\\n\\nHash algorithms\\n\\nUsage\\n\\nConstructors\\n\\nAttributes\\n\\nHash Objects\\n\\nSHAKE variable length digests\\n\\nFile hashing\\n\\nKey derivation\\n\\nBLAKE2\\n\\nCreating hash objects\\n\\nConstants\\n\\nExamples\\n\\nSimple hashing\\n\\nUsing different digest sizes\\n\\nKeyed hashing\\n\\nRandomized hashing\\n\\nPersonalization\\n\\nTree mode\\n\\nCredits\\n\\nPrevious topic\\n\\nCryptographic Services\\n\\nNext topic\\n\\nhmac — Keyed-Hashing for Message Authentication\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nCryptographic Services »\\n\\nhashlib — Secure hashes and message digests\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\heapq.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Types »\\n\\nheapq — Heap queue algorithm\\n\\n|\\n\\nheapq — Heap queue algorithm¶\\n\\nSource code: Lib/heapq.py\\n\\nThis module provides an implementation of the heap queue algorithm, also known as the priority queue algorithm.\\n\\nMin-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.\\n\\nFor min-heaps, this implementation uses lists for which heap[k] <= heap[2*k+1] and 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, heap[0].\\n\\nMax-heaps satisfy the reverse invariant: every parent node has a value greater than any of its children. These are implemented as lists for which maxheap[2*k+1] <= maxheap[k] and maxheap[2*k+2] <= maxheap[k] for all k for which the compared elements exist. The root, maxheap[0], contains the largest element; heap.sort(reverse=True) maintains the max-heap invariant.\\n\\nThe 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 lists.\\n\\nThese two aspects make it possible to view the heap as a regular Python list without surprises: heap[0] is the smallest item, and heap.sort() maintains the heap invariant!\\n\\nLike list.sort(), this implementation uses only the < operator for comparisons, for both min-heaps and max-heaps.\\n\\nIn 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 _max suffix.\\n\\nTo create a heap, use a list initialized as [], or transform an existing list into a min-heap or max-heap using the heapify() or heapify_max() functions, respectively.\\n\\nThe following functions are provided for min-heaps:\\n\\nFor max-heaps, the following functions are provided:\\n\\nThe module also offers three general purpose functions based on heaps.\\n\\nThe latter two functions perform best for smaller values of n. For larger values, it is more efficient to use the sorted() function. Also, when n==1, it is more efficient to use the built-in min() and max() functions. If repeated usage of these functions is required, consider turning the iterable into an actual heap.\\n\\nBasic Examples¶\\n\\nA heapsort can be implemented by pushing all values onto a heap and then popping off the smallest values one at a time:\\n\\n>>> def heapsort(iterable):\\n... h = []\\n... for value in iterable:\\n... heappush(h, value)\\n... return [heappop(h) for i in range(len(h))]\\n...\\n>>> heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])\\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\\n\\nThis is similar to sorted(iterable), but unlike sorted(), this implementation is not stable.\\n\\nHeap elements can be tuples. This is useful for assigning comparison values (such as task priorities) alongside the main record being tracked:\\n\\n>>> h = []\\n>>> heappush(h, (5, \\'write code\\'))\\n>>> heappush(h, (7, \\'release product\\'))\\n>>> heappush(h, (1, \\'write spec\\'))\\n>>> heappush(h, (3, \\'create tests\\'))\\n>>> heappop(h)\\n(1, \\'write spec\\')\\n\\nOther Applications¶\\n\\nMedians 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 that updates continuously as new data arrives.\\n\\nA 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:\\n\\ndef running_median(iterable):\\n \"Yields the cumulative median of values seen so far.\"\\n\\n lo = [] # max-heap\\n hi = [] # min-heap (same size as or one smaller than lo)\\n\\n for x in iterable:\\n if len(lo) == len(hi):\\n heappush_max(lo, heappushpop(hi, x))\\n yield lo[0]\\n else:\\n heappush(hi, heappushpop_max(lo, x))\\n yield (lo[0] + hi[0]) / 2\\n\\nFor example:\\n\\n>>> list(running_median([5.0, 9.0, 4.0, 12.0, 8.0, 9.0]))\\n[5.0, 7.0, 5.0, 7.0, 8.0, 8.5]\\n\\nPriority Queue Implementation Notes¶\\n\\nA priority queue is common use for a heap, and it presents several implementation challenges:\\n\\nSort stability: how do you get two tasks with equal priorities to be returned in the order they were originally added?\\n\\nTuple comparison breaks for (priority, task) pairs if the priorities are equal and the tasks do not have a default comparison order.\\n\\nIf the priority of a task changes, how do you move it to a new position in the heap?\\n\\nOr if a pending task needs to be deleted, how do you find it and remove it from the queue?\\n\\nA solution to the first two challenges is to store entries as 3-element list including the priority, an entry count, and the task. The entry count serves as a tie-breaker so that two tasks with the same priority are returned in the order they were added. And since no two entry counts are the same, the tuple comparison will never attempt to directly compare two tasks.\\n\\nAnother solution to the problem of non-comparable tasks is to create a wrapper class that ignores the task item and only compares the priority field:\\n\\nfrom dataclasses import dataclass, field\\nfrom typing import Any\\n\\n@dataclass(order=True)\\nclass PrioritizedItem:\\n priority: int\\n item: Any=field(compare=False)\\n\\nThe remaining challenges revolve around finding a pending task and making changes to its priority or removing it entirely. Finding a task can be done with a dictionary pointing to an entry in the queue.\\n\\nRemoving the entry or changing its priority is more difficult because it would break the heap structure invariants. So, a possible solution is to mark the entry as removed and add a new entry with the revised priority:\\n\\npq = [] # list of entries arranged in a heap\\nentry_finder = {} # mapping of tasks to entries\\nREMOVED = \\'\\' # placeholder for a removed task\\ncounter = itertools.count() # unique sequence count\\n\\ndef add_task(task, priority=0):\\n \\'Add a new task or update the priority of an existing task\\'\\n if task in entry_finder:\\n remove_task(task)\\n count = next(counter)\\n entry = [priority, count, task]\\n entry_finder[task] = entry\\n heappush(pq, entry)\\n\\ndef remove_task(task):\\n \\'Mark an existing task as REMOVED. Raise KeyError if not found.\\'\\n entry = entry_finder.pop(task)\\n entry[-1] = REMOVED\\n\\ndef pop_task():\\n \\'Remove and return the lowest priority task. Raise KeyError if empty.\\'\\n while pq:\\n priority, count, task = heappop(pq)\\n if task is not REMOVED:\\n del entry_finder[task]\\n return task\\n raise KeyError(\\'pop from an empty priority queue\\')\\n\\nTheory¶\\n\\nHeaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for all k, counting elements from 0. For the sake of comparison, non-existing elements are considered to be infinite. The interesting property of a heap is that a[0] is always its smallest element.\\n\\nThe strange invariant above is meant to be an efficient memory representation for a tournament. The numbers below are k, not a[k]:\\n\\nIn the tree above, each cell k is topping 2*k+1 and 2*k+2. In a usual binary tournament we see in sports, each cell is the winner over the two cells it tops, and we can trace the winner down the tree to see all opponents s/he had. However, in many computer applications of such tournaments, we do not need to trace the history of a winner. To be more memory efficient, when a winner is promoted, we try to replace it by something else at a lower level, and the rule becomes that a cell and the two cells it tops contain three different items, but the top cell “wins” over the two topped cells.\\n\\nIf this heap invariant is protected at all time, index 0 is clearly the overall winner. The simplest algorithmic way to remove it and find the “next” winner is to move some loser (let’s say cell 30 in the diagram above) into the 0 position, and then percolate this new 0 down the tree, exchanging values, until the invariant is re-established. This is clearly logarithmic on the total number of items in the tree. By iterating over all items, you get an O(n log n) sort.\\n\\nA nice feature of this sort is that you can efficiently insert new items while the sort is going on, provided that the inserted items are not “better” than the last 0’th element you extracted. This is especially useful in simulation contexts, where the tree holds all incoming events, and the “win” condition means the smallest scheduled time. When an event schedules other events for execution, they are scheduled into the future, so they can easily go into the heap. So, a heap is a good structure for implementing schedulers (this is what I used for my MIDI sequencer :-).\\n\\nVarious structures for implementing schedulers have been extensively studied, and heaps are good for this, as they are reasonably speedy, the speed is almost constant, and the worst case is not much different than the average case. However, there are other representations which are more efficient overall, yet the worst cases might be terrible.\\n\\nHeaps are also very useful in big disk sorts. You most probably all know that a big sort implies producing “runs” (which are pre-sorted sequences, whose size is usually related to the amount of CPU memory), followed by a merging passes for these runs, which merging is often very cleverly organised [1]. It is very important that the initial sort produces the longest runs possible. Tournaments are a good way to achieve that. If, using all the memory available to hold a tournament, you replace and percolate items that happen to fit the current run, you’ll produce runs which are twice the size of the memory for random input, and much better for input fuzzily ordered.\\n\\nMoreover, if you output the 0’th item on disk and get an input which may not fit in the current tournament (because the value “wins” over the last output value), it cannot fit in the heap, so the size of the heap decreases. The freed memory could be cleverly reused immediately for progressively building a second heap, which grows at exactly the same rate the first heap is melting. When the first heap completely vanishes, you switch heaps and start a new run. Clever and quite effective!\\n\\nIn a word, heaps are useful memory structures to know. I use them in a few applications, and I think it is good to keep a ‘heap’ module around. :-)\\n\\nFootnotes\\n\\n[1]\\n\\nThe disk balancing algorithms which are current, nowadays, are more annoying than clever, and this is a consequence of the seeking capabilities of the disks. On devices which cannot seek, like big tape drives, the story was quite different, and one had to be very clever to ensure (far in advance) that each tape movement will be the most effective possible (that is, will best participate at “progressing” the merge). Some tapes were even able to read backwards, and this was also used to avoid the rewinding time. Believe me, real good tape sorts were quite spectacular to watch! From all times, sorting has always been a Great Art! :-)\\n\\nTable of Contents\\n\\nheapq — Heap queue algorithm\\n\\nBasic Examples\\n\\nOther Applications\\n\\nPriority Queue Implementation Notes\\n\\nTheory\\n\\nPrevious topic\\n\\ncollections.abc — Abstract Base Classes for Containers\\n\\nNext topic\\n\\nbisect — Array bisection algorithm\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Types »\\n\\nheapq — Heap queue algorithm\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\hmac.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nCryptographic Services »\\n\\nhmac — Keyed-Hashing for Message Authentication\\n\\n|\\n\\nhmac — Keyed-Hashing for Message Authentication¶\\n\\nSource code: Lib/hmac.py\\n\\nThis module implements the HMAC algorithm as described by RFC 2104. 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.\\n\\nA hash object has the following attributes:\\n\\nChanged in version 3.10: Removed the undocumented attributes HMAC.digest_cons, HMAC.inner, and HMAC.outer.\\n\\nThis module also provides the following helper function:\\n\\nSee also\\n\\nPrevious topic\\n\\nhashlib — Secure hashes and message digests\\n\\nNext topic\\n\\nsecrets — Generate secure random numbers for managing secrets\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nCryptographic Services »\\n\\nhmac — Keyed-Hashing for Message Authentication\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\html.entities.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nStructured Markup Processing Tools »\\n\\nhtml.entities — Definitions of HTML general entities\\n\\n|\\n\\nhtml.entities — Definitions of HTML general entities¶\\n\\nSource code: Lib/html/entities.py\\n\\nThis module defines four dictionaries, html5, name2codepoint, codepoint2name, and entitydefs.\\n\\nFootnotes\\n\\n[1]\\n\\nSee https://html.spec.whatwg.org/multipage/named-characters.html#named-character-references\\n\\nPrevious topic\\n\\nhtml.parser — Simple HTML and XHTML parser\\n\\nNext topic\\n\\nXML Processing Modules\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nStructured Markup Processing Tools »\\n\\nhtml.entities — Definitions of HTML general entities\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\html.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nStructured Markup Processing Tools »\\n\\nhtml — HyperText Markup Language support\\n\\n|\\n\\nhtml — HyperText Markup Language support¶\\n\\nSource code: Lib/html/__init__.py\\n\\nThis module defines utilities to manipulate HTML.\\n\\nSubmodules in the html package are:\\n\\nhtml.parser – HTML/XHTML parser with lenient parsing mode\\n\\nhtml.entities – HTML entity definitions\\n\\nPrevious topic\\n\\nStructured Markup Processing Tools\\n\\nNext topic\\n\\nhtml.parser — Simple HTML and XHTML parser\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nStructured Markup Processing Tools »\\n\\nhtml — HyperText Markup Language support\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\html.parser.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nStructured Markup Processing Tools »\\n\\nhtml.parser — Simple HTML and XHTML parser\\n\\n|\\n\\nhtml.parser — Simple HTML and XHTML parser¶\\n\\nSource code: Lib/html/parser.py\\n\\nThis module defines a class HTMLParser which serves as the basis for parsing text files formatted in HTML (HyperText Mark-up Language) and XHTML.\\n\\nExample HTML Parser Application¶\\n\\nAs a basic example, below is a simple HTML parser that uses the HTMLParser class to print out start tags, end tags, and data as they are encountered:\\n\\nfrom html.parser import HTMLParser\\n\\nclass MyHTMLParser(HTMLParser):\\n def handle_starttag(self, tag, attrs):\\n print(\"Encountered a start tag:\", tag)\\n\\n def handle_endtag(self, tag):\\n print(\"Encountered an end tag :\", tag)\\n\\n def handle_data(self, data):\\n print(\"Encountered some data :\", data)\\n\\nparser = MyHTMLParser()\\nparser.feed(\\'Test\\'\\n \\'

Parse me!

\\')\\n\\nThe output will then be:\\n\\nEncountered a start tag: html\\nEncountered a start tag: head\\nEncountered a start tag: title\\nEncountered some data : Test\\nEncountered an end tag : title\\nEncountered an end tag : head\\nEncountered a start tag: body\\nEncountered a start tag: h1\\nEncountered some data : Parse me!\\nEncountered an end tag : h1\\nEncountered an end tag : body\\nEncountered an end tag : html\\n\\nHTMLParser Methods¶\\n\\nHTMLParser instances have the following methods:\\n\\nThe following methods are called when data or markup elements are encountered and they are meant to be overridden in a subclass. The base class implementations do nothing (except for handle_startendtag()):\\n\\nExamples¶\\n\\nThe following class implements a parser that will be used to illustrate more examples:\\n\\nfrom html.parser import HTMLParser\\nfrom html.entities import name2codepoint\\n\\nclass MyHTMLParser(HTMLParser):\\n def handle_starttag(self, tag, attrs):\\n print(\"Start tag:\", tag)\\n for attr in attrs:\\n print(\" attr:\", attr)\\n\\n def handle_endtag(self, tag):\\n print(\"End tag :\", tag)\\n\\n def handle_data(self, data):\\n print(\"Data :\", data)\\n\\n def handle_comment(self, data):\\n print(\"Comment :\", data)\\n\\n def handle_entityref(self, name):\\n c = chr(name2codepoint[name])\\n print(\"Named ent:\", c)\\n\\n def handle_charref(self, name):\\n if name.startswith(\\'x\\'):\\n c = chr(int(name[1:], 16))\\n else:\\n c = chr(int(name))\\n print(\"Num ent :\", c)\\n\\n def handle_decl(self, data):\\n print(\"Decl :\", data)\\n\\nparser = MyHTMLParser()\\n\\nParsing a doctype:\\n\\n>>> parser.feed(\\'\\')\\nDecl : DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\"\\n\\nParsing an element with a few attributes and a title:\\n\\n>>> parser.feed(\\'\"The\\')\\nStart tag: img\\n attr: (\\'src\\', \\'python-logo.png\\')\\n attr: (\\'alt\\', \\'The Python logo\\')\\n>>>\\n>>> parser.feed(\\'

Python

\\')\\nStart tag: h1\\nData : Python\\nEnd tag : h1\\n\\nThe content of elements like script and style is returned as is, without further parsing:\\n\\n>>> parser.feed(\\'\\')\\nStart tag: style\\n attr: (\\'type\\', \\'text/css\\')\\nData : #python { color: green }\\nEnd tag : style\\n\\n>>> parser.feed(\\'\\')\\nStart tag: script\\n attr: (\\'type\\', \\'text/javascript\\')\\nData : alert(\"hello! ☺\");\\nEnd tag : script\\n\\nParsing comments:\\n\\n>>> parser.feed(\\'\\'\\n... \\'\\')\\nComment : a comment\\nComment : [if IE 9]>IE-specific content\\'):\\n\\n>>> parser = MyHTMLParser()\\n>>> parser.feed(\\'>>>\\')\\nData : >>>\\n\\n>>> parser = MyHTMLParser(convert_charrefs=False)\\n>>> parser.feed(\\'>>>\\')\\nNamed ent: >\\nNum ent : >\\nNum ent : >\\n\\nFeeding incomplete chunks to feed() works, but handle_data() might be called more than once if convert_charrefs is false:\\n\\n>>> for chunk in [\\'buff\\', \\'ered\\', \\' text\\']:\\n... parser.feed(chunk)\\n...\\nStart tag: span\\nData : buff\\nData : ered\\nData : text\\nEnd tag : span\\n\\nParsing invalid HTML (e.g. unquoted attributes) also works:\\n\\n>>> parser.feed(\\'

tag soup

\\')\\nStart tag: p\\nStart tag: a\\n attr: (\\'class\\', \\'link\\')\\n attr: (\\'href\\', \\'#main\\')\\nData : tag soup\\nEnd tag : p\\nEnd tag : a\\n\\nTable of Contents\\n\\nhtml.parser — Simple HTML and XHTML parser\\n\\nExample HTML Parser Application\\n\\nHTMLParser Methods\\n\\nExamples\\n\\nPrevious topic\\n\\nhtml — HyperText Markup Language support\\n\\nNext topic\\n\\nhtml.entities — Definitions of HTML general entities\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nStructured Markup Processing Tools »\\n\\nhtml.parser — Simple HTML and XHTML parser\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\http.client.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Protocols and Support »\\n\\nhttp.client — HTTP protocol client\\n\\n|\\n\\nhttp.client — HTTP protocol client¶\\n\\nSource code: Lib/http/client.py\\n\\nThis module defines classes that implement the client side of the HTTP and HTTPS protocols. It is normally not used directly — the module urllib.request uses it to handle URLs that use HTTP and HTTPS.\\n\\nSee also\\n\\nThe Requests package is recommended for a higher-level HTTP client interface.\\n\\nNote\\n\\nHTTPS support is only available if Python was compiled with SSL support (through the ssl module).\\n\\nAvailability: not WASI.\\n\\nThis module does not work or is not available on WebAssembly. See WebAssembly platforms for more information.\\n\\nThe module provides the following classes:\\n\\nThis module provides the following function:\\n\\nThe following exceptions are raised as appropriate:\\n\\nThe constants defined in this module are:\\n\\nSee HTTP status codes for a list of HTTP status codes that are available in this module as constants.\\n\\nHTTPConnection Objects¶\\n\\nHTTPConnection instances have the following methods:\\n\\nAs an alternative to using the request() method described above, you can also send your request step by step, by using the four functions below.\\n\\nHTTPResponse Objects¶\\n\\nAn HTTPResponse instance wraps the HTTP response from the server. It provides access to the request headers and the entity body. The response is an iterable object and can be used in a with statement.\\n\\nChanged in version 3.5: The io.BufferedIOBase interface is now implemented and all of its reader operations are supported.\\n\\nExamples¶\\n\\nHere is an example session that uses the GET method:\\n\\n>>> import http.client\\n>>> conn = http.client.HTTPSConnection(\"www.python.org\")\\n>>> conn.request(\"GET\", \"/\")\\n>>> r1 = conn.getresponse()\\n>>> print(r1.status, r1.reason)\\n200 OK\\n>>> data1 = r1.read() # This will return entire content.\\n>>> # The following example demonstrates reading data in chunks.\\n>>> conn.request(\"GET\", \"/\")\\n>>> r1 = conn.getresponse()\\n>>> while chunk := r1.read(200):\\n... print(repr(chunk))\\nb\\'\\\\n| UnixStreamServer |\\n+-----------+ +------------------+\\n |\\n v\\n+-----------+ +--------------------+\\n| UDPServer |------->| UnixDatagramServer |\\n+-----------+ +--------------------+\\n\\nNote that UnixDatagramServer derives from UDPServer, not from UnixStreamServer — the only difference between an IP and a Unix server is the address family.\\n\\nAdded in version 3.12: The ForkingUnixStreamServer and ForkingUnixDatagramServer classes were added.\\n\\nTo implement a service, you must derive a class from BaseRequestHandler and redefine its handle() method. You can then run various versions of the service by combining one of the server classes with your request handler class. The request handler class must be different for datagram or stream services. This can be hidden by using the handler subclasses StreamRequestHandler or DatagramRequestHandler.\\n\\nOf course, you still have to use your head! For instance, it makes no sense to use a forking server if the service contains state in memory that can be modified by different requests, since the modifications in the child process would never reach the initial state kept in the parent process and passed to each child. In this case, you can use a threading server, but you will probably have to use locks to protect the integrity of the shared data.\\n\\nOn the other hand, if you are building an HTTP server where all data is stored externally (for instance, in the file system), a synchronous class will essentially render the service “deaf” while one request is being handled – which may be for a very long time if a client is slow to receive all the data it has requested. Here a threading or forking server is appropriate.\\n\\nIn some cases, it may be appropriate to process part of a request synchronously, but to finish processing in a forked child depending on the request data. This can be implemented by using a synchronous server and doing an explicit fork in the request handler class handle() method.\\n\\nAnother approach to handling multiple simultaneous requests in an environment that supports neither threads nor 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 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).\\n\\nServer Objects¶\\n\\nRequest Handler Objects¶\\n\\nExamples¶\\n\\nsocketserver.TCPServer Example¶\\n\\nThis is the server side:\\n\\nimport socketserver\\n\\nclass MyTCPHandler(socketserver.BaseRequestHandler):\\n \"\"\"\\n The request handler class for our server.\\n\\n It is instantiated once per connection to the server, and must\\n override the handle() method to implement communication to the\\n client.\\n \"\"\"\\n\\n def handle(self):\\n # self.request is the TCP socket connected to the client\\n pieces = [b\\'\\']\\n total = 0\\n while b\\'\\\\n\\' not in pieces[-1] and total < 10_000:\\n pieces.append(self.request.recv(2000))\\n total += len(pieces[-1])\\n self.data = b\\'\\'.join(pieces)\\n print(f\"Received from {self.client_address[0]}:\")\\n print(self.data.decode(\"utf-8\"))\\n # just send back the same data, but upper-cased\\n self.request.sendall(self.data.upper())\\n # after we return, the socket will be closed.\\n\\nif __name__ == \"__main__\":\\n HOST, PORT = \"localhost\", 9999\\n\\n # Create the server, binding to localhost on port 9999\\n with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server:\\n # Activate the server; this will keep running until you\\n # interrupt the program with Ctrl-C\\n server.serve_forever()\\n\\nAn alternative request handler class that makes use of streams (file-like objects that simplify communication by providing the standard file interface):\\n\\nclass MyTCPHandler(socketserver.StreamRequestHandler):\\n\\n def handle(self):\\n # self.rfile is a file-like object created by the handler.\\n # We can now use e.g. readline() instead of raw recv() calls.\\n # We limit ourselves to 10000 bytes to avoid abuse by the sender.\\n self.data = self.rfile.readline(10000).rstrip()\\n print(f\"{self.client_address[0]} wrote:\")\\n print(self.data.decode(\"utf-8\"))\\n # Likewise, self.wfile is a file-like object used to write back\\n # to the client\\n self.wfile.write(self.data.upper())\\n\\nThe difference is that the readline() call in the second handler will call recv() multiple times until it encounters a newline character, while the first handler had to use a recv() loop to accumulate data until a newline itself. If it had just used a single 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 send() or sendall() calls and the number of recv() calls on the server required to receive it.\\n\\nThis is the client side:\\n\\nimport socket\\nimport sys\\n\\nHOST, PORT = \"localhost\", 9999\\ndata = \" \".join(sys.argv[1:])\\n\\n# Create a socket (SOCK_STREAM means a TCP socket)\\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:\\n # Connect to server and send data\\n sock.connect((HOST, PORT))\\n sock.sendall(bytes(data, \"utf-8\"))\\n sock.sendall(b\"\\\\n\")\\n\\n # Receive data from the server and shut down\\n received = str(sock.recv(1024), \"utf-8\")\\n\\nprint(\"Sent: \", data)\\nprint(\"Received:\", received)\\n\\nThe output of the example should look something like this:\\n\\nServer:\\n\\n$ python TCPServer.py\\n127.0.0.1 wrote:\\nb\\'hello world with TCP\\'\\n127.0.0.1 wrote:\\nb\\'python is nice\\'\\n\\nClient:\\n\\n$ python TCPClient.py hello world with TCP\\nSent: hello world with TCP\\nReceived: HELLO WORLD WITH TCP\\n$ python TCPClient.py python is nice\\nSent: python is nice\\nReceived: PYTHON IS NICE\\n\\nsocketserver.UDPServer Example¶\\n\\nThis is the server side:\\n\\nimport socketserver\\n\\nclass MyUDPHandler(socketserver.BaseRequestHandler):\\n \"\"\"\\n This class works similar to the TCP handler class, except that\\n self.request consists of a pair of data and client socket, and since\\n there is no connection the client address must be given explicitly\\n when sending data back via sendto().\\n \"\"\"\\n\\n def handle(self):\\n data = self.request[0].strip()\\n socket = self.request[1]\\n print(f\"{self.client_address[0]} wrote:\")\\n print(data)\\n socket.sendto(data.upper(), self.client_address)\\n\\nif __name__ == \"__main__\":\\n HOST, PORT = \"localhost\", 9999\\n with socketserver.UDPServer((HOST, PORT), MyUDPHandler) as server:\\n server.serve_forever()\\n\\nThis is the client side:\\n\\nimport socket\\nimport sys\\n\\nHOST, PORT = \"localhost\", 9999\\ndata = \" \".join(sys.argv[1:])\\n\\n# SOCK_DGRAM is the socket type to use for UDP sockets\\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\\n\\n# As you can see, there is no connect() call; UDP has no connections.\\n# Instead, data is directly sent to the recipient via sendto().\\nsock.sendto(bytes(data + \"\\\\n\", \"utf-8\"), (HOST, PORT))\\nreceived = str(sock.recv(1024), \"utf-8\")\\n\\nprint(\"Sent: \", data)\\nprint(\"Received:\", received)\\n\\nThe output of the example should look exactly like for the TCP server example.\\n\\nAsynchronous Mixins¶\\n\\nTo build asynchronous handlers, use the ThreadingMixIn and ForkingMixIn classes.\\n\\nAn example for the ThreadingMixIn class:\\n\\nimport socket\\nimport threading\\nimport socketserver\\n\\nclass ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):\\n\\n def handle(self):\\n data = str(self.request.recv(1024), \\'ascii\\')\\n cur_thread = threading.current_thread()\\n response = bytes(\"{}: {}\".format(cur_thread.name, data), \\'ascii\\')\\n self.request.sendall(response)\\n\\nclass ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):\\n pass\\n\\ndef client(ip, port, message):\\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:\\n sock.connect((ip, port))\\n sock.sendall(bytes(message, \\'ascii\\'))\\n response = str(sock.recv(1024), \\'ascii\\')\\n print(\"Received: {}\".format(response))\\n\\nif __name__ == \"__main__\":\\n # Port 0 means to select an arbitrary unused port\\n HOST, PORT = \"localhost\", 0\\n\\n server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)\\n with server:\\n ip, port = server.server_address\\n\\n # Start a thread with the server -- that thread will then start one\\n # more thread for each request\\n server_thread = threading.Thread(target=server.serve_forever)\\n # Exit the server thread when the main thread terminates\\n server_thread.daemon = True\\n server_thread.start()\\n print(\"Server loop running in thread:\", server_thread.name)\\n\\n client(ip, port, \"Hello World 1\")\\n client(ip, port, \"Hello World 2\")\\n client(ip, port, \"Hello World 3\")\\n\\n server.shutdown()\\n\\nThe output of the example should look something like this:\\n\\n$ python ThreadedTCPServer.py\\nServer loop running in thread: Thread-1\\nReceived: Thread-2: Hello World 1\\nReceived: Thread-3: Hello World 2\\nReceived: Thread-4: Hello World 3\\n\\nThe ForkingMixIn class is used in the same way, except that the server will spawn a new process for each request. Available only on POSIX platforms that support fork().\\n\\nTable of Contents\\n\\nsocketserver — A framework for network servers\\n\\nServer Creation Notes\\n\\nServer Objects\\n\\nRequest Handler Objects\\n\\nExamples\\n\\nsocketserver.TCPServer Example\\n\\nsocketserver.UDPServer Example\\n\\nAsynchronous Mixins\\n\\nPrevious topic\\n\\nuuid — UUID objects according to RFC 9562\\n\\nNext topic\\n\\nhttp.server — HTTP servers\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Protocols and Support »\\n\\nsocketserver — A framework for network servers\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\spwd.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nRemoved Modules »\\n\\nspwd — The shadow password database\\n\\n|\\n\\nspwd — The shadow password database¶\\n\\nDeprecated since version 3.11, removed in version 3.13.\\n\\nThis module is no longer part of the Python standard library. It was removed in Python 3.13 after being deprecated in Python 3.11. The removal was decided in PEP 594.\\n\\nA possible replacement is the third-party library python-pam. This library is not supported or maintained by the Python core team.\\n\\nThe last version of Python that provided the spwd module was Python 3.12.\\n\\nPrevious topic\\n\\nsndhdr — Determine type of sound file\\n\\nNext topic\\n\\nsunau — Read and write Sun AU files\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nRemoved Modules »\\n\\nspwd — The shadow password database\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\sqlite3.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Persistence »\\n\\nsqlite3 — DB-API 2.0 interface for SQLite databases\\n\\n|\\n\\nsqlite3 — DB-API 2.0 interface for SQLite databases¶\\n\\nSource code: Lib/sqlite3/\\n\\nSQLite is a C library that provides a lightweight disk-based database that doesn’t require a separate server process and allows accessing the database using a nonstandard variant of the SQL query language. Some applications can use SQLite for internal data storage. It’s also possible to prototype an application using SQLite and then port the code to a larger database such as PostgreSQL or Oracle.\\n\\nThe sqlite3 module was written by Gerhard Häring. It provides an SQL interface compliant with the DB-API 2.0 specification described by PEP 249, and requires the third-party SQLite library.\\n\\nThis is an 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 Requirements for optional modules.\\n\\nThis document includes four main sections:\\n\\nTutorial teaches how to use the sqlite3 module.\\n\\nReference describes the classes and functions this module defines.\\n\\nHow-to guides details how to handle specific tasks.\\n\\nExplanation provides in-depth background on transaction control.\\n\\nSee also\\n\\nTutorial¶\\n\\nIn this tutorial, you will create a database of Monty Python movies using basic sqlite3 functionality. It assumes a fundamental understanding of database concepts, including cursors and transactions.\\n\\nFirst, we need to create a new database and open a database connection to allow sqlite3 to work with it. Call sqlite3.connect() to create a connection to the database tutorial.db in the current working directory, implicitly creating it if it does not exist:\\n\\nimport sqlite3\\ncon = sqlite3.connect(\"tutorial.db\")\\n\\nThe returned Connection object con represents the connection to the on-disk database.\\n\\nIn order to execute SQL statements and fetch results from SQL queries, we will need to use a database cursor. Call con.cursor() to create the Cursor:\\n\\ncur = con.cursor()\\n\\nNow that we’ve got a database connection and a cursor, we can create a database table movie with columns for title, release year, and review score. For simplicity, we can just use column names in the table declaration – thanks to the flexible typing feature of SQLite, specifying the data types is optional. Execute the CREATE TABLE statement by calling cur.execute(...):\\n\\ncur.execute(\"CREATE TABLE movie(title, year, score)\")\\n\\nWe can verify that the new table has been created by querying the sqlite_master table built-in to SQLite, which should now contain an entry for the movie table definition (see The Schema Table for details). Execute that query by calling cur.execute(...), assign the result to res, and call res.fetchone() to fetch the resulting row:\\n\\n>>> res = cur.execute(\"SELECT name FROM sqlite_master\")\\n>>> res.fetchone()\\n(\\'movie\\',)\\n\\nWe can see that the table has been created, as the query returns a tuple containing the table’s name. If we query sqlite_master for a non-existent table spam, res.fetchone() will return None:\\n\\n>>> res = cur.execute(\"SELECT name FROM sqlite_master WHERE name=\\'spam\\'\")\\n>>> res.fetchone() is None\\nTrue\\n\\nNow, add two rows of data supplied as SQL literals by executing an INSERT statement, once again by calling cur.execute(...):\\n\\ncur.execute(\"\"\"\\n INSERT INTO movie VALUES\\n (\\'Monty Python and the Holy Grail\\', 1975, 8.2),\\n (\\'And Now for Something Completely Different\\', 1971, 7.5)\\n\"\"\")\\n\\nThe INSERT statement implicitly opens a transaction, which needs to be committed before changes are saved in the database (see Transaction control for details). Call con.commit() on the connection object to commit the transaction:\\n\\ncon.commit()\\n\\nWe can verify that the data was inserted correctly by executing a SELECT query. Use the now-familiar cur.execute(...) to assign the result to res, and call res.fetchall() to return all resulting rows:\\n\\n>>> res = cur.execute(\"SELECT score FROM movie\")\\n>>> res.fetchall()\\n[(8.2,), (7.5,)]\\n\\nThe result is a list of two tuples, one per row, each containing that row’s score value.\\n\\nNow, insert three more rows by calling cur.executemany(...):\\n\\ndata = [\\n (\"Monty Python Live at the Hollywood Bowl\", 1982, 7.9),\\n (\"Monty Python\\'s The Meaning of Life\", 1983, 7.5),\\n (\"Monty Python\\'s Life of Brian\", 1979, 8.0),\\n]\\ncur.executemany(\"INSERT INTO movie VALUES(?, ?, ?)\", data)\\ncon.commit() # Remember to commit the transaction after executing INSERT.\\n\\nNotice that ? placeholders are used to bind data to the query. Always use placeholders instead of string formatting to bind Python values to SQL statements, to avoid SQL injection attacks (see How to use placeholders to bind values in SQL queries for more details).\\n\\nWe can verify that the new rows were inserted by executing a SELECT query, this time iterating over the results of the query:\\n\\n>>> for row in cur.execute(\"SELECT year, title FROM movie ORDER BY year\"):\\n... print(row)\\n(1971, \\'And Now for Something Completely Different\\')\\n(1975, \\'Monty Python and the Holy Grail\\')\\n(1979, \"Monty Python\\'s Life of Brian\")\\n(1982, \\'Monty Python Live at the Hollywood Bowl\\')\\n(1983, \"Monty Python\\'s The Meaning of Life\")\\n\\nEach row is a two-item tuple of (year, title), matching the columns selected in the query.\\n\\nFinally, verify that the database has been written to disk by calling con.close() to close the existing connection, opening a new one, creating a new cursor, then querying the database:\\n\\n>>> con.close()\\n>>> new_con = sqlite3.connect(\"tutorial.db\")\\n>>> new_cur = new_con.cursor()\\n>>> res = new_cur.execute(\"SELECT title, year FROM movie ORDER BY score DESC\")\\n>>> title, year = res.fetchone()\\n>>> print(f\\'The highest scoring Monty Python movie is {title!r}, released in {year}\\')\\nThe highest scoring Monty Python movie is \\'Monty Python and the Holy Grail\\', released in 1975\\n>>> new_con.close()\\n\\nYou’ve now created an SQLite database using the sqlite3 module, inserted data and retrieved values from it in multiple ways.\\n\\nSee also\\n\\nHow-to guides for further reading:\\n\\nHow to use placeholders to bind values in SQL queries\\n\\nHow to adapt custom Python types to SQLite values\\n\\nHow to convert SQLite values to custom Python types\\n\\nHow to use the connection context manager\\n\\nHow to create and use row factories\\n\\nExplanation for in-depth background on transaction control.\\n\\nReference¶\\n\\nModule functions¶\\n\\nModule constants¶\\n\\nDeprecated since version 3.12, removed in version 3.14: The version and version_info constants.\\n\\nConnection objects¶\\n\\nCursor objects¶\\n\\nA Cursor object represents a database cursor which is used to execute SQL statements, and manage the context of a fetch operation. Cursors are created using Connection.cursor(), or by using any of the connection shortcut methods.\\n\\nCursor objects are iterators, meaning that if you execute() a SELECT query, you can simply iterate over the cursor to fetch the resulting rows:\\n\\nfor row in cur.execute(\"SELECT t FROM data\"):\\n print(row)\\n\\nRow objects¶\\n\\nBlob objects¶\\n\\nPrepareProtocol objects¶\\n\\nExceptions¶\\n\\nThe exception hierarchy is defined by the DB-API 2.0 (PEP 249).\\n\\nSQLite and Python types¶\\n\\nSQLite natively supports the following types: NULL, INTEGER, REAL, TEXT, BLOB.\\n\\nThe following Python types can thus be sent to SQLite without any problem:\\n\\nPython type SQLite type None NULL int INTEGER float REAL str TEXT bytes BLOB\\n\\nThis is how SQLite types are converted to Python types by default:\\n\\nSQLite type Python type NULL None INTEGER int REAL float TEXT depends on text_factory , str by default BLOB bytes\\n\\nThe type system of the sqlite3 module is extensible in two ways: you can store additional Python types in an SQLite database via object adapters, and you can let the sqlite3 module convert SQLite types to Python types via converters.\\n\\nDefault adapters and converters (deprecated)¶\\n\\nNote\\n\\nThe default adapters and converters are deprecated as of Python 3.12. Instead, use the Adapter and converter recipes and tailor them to your needs.\\n\\nThe deprecated default adapters and converters consist of:\\n\\nAn adapter for datetime.date objects to strings in ISO 8601 format.\\n\\nAn adapter for datetime.datetime objects to strings in ISO 8601 format.\\n\\nA converter for declared “date” types to datetime.date objects.\\n\\nA converter for declared “timestamp” types to datetime.datetime objects. Fractional parts will be truncated to 6 digits (microsecond precision).\\n\\nNote\\n\\nThe default “timestamp” converter ignores UTC offsets in the database and always returns a naive datetime.datetime object. To preserve UTC offsets in timestamps, either leave converters disabled, or register an offset-aware converter with register_converter().\\n\\nDeprecated since version 3.12.\\n\\nCommand-line interface¶\\n\\nThe sqlite3 module can be invoked as a script, using the interpreter’s -m switch, in order to provide a simple SQLite shell. The argument signature is as follows:\\n\\npython -m sqlite3 [-h] [-v] [filename] [sql]\\n\\nType .quit or CTRL-D to exit the shell.\\n\\nAdded in version 3.12.\\n\\nHow-to guides¶\\n\\nHow to use placeholders to bind values in SQL queries¶\\n\\nSQL operations usually need to use values from Python variables. However, beware of using Python’s string operations to assemble queries, as they are vulnerable to SQL injection attacks. For example, an attacker can simply close the single quote and inject OR TRUE to select all rows:\\n\\n>>> # Never do this -- insecure!\\n>>> symbol = input()\\n\\' OR TRUE; --\\n>>> sql = \"SELECT * FROM stocks WHERE symbol = \\'%s\\'\" % symbol\\n>>> print(sql)\\nSELECT * FROM stocks WHERE symbol = \\'\\' OR TRUE; --\\'\\n>>> cur.execute(sql)\\n\\nInstead, use the DB-API’s parameter substitution. To insert a variable into a query string, use a placeholder in the string, and substitute the actual values into the query by providing them as a tuple of values to the second argument of the cursor’s execute() method.\\n\\nAn SQL statement may use one of two kinds of placeholders: question marks (qmark style) or named placeholders (named style). For the qmark style, parameters must be a sequence whose length must match the number of placeholders, or a ProgrammingError is raised. For the named style, parameters must be an instance of a dict (or a subclass), which must contain keys for all named parameters; any extra items are ignored. Here’s an example of both styles:\\n\\ncon = sqlite3.connect(\":memory:\")\\ncur = con.execute(\"CREATE TABLE lang(name, first_appeared)\")\\n\\n# This is the named style used with executemany():\\ndata = (\\n {\"name\": \"C\", \"year\": 1972},\\n {\"name\": \"Fortran\", \"year\": 1957},\\n {\"name\": \"Python\", \"year\": 1991},\\n {\"name\": \"Go\", \"year\": 2009},\\n)\\ncur.executemany(\"INSERT INTO lang VALUES(:name, :year)\", data)\\n\\n# This is the qmark style used in a SELECT query:\\nparams = (1972,)\\ncur.execute(\"SELECT * FROM lang WHERE first_appeared = ?\", params)\\nprint(cur.fetchall())\\ncon.close()\\n\\nNote\\n\\nPEP 249 numeric placeholders are not supported. If used, they will be interpreted as named placeholders.\\n\\nHow to adapt custom Python types to SQLite values¶\\n\\nSQLite supports only a limited set of data types natively. To store custom Python types in SQLite databases, adapt them to one of the Python types SQLite natively understands.\\n\\nThere are two ways to adapt Python objects to SQLite types: letting your object adapt itself, or using an adapter callable. The latter will take precedence above the former. For a library that exports a custom type, it may make sense to enable that type to adapt itself. As an application developer, it may make more sense to take direct control by registering custom adapter functions.\\n\\nHow to write adaptable objects¶\\n\\nSuppose we have a Point class that represents a pair of coordinates, x and y, in a Cartesian coordinate system. The coordinate pair will be stored as a text string in the database, using a semicolon to separate the coordinates. This can be implemented by adding a __conform__(self, protocol) method which returns the adapted value. The object passed to protocol will be of type PrepareProtocol.\\n\\nclass Point:\\n def __init__(self, x, y):\\n self.x, self.y = x, y\\n\\n def __conform__(self, protocol):\\n if protocol is sqlite3.PrepareProtocol:\\n return f\"{self.x};{self.y}\"\\n\\ncon = sqlite3.connect(\":memory:\")\\ncur = con.cursor()\\n\\ncur.execute(\"SELECT ?\", (Point(4.0, -3.2),))\\nprint(cur.fetchone()[0])\\ncon.close()\\n\\nHow to register adapter callables¶\\n\\nThe other possibility is to create a function that converts the Python object to an SQLite-compatible type. This function can then be registered using register_adapter().\\n\\nclass Point:\\n def __init__(self, x, y):\\n self.x, self.y = x, y\\n\\ndef adapt_point(point):\\n return f\"{point.x};{point.y}\"\\n\\nsqlite3.register_adapter(Point, adapt_point)\\n\\ncon = sqlite3.connect(\":memory:\")\\ncur = con.cursor()\\n\\ncur.execute(\"SELECT ?\", (Point(1.0, 2.5),))\\nprint(cur.fetchone()[0])\\ncon.close()\\n\\nHow to convert SQLite values to custom Python types¶\\n\\nWriting an adapter lets you convert from custom Python types to SQLite values. To be able to convert from SQLite values to custom Python types, we use converters.\\n\\nLet’s go back to the Point class. We stored the x and y coordinates separated via semicolons as strings in SQLite.\\n\\nFirst, we’ll define a converter function that accepts the string as a parameter and constructs a Point object from it.\\n\\nNote\\n\\nConverter functions are always passed a bytes object, no matter the underlying SQLite data type.\\n\\ndef convert_point(s):\\n x, y = map(float, s.split(b\";\"))\\n return Point(x, y)\\n\\nWe now need to tell sqlite3 when it should convert a given SQLite value. This is done when connecting to a database, using the detect_types parameter of connect(). There are three options:\\n\\nImplicit: set detect_types to PARSE_DECLTYPES\\n\\nExplicit: set detect_types to PARSE_COLNAMES\\n\\nBoth: set detect_types to sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES. Column names take precedence over declared types.\\n\\nThe following example illustrates the implicit and explicit approaches:\\n\\nclass Point:\\n def __init__(self, x, y):\\n self.x, self.y = x, y\\n\\n def __repr__(self):\\n return f\"Point({self.x}, {self.y})\"\\n\\ndef adapt_point(point):\\n return f\"{point.x};{point.y}\"\\n\\ndef convert_point(s):\\n x, y = list(map(float, s.split(b\";\")))\\n return Point(x, y)\\n\\n# Register the adapter and converter\\nsqlite3.register_adapter(Point, adapt_point)\\nsqlite3.register_converter(\"point\", convert_point)\\n\\n# 1) Parse using declared types\\np = Point(4.0, -3.2)\\ncon = sqlite3.connect(\":memory:\", detect_types=sqlite3.PARSE_DECLTYPES)\\ncur = con.execute(\"CREATE TABLE test(p point)\")\\n\\ncur.execute(\"INSERT INTO test(p) VALUES(?)\", (p,))\\ncur.execute(\"SELECT p FROM test\")\\nprint(\"with declared types:\", cur.fetchone()[0])\\ncur.close()\\ncon.close()\\n\\n# 2) Parse using column names\\ncon = sqlite3.connect(\":memory:\", detect_types=sqlite3.PARSE_COLNAMES)\\ncur = con.execute(\"CREATE TABLE test(p)\")\\n\\ncur.execute(\"INSERT INTO test(p) VALUES(?)\", (p,))\\ncur.execute(\\'SELECT p AS \"p [point]\" FROM test\\')\\nprint(\"with column names:\", cur.fetchone()[0])\\ncur.close()\\ncon.close()\\n\\nAdapter and converter recipes¶\\n\\nThis section shows recipes for common adapters and converters.\\n\\nimport datetime\\nimport sqlite3\\n\\ndef adapt_date_iso(val):\\n \"\"\"Adapt datetime.date to ISO 8601 date.\"\"\"\\n return val.isoformat()\\n\\ndef adapt_datetime_iso(val):\\n \"\"\"Adapt datetime.datetime to timezone-naive ISO 8601 date.\"\"\"\\n return val.replace(tzinfo=None).isoformat()\\n\\ndef adapt_datetime_epoch(val):\\n \"\"\"Adapt datetime.datetime to Unix timestamp.\"\"\"\\n return int(val.timestamp())\\n\\nsqlite3.register_adapter(datetime.date, adapt_date_iso)\\nsqlite3.register_adapter(datetime.datetime, adapt_datetime_iso)\\nsqlite3.register_adapter(datetime.datetime, adapt_datetime_epoch)\\n\\ndef convert_date(val):\\n \"\"\"Convert ISO 8601 date to datetime.date object.\"\"\"\\n return datetime.date.fromisoformat(val.decode())\\n\\ndef convert_datetime(val):\\n \"\"\"Convert ISO 8601 datetime to datetime.datetime object.\"\"\"\\n return datetime.datetime.fromisoformat(val.decode())\\n\\ndef convert_timestamp(val):\\n \"\"\"Convert Unix epoch timestamp to datetime.datetime object.\"\"\"\\n return datetime.datetime.fromtimestamp(int(val))\\n\\nsqlite3.register_converter(\"date\", convert_date)\\nsqlite3.register_converter(\"datetime\", convert_datetime)\\nsqlite3.register_converter(\"timestamp\", convert_timestamp)\\n\\nHow to use connection shortcut methods¶\\n\\nUsing the execute(), executemany(), and executescript() methods of the Connection class, your code can be written more concisely because you don’t have to create the (often superfluous) Cursor objects explicitly. Instead, the Cursor objects are created implicitly and these shortcut methods return the cursor objects. This way, you can execute a SELECT statement and iterate over it directly using only a single call on the Connection object.\\n\\n# Create and fill the table.\\ncon = sqlite3.connect(\":memory:\")\\ncon.execute(\"CREATE TABLE lang(name, first_appeared)\")\\ndata = [\\n (\"C++\", 1985),\\n (\"Objective-C\", 1984),\\n]\\ncon.executemany(\"INSERT INTO lang(name, first_appeared) VALUES(?, ?)\", data)\\n\\n# Print the table contents\\nfor row in con.execute(\"SELECT name, first_appeared FROM lang\"):\\n print(row)\\n\\nprint(\"I just deleted\", con.execute(\"DELETE FROM lang\").rowcount, \"rows\")\\n\\n# close() is not a shortcut method and it\\'s not called automatically;\\n# the connection object should be closed manually\\ncon.close()\\n\\nHow to use the connection context manager¶\\n\\nA Connection object can be used as a context manager that automatically commits or rolls back open transactions when leaving the body of the context manager. If the body of the with statement finishes without exceptions, the transaction is committed. If this commit fails, or if the body of the with statement raises an uncaught exception, the transaction is rolled back. If autocommit is False, a new transaction is implicitly opened after committing or rolling back.\\n\\nIf there is no open transaction upon leaving the body of the with statement, or if autocommit is True, the context manager does nothing.\\n\\nNote\\n\\nThe context manager neither implicitly opens a new transaction nor closes the connection. If you need a closing context manager, consider using contextlib.closing().\\n\\ncon = sqlite3.connect(\":memory:\")\\ncon.execute(\"CREATE TABLE lang(id INTEGER PRIMARY KEY, name VARCHAR UNIQUE)\")\\n\\n# Successful, con.commit() is called automatically afterwards\\nwith con:\\n con.execute(\"INSERT INTO lang(name) VALUES(?)\", (\"Python\",))\\n\\n# con.rollback() is called after the with block finishes with an exception,\\n# the exception is still raised and must be caught\\ntry:\\n with con:\\n con.execute(\"INSERT INTO lang(name) VALUES(?)\", (\"Python\",))\\nexcept sqlite3.IntegrityError:\\n print(\"couldn\\'t add Python twice\")\\n\\n# Connection object used as context manager only commits or rollbacks transactions,\\n# so the connection object should be closed manually\\ncon.close()\\n\\nHow to work with SQLite URIs¶\\n\\nSome useful URI tricks include:\\n\\nOpen a database in read-only mode:\\n\\n>>> con = sqlite3.connect(\"file:tutorial.db?mode=ro\", uri=True)\\n>>> con.execute(\"CREATE TABLE readonly(data)\")\\nTraceback (most recent call last):\\nOperationalError: attempt to write a readonly database\\n>>> con.close()\\n\\nDo not implicitly create a new database file if it does not already exist; will raise OperationalError if unable to create a new file:\\n\\n>>> con = sqlite3.connect(\"file:nosuchdb.db?mode=rw\", uri=True)\\nTraceback (most recent call last):\\nOperationalError: unable to open database file\\n\\nCreate a shared named in-memory database:\\n\\ndb = \"file:mem1?mode=memory&cache=shared\"\\ncon1 = sqlite3.connect(db, uri=True)\\ncon2 = sqlite3.connect(db, uri=True)\\nwith con1:\\n con1.execute(\"CREATE TABLE shared(data)\")\\n con1.execute(\"INSERT INTO shared VALUES(28)\")\\nres = con2.execute(\"SELECT data FROM shared\")\\nassert res.fetchone() == (28,)\\n\\ncon1.close()\\ncon2.close()\\n\\nMore information about this feature, including a list of parameters, can be found in the SQLite URI documentation.\\n\\nHow to create and use row factories¶\\n\\nBy default, sqlite3 represents each row as a tuple. If a tuple does not suit your needs, you can use the sqlite3.Row class or a custom row_factory.\\n\\nWhile row_factory exists as an attribute both on the Cursor and the Connection, it is recommended to set Connection.row_factory, so all cursors created from the connection will use the same row factory.\\n\\nRow provides indexed and case-insensitive named access to columns, with minimal memory overhead and performance impact over a tuple. To use Row as a row factory, assign it to the row_factory attribute:\\n\\n>>> con = sqlite3.connect(\":memory:\")\\n>>> con.row_factory = sqlite3.Row\\n\\nQueries now return Row objects:\\n\\n>>> res = con.execute(\"SELECT \\'Earth\\' AS name, 6378 AS radius\")\\n>>> row = res.fetchone()\\n>>> row.keys()\\n[\\'name\\', \\'radius\\']\\n>>> row[0] # Access by index.\\n\\'Earth\\'\\n>>> row[\"name\"] # Access by name.\\n\\'Earth\\'\\n>>> row[\"RADIUS\"] # Column names are case-insensitive.\\n6378\\n>>> con.close()\\n\\nNote\\n\\nThe FROM clause can be omitted in the 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 expr AS alias.\\n\\nYou can create a custom row_factory that returns each row as a dict, with column names mapped to values:\\n\\ndef dict_factory(cursor, row):\\n fields = [column[0] for column in cursor.description]\\n return {key: value for key, value in zip(fields, row)}\\n\\nUsing it, queries now return a dict instead of a tuple:\\n\\n>>> con = sqlite3.connect(\":memory:\")\\n>>> con.row_factory = dict_factory\\n>>> for row in con.execute(\"SELECT 1 AS a, 2 AS b\"):\\n... print(row)\\n{\\'a\\': 1, \\'b\\': 2}\\n>>> con.close()\\n\\nThe following row factory returns a named tuple:\\n\\nfrom collections import namedtuple\\n\\ndef namedtuple_factory(cursor, row):\\n fields = [column[0] for column in cursor.description]\\n cls = namedtuple(\"Row\", fields)\\n return cls._make(row)\\n\\nnamedtuple_factory() can be used as follows:\\n\\n>>> con = sqlite3.connect(\":memory:\")\\n>>> con.row_factory = namedtuple_factory\\n>>> cur = con.execute(\"SELECT 1 AS a, 2 AS b\")\\n>>> row = cur.fetchone()\\n>>> row\\nRow(a=1, b=2)\\n>>> row[0] # Indexed access.\\n1\\n>>> row.b # Attribute access.\\n2\\n>>> con.close()\\n\\nWith some adjustments, the above recipe can be adapted to use a dataclass, or any other custom class, instead of a namedtuple.\\n\\nHow to handle non-UTF-8 text encodings¶\\n\\nBy default, sqlite3 uses str to adapt SQLite values with the 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 text_factory to handle such cases.\\n\\nBecause of SQLite’s flexible typing, it is not uncommon to encounter table columns with the 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 Connection instance con connected to this database, we can decode the Latin-2 encoded text using this text_factory:\\n\\ncon.text_factory = lambda data: str(data, encoding=\"latin2\")\\n\\nFor invalid UTF-8 or arbitrary data in stored in TEXT table columns, you can use the following technique, borrowed from the Unicode HOWTO:\\n\\ncon.text_factory = lambda data: str(data, errors=\"surrogateescape\")\\n\\nNote\\n\\nThe sqlite3 module API does not support strings containing surrogates.\\n\\nSee also\\n\\nUnicode HOWTO\\n\\nExplanation¶\\n\\nTransaction control¶\\n\\nsqlite3 offers multiple methods of controlling whether, when and how database transactions are opened and closed. Transaction control via the autocommit attribute is recommended, while Transaction control via the isolation_level attribute retains the pre-Python 3.12 behaviour.\\n\\nTransaction control via the autocommit attribute¶\\n\\nThe recommended way of controlling transaction behaviour is through the Connection.autocommit attribute, which should preferably be set using the autocommit parameter of connect().\\n\\nIt is suggested to set autocommit to False, which implies PEP 249-compliant transaction control. This means:\\n\\nsqlite3 ensures that a transaction is always open, so connect(), Connection.commit(), and Connection.rollback() will implicitly open a new transaction (immediately after closing the pending one, for the latter two). sqlite3 uses BEGIN DEFERRED statements when opening transactions.\\n\\nTransactions should be committed explicitly using commit().\\n\\nTransactions should be rolled back explicitly using rollback().\\n\\nAn implicit rollback is performed if the database is close()-ed with pending changes.\\n\\nSet autocommit to True to enable SQLite’s autocommit mode. In this mode, Connection.commit() and Connection.rollback() have no effect. Note that SQLite’s autocommit mode is distinct from the PEP 249-compliant Connection.autocommit attribute; use Connection.in_transaction to query the low-level SQLite autocommit mode.\\n\\nSet autocommit to LEGACY_TRANSACTION_CONTROL to leave transaction control behaviour to the Connection.isolation_level attribute. See Transaction control via the isolation_level attribute for more information.\\n\\nTransaction control via the isolation_level attribute¶\\n\\nNote\\n\\nThe recommended way of controlling transactions is via the autocommit attribute. See Transaction control via the autocommit attribute.\\n\\nIf Connection.autocommit is set to LEGACY_TRANSACTION_CONTROL (the default), transaction behaviour is controlled using the Connection.isolation_level attribute. Otherwise, isolation_level has no effect.\\n\\nIf the connection attribute isolation_level is not None, new transactions are implicitly opened before execute() and executemany() executes INSERT, UPDATE, DELETE, or REPLACE statements; for other statements, no implicit transaction handling is performed. Use the commit() and rollback() methods to respectively commit and roll back pending transactions. You can choose the underlying SQLite transaction behaviour — that is, whether and what type of BEGIN statements sqlite3 implicitly executes – via the isolation_level attribute.\\n\\nIf isolation_level is set to None, no transactions are implicitly opened at all. This leaves the underlying SQLite library in autocommit mode, but also allows the user to perform their own transaction handling using explicit SQL statements. The underlying SQLite library autocommit mode can be queried using the in_transaction attribute.\\n\\nThe executescript() method implicitly commits any pending transaction before execution of the given SQL script, regardless of the value of isolation_level.\\n\\nChanged in version 3.6: sqlite3 used to implicitly commit an open transaction before DDL statements. This is no longer the case.\\n\\nChanged in version 3.12: The recommended way of controlling transactions is now via the autocommit attribute.\\n\\nTable of Contents\\n\\nsqlite3 — DB-API 2.0 interface for SQLite databases\\n\\nTutorial\\n\\nReference\\n\\nModule functions\\n\\nModule constants\\n\\nConnection objects\\n\\nCursor objects\\n\\nRow objects\\n\\nBlob objects\\n\\nPrepareProtocol objects\\n\\nExceptions\\n\\nSQLite and Python types\\n\\nDefault adapters and converters (deprecated)\\n\\nCommand-line interface\\n\\nHow-to guides\\n\\nHow to use placeholders to bind values in SQL queries\\n\\nHow to adapt custom Python types to SQLite values\\n\\nHow to write adaptable objects\\n\\nHow to register adapter callables\\n\\nHow to convert SQLite values to custom Python types\\n\\nAdapter and converter recipes\\n\\nHow to use connection shortcut methods\\n\\nHow to use the connection context manager\\n\\nHow to work with SQLite URIs\\n\\nHow to create and use row factories\\n\\nHow to handle non-UTF-8 text encodings\\n\\nExplanation\\n\\nTransaction control\\n\\nTransaction control via the autocommit attribute\\n\\nTransaction control via the isolation_level attribute\\n\\nPrevious topic\\n\\ndbm — Interfaces to Unix “databases”\\n\\nNext topic\\n\\nData Compression and Archiving\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Persistence »\\n\\nsqlite3 — DB-API 2.0 interface for SQLite databases\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\ssl.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nssl — TLS/SSL wrapper for socket objects\\n\\n|\\n\\nssl — TLS/SSL wrapper for socket objects¶\\n\\nSource code: Lib/ssl.py\\n\\nThis 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.\\n\\nThis is an 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 Requirements for optional modules.\\n\\nNote\\n\\nSome 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.\\n\\nWarning\\n\\nDon’t use this module without reading the Security considerations. Doing so may lead to a false sense of security, as the default settings of the ssl module are not necessarily appropriate for your application.\\n\\nAvailability: not WASI.\\n\\nThis module does not work or is not available on WebAssembly. See WebAssembly platforms for more information.\\n\\nThis section documents the objects and functions in the ssl module; for more general information about TLS, SSL, and certificates, the reader is referred to the documents in the “See Also” section at the bottom.\\n\\nThis module provides a class, ssl.SSLSocket, which is derived from the 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 getpeercert(), which retrieves the certificate of the other side of the connection, cipher(), which retrieves the cipher being used for the secure connection or get_verified_chain(), get_unverified_chain() which retrieves certificate chain.\\n\\nFor more sophisticated applications, the ssl.SSLContext class helps manage settings and certificates, which can then be inherited by SSL sockets created through the SSLContext.wrap_socket() method.\\n\\nChanged in version 3.5.3: Updated to support linking with OpenSSL 1.1.0\\n\\nChanged in version 3.6: OpenSSL 0.9.8, 1.0.0 and 1.0.1 are deprecated and no longer supported. In the future the ssl module will require at least OpenSSL 1.0.2 or 1.1.0.\\n\\nChanged in version 3.10: PEP 644 has been implemented. The ssl module requires OpenSSL 1.1.1 or newer.\\n\\nUse of deprecated constants and functions result in deprecation warnings.\\n\\nFunctions, Constants, and Exceptions¶\\n\\nSocket creation¶\\n\\nInstances of SSLSocket must be created using the SSLContext.wrap_socket() method. The helper function create_default_context() returns a new context with secure default settings.\\n\\nClient socket example with default context and IPv4/IPv6 dual stack:\\n\\nimport socket\\nimport ssl\\n\\nhostname = \\'www.python.org\\'\\ncontext = ssl.create_default_context()\\n\\nwith socket.create_connection((hostname, 443)) as sock:\\n with context.wrap_socket(sock, server_hostname=hostname) as ssock:\\n print(ssock.version())\\n\\nClient socket example with custom context and IPv4:\\n\\nhostname = \\'www.python.org\\'\\n# PROTOCOL_TLS_CLIENT requires valid cert chain and hostname\\ncontext = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)\\ncontext.load_verify_locations(\\'path/to/cabundle.pem\\')\\n\\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:\\n with context.wrap_socket(sock, server_hostname=hostname) as ssock:\\n print(ssock.version())\\n\\nServer socket example listening on localhost IPv4:\\n\\ncontext = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)\\ncontext.load_cert_chain(\\'/path/to/certchain.pem\\', \\'/path/to/private.key\\')\\n\\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:\\n sock.bind((\\'127.0.0.1\\', 8443))\\n sock.listen(5)\\n with context.wrap_socket(sock, server_side=True) as ssock:\\n conn, addr = ssock.accept()\\n ...\\n\\nContext creation¶\\n\\nA convenience function helps create SSLContext objects for common purposes.\\n\\nSignature algorithms¶\\n\\nExceptions¶\\n\\nRandom generation¶\\n\\nCertificate handling¶\\n\\nConstants¶\\n\\nAll constants are now enum.IntEnum or enum.IntFlag collections.\\n\\nAdded in version 3.6.\\n\\nSSL Sockets¶\\n\\nSSL sockets also have the following additional methods and attributes:\\n\\nNote\\n\\nThe read() and write() methods are the low-level methods that read and write unencrypted, application-level data and decrypt/encrypt it to encrypted, wire-level data. These methods require an active SSL connection, i.e. the handshake was completed and SSLSocket.unwrap() was not called.\\n\\nNormally you should use the socket API methods like recv() and send() instead of these methods.\\n\\nSSL Contexts¶\\n\\nAdded in version 3.2.\\n\\nAn SSL context holds various data longer-lived than single SSL connections, such as SSL configuration options, certificate(s) and private key(s). It also manages a cache of SSL sessions for server-side sockets, in order to speed up repeated connections from the same clients.\\n\\nSSLContext objects have the following methods and attributes:\\n\\nCertificates¶\\n\\nCertificates in general are part of a public-key / private-key system. In this system, each principal, (which may be a machine, or a person, or an organization) is assigned a unique two-part encryption key. One part of the key is public, and is called the public key; the other part is kept secret, and is called the private key. The two parts are related, in that if you encrypt a message with one of the parts, you can decrypt it with the other part, and only with the other part.\\n\\nA certificate contains information about two principals. It contains the name of a subject, and the subject’s public key. It also contains a statement by a second principal, the issuer, that the subject is who they claim to be, and that this is indeed the subject’s public key. The issuer’s statement is signed with the issuer’s private key, which only the issuer knows. However, anyone can verify the issuer’s statement by finding the issuer’s public key, decrypting the statement with it, and comparing it to the other information in the certificate. The certificate also contains information about the time period over which it is valid. This is expressed as two fields, called “notBefore” and “notAfter”.\\n\\nIn the Python use of certificates, a client or server can use a certificate to prove who they are. The other side of a network connection can also be required to produce a certificate, and that certificate can be validated to the satisfaction of the client or server that requires such validation. The connection attempt can be set to raise an exception if the validation fails. Validation is done automatically, by the underlying OpenSSL framework; the application need not concern itself with its mechanics. But the application does usually need to provide sets of certificates to allow this process to take place.\\n\\nPython uses files to contain certificates. They should be formatted as “PEM” (see RFC 1422), which is a base-64 encoded form wrapped with a header line and a footer line:\\n\\n-----BEGIN CERTIFICATE-----\\n... (certificate in base64 PEM encoding) ...\\n-----END CERTIFICATE-----\\n\\nCertificate chains¶\\n\\nThe Python files which contain certificates can contain a sequence of certificates, sometimes called a certificate chain. This chain should start with the specific certificate for the principal who “is” the client or server, and then the certificate for the issuer of that certificate, and then the certificate for the issuer of that certificate, and so on up the chain till you get to a certificate which is self-signed, that is, a certificate which has the same subject and issuer, sometimes called a root certificate. The certificates should just be concatenated together in the certificate file. For example, suppose we had a three certificate chain, from our server certificate to the certificate of the certification authority that signed our server certificate, to the root certificate of the agency which issued the certification authority’s certificate:\\n\\n-----BEGIN CERTIFICATE-----\\n... (certificate for your server)...\\n-----END CERTIFICATE-----\\n-----BEGIN CERTIFICATE-----\\n... (the certificate for the CA)...\\n-----END CERTIFICATE-----\\n-----BEGIN CERTIFICATE-----\\n... (the root certificate for the CA\\'s issuer)...\\n-----END CERTIFICATE-----\\n\\nCA certificates¶\\n\\nIf you are going to require validation of the other side of the connection’s certificate, you need to provide a “CA certs” file, filled with the certificate chains for each issuer you are willing to trust. Again, this file just contains these chains concatenated together. For validation, Python will use the first chain it finds in the file which matches. The platform’s certificates file can be used by calling SSLContext.load_default_certs(), this is done automatically with create_default_context().\\n\\nCombined key and certificate¶\\n\\nOften the private key is stored in the same file as the certificate; in this case, only the certfile parameter to 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:\\n\\n-----BEGIN RSA PRIVATE KEY-----\\n... (private key in base64 encoding) ...\\n-----END RSA PRIVATE KEY-----\\n-----BEGIN CERTIFICATE-----\\n... (certificate in base64 PEM encoding) ...\\n-----END CERTIFICATE-----\\n\\nSelf-signed certificates¶\\n\\nIf you are going to create a server that provides SSL-encrypted connection services, you will need to acquire a certificate for that service. There are many ways of acquiring appropriate certificates, such as buying one from a certification authority. Another common practice is to generate a self-signed certificate. The simplest way to do this is with the OpenSSL package, using something like the following:\\n\\n% openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem\\nGenerating a 1024 bit RSA private key\\n.......++++++\\n.............................++++++\\nwriting new private key to \\'cert.pem\\'\\n-----\\nYou are about to be asked to enter information that will be incorporated\\ninto your certificate request.\\nWhat you are about to enter is what is called a Distinguished Name or a DN.\\nThere are quite a few fields but you can leave some blank\\nFor some fields there will be a default value,\\nIf you enter \\'.\\', the field will be left blank.\\n-----\\nCountry Name (2 letter code) [AU]:US\\nState or Province Name (full name) [Some-State]:MyState\\nLocality Name (eg, city) []:Some City\\nOrganization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc.\\nOrganizational Unit Name (eg, section) []:My Group\\nCommon Name (eg, YOUR name) []:myserver.mygroup.myorganization.com\\nEmail Address []:ops@myserver.mygroup.myorganization.com\\n%\\n\\nThe disadvantage of a self-signed certificate is that it is its own root certificate, and no one else will have it in their cache of known (and trusted) root certificates.\\n\\nExamples¶\\n\\nTesting for SSL support¶\\n\\nTo test for the presence of SSL support in a Python installation, user code should use the following idiom:\\n\\ntry:\\n import ssl\\nexcept ImportError:\\n pass\\nelse:\\n ... # do something that requires SSL support\\n\\nClient-side operation¶\\n\\nThis example creates a SSL context with the recommended security settings for client sockets, including automatic certificate verification:\\n\\n>>> context = ssl.create_default_context()\\n\\nIf you prefer to tune security settings yourself, you might create a context from scratch (but beware that you might not get the settings right):\\n\\n>>> context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)\\n>>> context.load_verify_locations(\"/etc/ssl/certs/ca-bundle.crt\")\\n\\n(this snippet assumes your operating system places a bundle of all CA certificates in /etc/ssl/certs/ca-bundle.crt; if not, you’ll get an error and have to adjust the location)\\n\\nThe PROTOCOL_TLS_CLIENT protocol configures the context for cert validation and hostname verification. verify_mode is set to CERT_REQUIRED and check_hostname is set to True. All other protocols create SSL contexts with insecure defaults.\\n\\nWhen you use the context to connect to a server, CERT_REQUIRED and 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:\\n\\n>>> conn = context.wrap_socket(socket.socket(socket.AF_INET),\\n... server_hostname=\"www.python.org\")\\n>>> conn.connect((\"www.python.org\", 443))\\n\\nYou may then fetch the certificate:\\n\\n>>> cert = conn.getpeercert()\\n\\nVisual inspection shows that the certificate does identify the desired service (that is, the HTTPS host www.python.org):\\n\\n>>> pprint.pprint(cert)\\n{\\'OCSP\\': (\\'http://ocsp.digicert.com\\',),\\n \\'caIssuers\\': (\\'http://cacerts.digicert.com/DigiCertSHA2ExtendedValidationServerCA.crt\\',),\\n \\'crlDistributionPoints\\': (\\'http://crl3.digicert.com/sha2-ev-server-g1.crl\\',\\n \\'http://crl4.digicert.com/sha2-ev-server-g1.crl\\'),\\n \\'issuer\\': (((\\'countryName\\', \\'US\\'),),\\n ((\\'organizationName\\', \\'DigiCert Inc\\'),),\\n ((\\'organizationalUnitName\\', \\'www.digicert.com\\'),),\\n ((\\'commonName\\', \\'DigiCert SHA2 Extended Validation Server CA\\'),)),\\n \\'notAfter\\': \\'Sep 9 12:00:00 2016 GMT\\',\\n \\'notBefore\\': \\'Sep 5 00:00:00 2014 GMT\\',\\n \\'serialNumber\\': \\'01BB6F00122B177F36CAB49CEA8B6B26\\',\\n \\'subject\\': (((\\'businessCategory\\', \\'Private Organization\\'),),\\n ((\\'1.3.6.1.4.1.311.60.2.1.3\\', \\'US\\'),),\\n ((\\'1.3.6.1.4.1.311.60.2.1.2\\', \\'Delaware\\'),),\\n ((\\'serialNumber\\', \\'3359300\\'),),\\n ((\\'streetAddress\\', \\'16 Allen Rd\\'),),\\n ((\\'postalCode\\', \\'03894-4801\\'),),\\n ((\\'countryName\\', \\'US\\'),),\\n ((\\'stateOrProvinceName\\', \\'NH\\'),),\\n ((\\'localityName\\', \\'Wolfeboro\\'),),\\n ((\\'organizationName\\', \\'Python Software Foundation\\'),),\\n ((\\'commonName\\', \\'www.python.org\\'),)),\\n \\'subjectAltName\\': ((\\'DNS\\', \\'www.python.org\\'),\\n (\\'DNS\\', \\'python.org\\'),\\n (\\'DNS\\', \\'pypi.org\\'),\\n (\\'DNS\\', \\'docs.python.org\\'),\\n (\\'DNS\\', \\'testpypi.org\\'),\\n (\\'DNS\\', \\'bugs.python.org\\'),\\n (\\'DNS\\', \\'wiki.python.org\\'),\\n (\\'DNS\\', \\'hg.python.org\\'),\\n (\\'DNS\\', \\'mail.python.org\\'),\\n (\\'DNS\\', \\'packaging.python.org\\'),\\n (\\'DNS\\', \\'pythonhosted.org\\'),\\n (\\'DNS\\', \\'www.pythonhosted.org\\'),\\n (\\'DNS\\', \\'test.pythonhosted.org\\'),\\n (\\'DNS\\', \\'us.pycon.org\\'),\\n (\\'DNS\\', \\'id.python.org\\')),\\n \\'version\\': 3}\\n\\nNow the SSL channel is established and the certificate verified, you can proceed to talk with the server:\\n\\n>>> conn.sendall(b\"HEAD / HTTP/1.0\\\\r\\\\nHost: linuxfr.org\\\\r\\\\n\\\\r\\\\n\")\\n>>> pprint.pprint(conn.recv(1024).split(b\"\\\\r\\\\n\"))\\n[b\\'HTTP/1.1 200 OK\\',\\n b\\'Date: Sat, 18 Oct 2014 18:27:20 GMT\\',\\n b\\'Server: nginx\\',\\n b\\'Content-Type: text/html; charset=utf-8\\',\\n b\\'X-Frame-Options: SAMEORIGIN\\',\\n b\\'Content-Length: 45679\\',\\n b\\'Accept-Ranges: bytes\\',\\n b\\'Via: 1.1 varnish\\',\\n b\\'Age: 2188\\',\\n b\\'X-Served-By: cache-lcy1134-LCY\\',\\n b\\'X-Cache: HIT\\',\\n b\\'X-Cache-Hits: 11\\',\\n b\\'Vary: Cookie\\',\\n b\\'Strict-Transport-Security: max-age=63072000; includeSubDomains\\',\\n b\\'Connection: close\\',\\n b\\'\\',\\n b\\'\\']\\n\\nSee the discussion of Security considerations below.\\n\\nServer-side operation¶\\n\\nFor server operation, typically you’ll need to have a server certificate, and private key, each in a file. You’ll first create a context holding the key and the certificate, so that clients can check your authenticity. Then you’ll open a socket, bind it to a port, call listen() on it, and start waiting for clients to connect:\\n\\nimport socket, ssl\\n\\ncontext = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\\ncontext.load_cert_chain(certfile=\"mycertfile\", keyfile=\"mykeyfile\")\\n\\nbindsocket = socket.socket()\\nbindsocket.bind((\\'myaddr.example.com\\', 10023))\\nbindsocket.listen(5)\\n\\nWhen a client connects, you’ll call accept() on the socket to get the new socket from the other end, and use the context’s SSLContext.wrap_socket() method to create a server-side SSL socket for the connection:\\n\\nwhile True:\\n newsocket, fromaddr = bindsocket.accept()\\n connstream = context.wrap_socket(newsocket, server_side=True)\\n try:\\n deal_with_client(connstream)\\n finally:\\n connstream.shutdown(socket.SHUT_RDWR)\\n connstream.close()\\n\\nThen you’ll read data from the connstream and do something with it till you are finished with the client (or the client is finished with you):\\n\\ndef deal_with_client(connstream):\\n data = connstream.recv(1024)\\n # empty data means the client is finished with us\\n while data:\\n if not do_something(connstream, data):\\n # we\\'ll assume do_something returns False\\n # when we\\'re finished with client\\n break\\n data = connstream.recv(1024)\\n # finished with client\\n\\nAnd go back to listening for new client connections (of course, a real server would probably handle each client connection in a separate thread, or put the sockets in non-blocking mode and use an event loop).\\n\\nNotes on non-blocking sockets¶\\n\\nSSL sockets behave slightly different than regular sockets in non-blocking mode. When working with non-blocking sockets, there are thus several things you need to be aware of:\\n\\nMost SSLSocket methods will raise either SSLWantWriteError or SSLWantReadError instead of BlockingIOError if an I/O operation would block. SSLWantReadError will be raised if a read operation on the underlying socket is necessary, and SSLWantWriteError for a write operation on the underlying socket. Note that attempts to write to an SSL socket may require reading from the underlying socket first, and attempts to read from the SSL socket may require a prior write to the underlying socket.\\n\\nChanged in version 3.5: In earlier Python versions, the SSLSocket.send() method returned zero instead of raising SSLWantWriteError or SSLWantReadError.\\n\\nCalling select() tells you that the OS-level socket can be read from (or written to), but it does not imply that there is sufficient data at the upper SSL layer. For example, only part of an SSL frame might have arrived. Therefore, you must be ready to handle SSLSocket.recv() and SSLSocket.send() failures, and retry after another call to select().\\n\\nConversely, since the SSL layer has its own framing, a SSL socket may still have data available for reading without select() being aware of it. Therefore, you should first call SSLSocket.recv() to drain any potentially available data, and then only block on a select() call if still necessary.\\n\\n(of course, similar provisions apply when using other primitives such as poll(), or those in the selectors module)\\n\\nThe SSL handshake itself will be non-blocking: the SSLSocket.do_handshake() method has to be retried until it returns successfully. Here is a synopsis using select() to wait for the socket’s readiness:\\n\\nwhile True:\\n try:\\n sock.do_handshake()\\n break\\n except ssl.SSLWantReadError:\\n select.select([sock], [], [])\\n except ssl.SSLWantWriteError:\\n select.select([], [sock], [])\\n\\nSee also\\n\\nThe asyncio module supports non-blocking SSL sockets and provides a higher level Streams API. It polls for events using the selectors module and handles SSLWantWriteError, SSLWantReadError and BlockingIOError exceptions. It runs the SSL handshake asynchronously as well.\\n\\nMemory BIO Support¶\\n\\nAdded in version 3.5.\\n\\nEver since the SSL module was introduced in Python 2.6, the SSLSocket class has provided two related but distinct areas of functionality:\\n\\nSSL protocol handling\\n\\nNetwork IO\\n\\nThe network IO API is identical to that provided by socket.socket, from which SSLSocket also inherits. This allows an SSL socket to be used as a drop-in replacement for a regular socket, making it very easy to add SSL support to an existing application.\\n\\nCombining SSL protocol handling and network IO usually works well, but there are some cases where it doesn’t. An example is async IO frameworks that want to use a different IO multiplexing model than the “select/poll on a file descriptor” (readiness based) model that is assumed by socket.socket and by the internal OpenSSL socket IO routines. This is mostly relevant for platforms like Windows where this model is not efficient. For this purpose, a reduced scope variant of SSLSocket called SSLObject is provided.\\n\\nAn SSLObject communicates with the outside world using memory buffers. The class MemoryBIO provides a memory buffer that can be used for this purpose. It wraps an OpenSSL memory BIO (Basic IO) object:\\n\\nSSL session¶\\n\\nAdded in version 3.6.\\n\\nSecurity considerations¶\\n\\nBest defaults¶\\n\\nFor client use, if you don’t have any special requirements for your security policy, it is highly recommended that you use the create_default_context() function to create your SSL context. It will load the system’s trusted CA certificates, enable certificate validation and hostname checking, and try to choose reasonably secure protocol and cipher settings.\\n\\nFor example, here is how you would use the smtplib.SMTP class to create a trusted, secure connection to a SMTP server:\\n\\n>>> import ssl, smtplib\\n>>> smtp = smtplib.SMTP(\"mail.python.org\", port=587)\\n>>> context = ssl.create_default_context()\\n>>> smtp.starttls(context=context)\\n(220, b\\'2.0.0 Ready to start TLS\\')\\n\\nIf a client certificate is needed for the connection, it can be added with SSLContext.load_cert_chain().\\n\\nBy contrast, if you create the SSL context by calling the SSLContext constructor yourself, it will not have certificate validation nor hostname checking enabled by default. If you do so, please read the paragraphs below to achieve a good security level.\\n\\nManual settings¶\\n\\nVerifying certificates¶\\n\\nWhen calling the SSLContext constructor directly, 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 CERT_REQUIRED. However, it is in itself not sufficient; you also have to check that the server certificate, which can be obtained by calling 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 SSLContext.check_hostname is enabled.\\n\\nChanged in version 3.7: Hostname matchings is now performed by OpenSSL. Python no longer uses match_hostname().\\n\\nIn server mode, if you want to authenticate your clients using the SSL layer (rather than using a higher-level authentication mechanism), you’ll also have to specify CERT_REQUIRED and similarly check the client certificate.\\n\\nProtocol versions¶\\n\\nSSL versions 2 and 3 are considered insecure and are therefore dangerous to use. If you want maximum compatibility between clients and servers, it is recommended to use PROTOCOL_TLS_CLIENT or PROTOCOL_TLS_SERVER as the protocol version. SSLv2 and SSLv3 are disabled by default.\\n\\n>>> client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)\\n>>> client_context.minimum_version = ssl.TLSVersion.TLSv1_3\\n>>> client_context.maximum_version = ssl.TLSVersion.TLSv1_3\\n\\nThe SSL context created above will only allow TLSv1.3 and later (if supported by your system) connections to a server. PROTOCOL_TLS_CLIENT implies certificate validation and hostname checks by default. You have to load certificates into the context.\\n\\nCipher selection¶\\n\\nIf you have advanced security requirements, fine-tuning of the ciphers enabled when negotiating a SSL session is possible through the 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. If you want to check which ciphers are enabled by a given cipher list, use SSLContext.get_ciphers() or the openssl ciphers command on your system.\\n\\nMulti-processing¶\\n\\nIf using this module as part of a multi-processed application (using, for example the multiprocessing or 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 os.fork(). Any successful call of RAND_add() or RAND_bytes() is sufficient.\\n\\nTLS 1.3¶\\n\\nAdded in version 3.7.\\n\\nThe TLS 1.3 protocol behaves slightly differently than previous version of TLS/SSL. Some new TLS 1.3 features are not yet available.\\n\\nTLS 1.3 uses a disjunct set of cipher suites. All AES-GCM and ChaCha20 cipher suites are enabled by default. To restrict which TLS 1.3 ciphers are allowed, the SSLContext.set_ciphersuites() method should be called instead of SSLContext.set_ciphers(), which only affects ciphers in older TLS versions. The SSLContext.get_ciphers() method returns information about ciphers for both TLS 1.3 and earlier versions and the method SSLSocket.cipher() returns information about the negotiated cipher for both TLS 1.3 and earlier versions once a connection is established.\\n\\nSession tickets are no longer sent as part of the initial handshake and are handled differently. SSLSocket.session and SSLSession are not compatible with TLS 1.3.\\n\\nClient-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.\\n\\nTLS 1.3 features like early data, deferred TLS client cert request, and rekeying are not supported yet.\\n\\nSee also\\n\\nTable of Contents\\n\\nssl — TLS/SSL wrapper for socket objects\\n\\nFunctions, Constants, and Exceptions\\n\\nSocket creation\\n\\nContext creation\\n\\nSignature algorithms\\n\\nExceptions\\n\\nRandom generation\\n\\nCertificate handling\\n\\nConstants\\n\\nSSL Sockets\\n\\nSSL Contexts\\n\\nCertificates\\n\\nCertificate chains\\n\\nCA certificates\\n\\nCombined key and certificate\\n\\nSelf-signed certificates\\n\\nExamples\\n\\nTesting for SSL support\\n\\nClient-side operation\\n\\nServer-side operation\\n\\nNotes on non-blocking sockets\\n\\nMemory BIO Support\\n\\nSSL session\\n\\nSecurity considerations\\n\\nBest defaults\\n\\nManual settings\\n\\nVerifying certificates\\n\\nProtocol versions\\n\\nCipher selection\\n\\nMulti-processing\\n\\nTLS 1.3\\n\\nPrevious topic\\n\\nsocket — Low-level networking interface\\n\\nNext topic\\n\\nselect — Waiting for I/O completion\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNetworking and Interprocess Communication »\\n\\nssl — TLS/SSL wrapper for socket objects\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\stat.html'}, page_content=\"Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nFile and Directory Access »\\n\\nstat — Interpreting stat() results\\n\\n|\\n\\nstat — Interpreting stat() results¶\\n\\nSource code: Lib/stat.py\\n\\nThe stat module defines constants and functions for interpreting the results of os.stat(), os.fstat() and os.lstat() (if they exist). For complete details about the stat(), fstat() and lstat() calls, consult the documentation for your system.\\n\\nChanged in version 3.4: The stat module is backed by a C implementation.\\n\\nThe stat module defines the following functions to test for specific file types:\\n\\nTwo additional functions are defined for more general manipulation of the file’s mode:\\n\\nNormally, you would use the 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 stat() system call for each test. These are also useful when checking for information about a file that isn’t handled by os.path, like the tests for block and character devices.\\n\\nExample:\\n\\nimport os, sys\\nfrom stat import *\\n\\ndef walktree(top, callback):\\n '''recursively descend the directory tree rooted at top,\\n calling the callback function for each regular file'''\\n\\n for f in os.listdir(top):\\n pathname = os.path.join(top, f)\\n mode = os.lstat(pathname).st_mode\\n if S_ISDIR(mode):\\n # It's a directory, recurse into it\\n walktree(pathname, callback)\\n elif S_ISREG(mode):\\n # It's a file, call the callback function\\n callback(pathname)\\n else:\\n # Unknown file type, print a message\\n print('Skipping %s' % pathname)\\n\\ndef visitfile(file):\\n print('visiting', file)\\n\\nif __name__ == '__main__':\\n walktree(sys.argv[1], visitfile)\\n\\nAn additional utility function is provided to convert a file’s mode in a human readable string:\\n\\nAll the variables below are simply symbolic indexes into the 10-tuple returned by os.stat(), os.fstat() or os.lstat().\\n\\nThe interpretation of “file size” changes according to the file type. For plain files this is the size of the file in bytes. For FIFOs and sockets under most flavors of Unix (including Linux in particular), the “size” is the number of bytes waiting to be read at the time of the call to os.stat(), os.fstat(), or os.lstat(); this can sometimes be useful, especially for polling one of these special files after a non-blocking open. The meaning of the size field for other character and block devices varies more, depending on the implementation of the underlying system call.\\n\\nThe variables below define the flags used in the ST_MODE field.\\n\\nUse of the functions above is more portable than use of the first set of flags:\\n\\nNote\\n\\nS_IFDOOR, S_IFPORT or S_IFWHT are defined as 0 when the platform does not have support for the file types.\\n\\nThe following flags can also be used in the mode argument of os.chmod():\\n\\nThe following flags can be used in the flags argument of os.chflags():\\n\\nSee the *BSD or macOS systems man page chflags(2) for more information.\\n\\nOn Windows, the following file attribute constants are available for use when testing bits in the st_file_attributes member returned by os.stat(). See the Windows API documentation for more detail on the meaning of these constants.\\n\\nOn Windows, the following constants are available for comparing against the st_reparse_tag member returned by os.lstat(). These are well-known constants, but are not an exhaustive list.\\n\\nOn Linux, the following file attribute constants are available for use when testing bits in the stx_attributes and stx_attributes_mask members returned by os.statx(). See the statx(2) man page for more detail on the meaning of these constants.\\n\\nPrevious topic\\n\\nos.path — Common pathname manipulations\\n\\nNext topic\\n\\nfilecmp — File and Directory Comparisons\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nFile and Directory Access »\\n\\nstat — Interpreting stat() results\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.\"), Document(metadata={'source': '..\\\\..\\\\docs\\\\statistics.html'}, page_content=\"Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNumeric and Mathematical Modules »\\n\\nstatistics — Mathematical statistics functions\\n\\n|\\n\\nstatistics — Mathematical statistics functions¶\\n\\nAdded in version 3.4.\\n\\nSource code: Lib/statistics.py\\n\\nThis module provides functions for calculating mathematical statistics of numeric (Real-valued) data.\\n\\nThe module is not intended to be a competitor to third-party libraries such as NumPy, SciPy, or proprietary full-featured statistics packages aimed at professional statisticians such as Minitab, SAS and Matlab. It is aimed at the level of graphing and scientific calculators.\\n\\nUnless explicitly noted, these functions support int, float, Decimal and Fraction. Behaviour with other types (whether in the numeric tower or not) is currently unsupported. Collections with a mix of types are also undefined and implementation-dependent. If your input data consists of mixed types, you may be able to use map() to ensure a consistent result, for example: map(float, input_data).\\n\\nSome datasets use NaN (not a number) values to represent missing data. Since NaNs have unusual comparison semantics, they cause surprising or undefined behaviors in the statistics functions that sort data or that count occurrences. The functions affected are median(), median_low(), median_high(), median_grouped(), mode(), multimode(), and quantiles(). The NaN values should be stripped before calling these functions:\\n\\n>>> from statistics import median\\n>>> from math import isnan\\n>>> from itertools import filterfalse\\n\\n>>> data = [20.7, float('NaN'),19.2, 18.3, float('NaN'), 14.4]\\n>>> sorted(data) # This has surprising behavior\\n[20.7, nan, 14.4, 18.3, 19.2, nan]\\n>>> median(data) # This result is unexpected\\n16.35\\n\\n>>> sum(map(isnan, data)) # Number of missing values\\n2\\n>>> clean = list(filterfalse(isnan, data)) # Strip NaN values\\n>>> clean\\n[20.7, 19.2, 18.3, 14.4]\\n>>> sorted(clean) # Sorting now works as expected\\n[14.4, 18.3, 19.2, 20.7]\\n>>> median(clean) # This result is now well defined\\n18.75\\n\\nAverages and measures of central location¶\\n\\nThese functions calculate an average or typical value from a population or sample.\\n\\nmean() Arithmetic mean (“average”) of data. fmean() Fast, floating-point arithmetic mean, with optional weighting. geometric_mean() Geometric mean of data. harmonic_mean() Harmonic mean of data. kde() Estimate the probability density distribution of the data. kde_random() Random sampling from the PDF generated by kde(). median() Median (middle value) of data. median_low() Low median of data. median_high() High median of data. median_grouped() Median (50th percentile) of grouped data. mode() Single mode (most common value) of discrete or nominal data. multimode() List of modes (most common values) of discrete or nominal data. quantiles() Divide data into intervals with equal probability.\\n\\nMeasures of spread¶\\n\\nThese functions calculate a measure of how much the population or sample tends to deviate from the typical or average values.\\n\\npstdev() Population standard deviation of data. pvariance() Population variance of data. stdev() Sample standard deviation of data. variance() Sample variance of data.\\n\\nStatistics for relations between two inputs¶\\n\\nThese functions calculate statistics regarding relations between two inputs.\\n\\ncovariance() Sample covariance for two variables. correlation() Pearson and Spearman’s correlation coefficients. linear_regression() Slope and intercept for simple linear regression.\\n\\nFunction details¶\\n\\nNote: The functions do not require the data given to them to be sorted. However, for reading convenience, most of the examples show sorted sequences.\\n\\nExceptions¶\\n\\nA single exception is defined:\\n\\nNormalDist objects¶\\n\\nNormalDist is a tool for creating and manipulating normal distributions of a random variable. It is a class that treats the mean and standard deviation of data measurements as a single entity.\\n\\nNormal distributions arise from the Central Limit Theorem and have a wide range of applications in statistics.\\n\\nExamples and Recipes¶\\n\\nClassic probability problems¶\\n\\nNormalDist readily solves classic probability problems.\\n\\nFor example, given historical data for SAT exams 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:\\n\\n>>> sat = NormalDist(1060, 195)\\n>>> fraction = sat.cdf(1200 + 0.5) - sat.cdf(1100 - 0.5)\\n>>> round(fraction * 100.0, 1)\\n18.4\\n\\nFind the quartiles and deciles for the SAT scores:\\n\\n>>> list(map(round, sat.quantiles()))\\n[928, 1060, 1192]\\n>>> list(map(round, sat.quantiles(n=10)))\\n[810, 896, 958, 1011, 1060, 1109, 1162, 1224, 1310]\\n\\nMonte Carlo inputs for simulations¶\\n\\nTo estimate the distribution for a model that isn’t easy to solve analytically, NormalDist can generate input samples for a Monte Carlo simulation:\\n\\n>>> def model(x, y, z):\\n... return (3*x + 7*x*y - 5*y) / (11 * z)\\n...\\n>>> n = 100_000\\n>>> X = NormalDist(10, 2.5).samples(n, seed=3652260728)\\n>>> Y = NormalDist(15, 1.75).samples(n, seed=4582495471)\\n>>> Z = NormalDist(50, 1.25).samples(n, seed=6582483453)\\n>>> quantiles(map(model, X, Y, Z))\\n[1.4591308524824727, 1.8035946855390597, 2.175091447274739]\\n\\nApproximating binomial distributions¶\\n\\nNormal distributions can be used to approximate Binomial distributions when the sample size is large and when the probability of a successful trial is near 50%.\\n\\nFor 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?\\n\\n>>> n = 750 # Sample size\\n>>> p = 0.65 # Preference for Python\\n>>> q = 1.0 - p # Preference for Ruby\\n>>> k = 500 # Room capacity\\n\\n>>> # Approximation using the cumulative normal distribution\\n>>> from math import sqrt\\n>>> round(NormalDist(mu=n*p, sigma=sqrt(n*p*q)).cdf(k + 0.5), 4)\\n0.8402\\n\\n>>> # Exact solution using the cumulative binomial distribution\\n>>> from math import comb, fsum\\n>>> round(fsum(comb(n, r) * p**r * q**(n-r) for r in range(k+1)), 4)\\n0.8402\\n\\n>>> # Approximation using a simulation\\n>>> from random import seed, binomialvariate\\n>>> seed(8675309)\\n>>> mean(binomialvariate(n, p) <= k for i in range(10_000))\\n0.8406\\n\\nNaive bayesian classifier¶\\n\\nNormal distributions commonly arise in machine learning problems.\\n\\nWikipedia has a nice example of a Naive Bayesian Classifier. The challenge is to predict a person’s gender from measurements of normally distributed features including height, weight, and foot size.\\n\\nWe’re given a training dataset with measurements for eight people. The measurements are assumed to be normally distributed, so we summarize the data with NormalDist:\\n\\n>>> height_male = NormalDist.from_samples([6, 5.92, 5.58, 5.92])\\n>>> height_female = NormalDist.from_samples([5, 5.5, 5.42, 5.75])\\n>>> weight_male = NormalDist.from_samples([180, 190, 170, 165])\\n>>> weight_female = NormalDist.from_samples([100, 150, 130, 150])\\n>>> foot_size_male = NormalDist.from_samples([12, 11, 12, 10])\\n>>> foot_size_female = NormalDist.from_samples([6, 8, 7, 9])\\n\\nNext, we encounter a new person whose feature measurements are known but whose gender is unknown:\\n\\n>>> ht = 6.0 # height\\n>>> wt = 130 # weight\\n>>> fs = 8 # foot size\\n\\nStarting with a 50% 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:\\n\\n>>> prior_male = 0.5\\n>>> prior_female = 0.5\\n>>> posterior_male = (prior_male * height_male.pdf(ht) *\\n... weight_male.pdf(wt) * foot_size_male.pdf(fs))\\n\\n>>> posterior_female = (prior_female * height_female.pdf(ht) *\\n... weight_female.pdf(wt) * foot_size_female.pdf(fs))\\n\\nThe final prediction goes to the largest posterior. This is known as the maximum a posteriori or MAP:\\n\\n>>> 'male' if posterior_male > posterior_female else 'female'\\n'female'\\n\\nTable of Contents\\n\\nstatistics — Mathematical statistics functions\\n\\nAverages and measures of central location\\n\\nMeasures of spread\\n\\nStatistics for relations between two inputs\\n\\nFunction details\\n\\nExceptions\\n\\nNormalDist objects\\n\\nExamples and Recipes\\n\\nClassic probability problems\\n\\nMonte Carlo inputs for simulations\\n\\nApproximating binomial distributions\\n\\nNaive bayesian classifier\\n\\nPrevious topic\\n\\nrandom — Generate pseudo-random numbers\\n\\nNext topic\\n\\nFunctional Programming Modules\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nNumeric and Mathematical Modules »\\n\\nstatistics — Mathematical statistics functions\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.\"), Document(metadata={'source': '..\\\\..\\\\docs\\\\stdtypes.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nBuilt-in Types\\n\\n|\\n\\nBuilt-in Types¶\\n\\nThe following sections describe the standard types that are built into the interpreter.\\n\\nThe principal built-in types are numerics, sequences, mappings, classes, instances and exceptions.\\n\\nSome collection classes are mutable. The methods that add, subtract, or rearrange their members in place, and don’t return a specific item, never return the collection instance itself but None.\\n\\nSome operations are supported by several object types; in particular, practically all objects can be compared for equality, tested for truth value, and converted to a string (with the repr() function or the slightly different str() function). The latter function is implicitly used when an object is written by the print() function.\\n\\nTruth Value Testing¶\\n\\nAny object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below.\\n\\nBy default, an object is considered true unless its class defines either a __bool__() method that returns False or a __len__() method that returns zero, when called with the object. [1] 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, NotImplemented). Here are most of the built-in objects considered false:\\n\\nconstants defined to be false: None and False\\n\\nzero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)\\n\\nempty sequences and collections: \\'\\', (), [], {}, set(), range(0)\\n\\nOperations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.)\\n\\nBoolean Operations — and, or, not¶\\n\\nThese are the Boolean operations, ordered by ascending priority:\\n\\nOperation Result Notes x or y if x is true, then x , else y (1) x and y if x is false, then x , else y (2) not x if x is false, then True ,\\nelse False (3)\\n\\nNotes:\\n\\nThis is a short-circuit operator, so it only evaluates the second argument if the first one is false.\\n\\nThis is a short-circuit operator, so it only evaluates the second argument if the first one is true.\\n\\nnot has a lower priority than non-Boolean operators, so not a == b is interpreted as not (a == b), and a == not b is a syntax error.\\n\\nComparisons¶\\n\\nThere are eight comparison operations in Python. They all have the same priority (which is higher than that of the Boolean operations). Comparisons can be chained arbitrarily; for example, x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).\\n\\nThis table summarizes the comparison operations:\\n\\nOperation Meaning < strictly less than <= less than or equal > strictly greater than >= greater than or equal == equal != not equal is object identity is not negated object identity\\n\\nUnless stated otherwise, objects of different types never compare equal. The == operator is always defined but for some object types (for example, class objects) is equivalent to is. The <, <=, > and >= operators are only defined where they make sense; for example, they raise a TypeError exception when one of the arguments is a complex number.\\n\\nNon-identical instances of a class normally compare as non-equal unless the class defines the __eq__() method.\\n\\nInstances of a class cannot be ordered with respect to other instances of the same class, or other types of object, unless the class defines enough of the methods __lt__(), __le__(), __gt__(), and __ge__() (in general, __lt__() and __eq__() are sufficient, if you want the conventional meanings of the comparison operators).\\n\\nThe behavior of the is and is not operators cannot be customized; also they can be applied to any two objects and never raise an exception.\\n\\nTwo more operations with the same syntactic priority, in and not in, are supported by types that are iterable or implement the __contains__() method.\\n\\nNumeric Types — int, float, complex¶\\n\\nThere are three distinct numeric types: integers, floating-point numbers, and complex numbers. In addition, Booleans are a subtype of integers. Integers have unlimited precision. Floating-point numbers are usually implemented using double in C; information about the precision and internal representation of floating-point numbers for the machine on which your program is running is available in sys.float_info. Complex numbers have a real and imaginary part, which are each a floating-point number. To extract these parts from a complex number z, use z.real and z.imag. (The standard library includes the additional numeric types fractions.Fraction, for rationals, and decimal.Decimal, for floating-point numbers with user-definable precision.)\\n\\nNumbers are created by numeric literals or as the result of built-in functions and operators. Unadorned integer literals (including hex, octal and binary numbers) yield integers. Numeric literals containing a decimal point or an exponent sign yield floating-point numbers. Appending \\'j\\' or \\'J\\' to a numeric literal yields an imaginary number (a complex number with a zero real part) which you can add to an integer or float to get a complex number with real and imaginary parts.\\n\\nThe constructors int(), float(), and complex() can be used to produce numbers of a specific type.\\n\\nPython 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:\\n\\nIf both arguments are complex numbers, no conversion is performed;\\n\\nif either argument is a complex or a floating-point number, the other is converted to a floating-point number;\\n\\notherwise, both must be integers and no conversion is necessary.\\n\\nArithmetic with complex and real operands is defined by the usual mathematical formula, for example:\\n\\nx + complex(u, v) = complex(x + u, v)\\nx * complex(u, v) = complex(x * u, x * v)\\n\\nA comparison between numbers of different types behaves as though the exact values of those numbers were being compared. [2]\\n\\nAll numeric types (except complex) support the following operations (for priorities of the operations, see Operator precedence):\\n\\nOperation Result Notes Full documentation x + y sum of x and y x - y difference of x and y x * y product of x and y x / y quotient of x and y x // y floored quotient of x and y (1)(2) x % y remainder of x / y (2) -x x negated +x x unchanged abs(x) absolute value or magnitude of x abs() int(x) x converted to integer (3)(6) int() float(x) x converted to floating point (4)(6) float() complex(re, im) a complex number with real part re , imaginary part im . im defaults to zero. (6) complex() c.conjugate() conjugate of the complex number c divmod(x, y) the pair (x // y, x % y) (2) divmod() pow(x, y) x to the power y (5) pow() x ** y x to the power y (5)\\n\\nNotes:\\n\\nAlso referred to as integer division. For operands of type int, the result has type int. For operands of type float, the result has type float. In general, the result is a whole integer, though the result’s type is not necessarily int. The result is always rounded towards minus infinity: 1//2 is 0, (-1)//2 is -1, 1//(-2) is -1, and (-1)//(-2) is 0.\\n\\nNot for complex numbers. Instead convert to floats using abs() if appropriate.\\n\\nConversion from float to int truncates, discarding the fractional part. See functions math.floor() and math.ceil() for alternative conversions.\\n\\nfloat also accepts the strings “nan” and “inf” with an optional prefix “+” or “-” for Not a Number (NaN) and positive or negative infinity.\\n\\nPython defines pow(0, 0) and 0 ** 0 to be 1, as is common for programming languages.\\n\\nThe numeric literals accepted include the digits 0 to 9 or any Unicode equivalent (code points with the Nd property).\\n\\nSee the Unicode Standard for a complete list of code points with the Nd property.\\n\\nAll numbers.Real types (int and float) also include the following operations:\\n\\nOperation Result math.trunc(x) x truncated to Integral round(x[, n]) x rounded to n digits,\\nrounding half to even. If n is\\nomitted, it defaults to 0. math.floor(x) the greatest Integral <= x math.ceil(x) the least Integral >= x\\n\\nFor additional numeric operations see the math and cmath modules.\\n\\nBitwise Operations on Integer Types¶\\n\\nBitwise operations only make sense for integers. The result of bitwise operations is calculated as though carried out in two’s complement with an infinite number of sign bits.\\n\\nThe priorities of the binary bitwise operations are all lower than the numeric operations and higher than the comparisons; the unary operation ~ has the same priority as the other unary numeric operations (+ and -).\\n\\nThis table lists the bitwise operations sorted in ascending priority:\\n\\nOperation Result Notes x | y bitwise or of x and y (4) x ^ y bitwise exclusive or of x and y (4) x & y bitwise and of x and y (4) x << n x shifted left by n bits (1)(2) x >> n x shifted right by n bits (1)(3) ~x the bits of x inverted\\n\\nNotes:\\n\\nNegative shift counts are illegal and cause a ValueError to be raised.\\n\\nA left shift by n bits is equivalent to multiplication by pow(2, n).\\n\\nA right shift by n bits is equivalent to floor division by pow(2, n).\\n\\nPerforming these calculations with at least one extra sign extension bit in a finite two’s complement representation (a working bit-width of 1 + max(x.bit_length(), y.bit_length()) or more) is sufficient to get the same result as if there were an infinite number of sign bits.\\n\\nAdditional Methods on Integer Types¶\\n\\nThe int type implements the numbers.Integral abstract base class. In addition, it provides a few more methods:\\n\\nAdditional Methods on Float¶\\n\\nThe float type implements the numbers.Real abstract base class. float also has the following additional methods.\\n\\nTwo methods support conversion to and from hexadecimal strings. Since Python’s floats are stored internally as binary numbers, converting a float to or from a decimal string usually involves a small rounding error. In contrast, hexadecimal strings allow exact representation and specification of floating-point numbers. This can be useful when debugging, and in numerical work.\\n\\nNote that float.hex() is an instance method, while float.fromhex() is a class method.\\n\\nA hexadecimal string takes the form:\\n\\n[sign] [\\'0x\\'] integer [\\'.\\' fraction] [\\'p\\' exponent]\\n\\nwhere the optional sign may by either + or -, integer and fraction are strings of hexadecimal digits, and exponent is a decimal integer with an optional leading sign. Case is not significant, and there must be at least one hexadecimal digit in either the integer or the fraction. This syntax is similar to the syntax specified in section 6.4.4.2 of the C99 standard, and also to the syntax used in Java 1.5 onwards. In particular, the output of float.hex() is usable as a hexadecimal floating-point literal in C or Java code, and hexadecimal strings produced by C’s %a format character or Java’s Double.toHexString are accepted by float.fromhex().\\n\\nNote that the exponent is written in decimal rather than hexadecimal, and that it gives the power of 2 by which to multiply the coefficient. For example, the hexadecimal string 0x3.a7p10 represents the floating-point number (3 + 10./16 + 7./16**2) * 2.0**10, or 3740.0:\\n\\n>>> float.fromhex(\\'0x3.a7p10\\')\\n3740.0\\n\\nApplying the reverse conversion to 3740.0 gives a different hexadecimal string representing the same number:\\n\\n>>> float.hex(3740.0)\\n\\'0x1.d380000000000p+11\\'\\n\\nAdditional Methods on Complex¶\\n\\nThe complex type implements the numbers.Complex abstract base class. complex also has the following additional methods.\\n\\nHashing of numeric types¶\\n\\nFor numbers x and y, possibly of different types, it’s a requirement that hash(x) == hash(y) whenever x == y (see the __hash__() method documentation for more details). For ease of implementation and efficiency across a variety of numeric types (including int, float, decimal.Decimal and fractions.Fraction) Python’s hash for numeric types is based on a single mathematical function that’s defined for any rational number, and hence applies to all instances of int and fractions.Fraction, and all finite instances of float and decimal.Decimal. Essentially, this function is given by reduction modulo P for a fixed prime P. The value of P is made available to Python as the modulus attribute of sys.hash_info.\\n\\nCPython implementation detail: Currently, the prime used is P = 2**31 - 1 on machines with 32-bit C longs and P = 2**61 - 1 on machines with 64-bit C longs.\\n\\nHere are the rules in detail:\\n\\nIf x = m / n is a nonnegative rational number and n is not divisible by P, define hash(x) as m * invmod(n, P) % P, where invmod(n, P) gives the inverse of n modulo P.\\n\\nIf x = m / n is a nonnegative rational number and n is divisible by P (but m is not) then n has no inverse modulo P and the rule above doesn’t apply; in this case define hash(x) to be the constant value sys.hash_info.inf.\\n\\nIf x = m / n is a negative rational number define hash(x) as -hash(-x). If the resulting hash is -1, replace it with -2.\\n\\nThe particular values sys.hash_info.inf and -sys.hash_info.inf are used as hash values for positive infinity or negative infinity (respectively).\\n\\nFor a complex number z, the hash values of the real and imaginary parts are combined by computing hash(z.real) + sys.hash_info.imag * hash(z.imag), reduced modulo 2**sys.hash_info.width so that it lies in range(-2**(sys.hash_info.width - 1), 2**(sys.hash_info.width - 1)). Again, if the result is -1, it’s replaced with -2.\\n\\nTo clarify the above rules, here’s some example Python code, equivalent to the built-in hash, for computing the hash of a rational number, float, or complex:\\n\\nimport sys, math\\n\\ndef hash_fraction(m, n):\\n \"\"\"Compute the hash of a rational number m / n.\\n\\n Assumes m and n are integers, with n positive.\\n Equivalent to hash(fractions.Fraction(m, n)).\\n\\n \"\"\"\\n P = sys.hash_info.modulus\\n # Remove common factors of P. (Unnecessary if m and n already coprime.)\\n while m % P == n % P == 0:\\n m, n = m // P, n // P\\n\\n if n % P == 0:\\n hash_value = sys.hash_info.inf\\n else:\\n # Fermat\\'s Little Theorem: pow(n, P-1, P) is 1, so\\n # pow(n, P-2, P) gives the inverse of n modulo P.\\n hash_value = (abs(m) % P) * pow(n, P - 2, P) % P\\n if m < 0:\\n hash_value = -hash_value\\n if hash_value == -1:\\n hash_value = -2\\n return hash_value\\n\\ndef hash_float(x):\\n \"\"\"Compute the hash of a float x.\"\"\"\\n\\n if math.isnan(x):\\n return object.__hash__(x)\\n elif math.isinf(x):\\n return sys.hash_info.inf if x > 0 else -sys.hash_info.inf\\n else:\\n return hash_fraction(*x.as_integer_ratio())\\n\\ndef hash_complex(z):\\n \"\"\"Compute the hash of a complex number z.\"\"\"\\n\\n hash_value = hash_float(z.real) + sys.hash_info.imag * hash_float(z.imag)\\n # do a signed reduction modulo 2**sys.hash_info.width\\n M = 2**(sys.hash_info.width - 1)\\n hash_value = (hash_value & (M - 1)) - (hash_value & M)\\n if hash_value == -1:\\n hash_value = -2\\n return hash_value\\n\\nBoolean Type - bool¶\\n\\nBooleans represent truth values. The bool type has exactly two constant instances: True and False.\\n\\nThe built-in function bool() converts any value to a boolean, if the value can be interpreted as a truth value (see section Truth Value Testing above).\\n\\nFor logical operations, use the boolean operators and, or and not. When applying the bitwise operators &, |, ^ to two booleans, they return a bool equivalent to the logical operations “and”, “or”, “xor”. However, the logical operators and, or and != should be preferred over &, | and ^.\\n\\nDeprecated since version 3.12: The use of the bitwise inversion operator ~ is deprecated and will raise an error in Python 3.16.\\n\\nbool is a subclass of int (see Numeric Types — int, float, complex). In many numeric contexts, False and True behave like the integers 0 and 1, respectively. However, relying on this is discouraged; explicitly convert using int() instead.\\n\\nIterator Types¶\\n\\nPython supports a concept of iteration over containers. This is implemented using two distinct methods; these are used to allow user-defined classes to support iteration. Sequences, described below in more detail, always support the iteration methods.\\n\\nOne method needs to be defined for container objects to provide iterable support:\\n\\nThe iterator objects themselves are required to support the following two methods, which together form the iterator protocol:\\n\\nPython defines several iterator objects to support iteration over general and specific sequence types, dictionaries, and other more specialized forms. The specific types are not important beyond their implementation of the iterator protocol.\\n\\nOnce an iterator’s __next__() method raises StopIteration, it must continue to do so on subsequent calls. Implementations that do not obey this property are deemed broken.\\n\\nGenerator Types¶\\n\\nPython’s generators provide a convenient way to implement the iterator protocol. If a container object’s __iter__() method is implemented as a generator, it will automatically return an iterator object (technically, a generator object) supplying the __iter__() and __next__() methods. More information about generators can be found in the documentation for the yield expression.\\n\\nSequence Types — list, tuple, range¶\\n\\nThere are three basic sequence types: lists, tuples, and range objects. Additional sequence types tailored for processing of binary data and text strings are described in dedicated sections.\\n\\nCommon Sequence Operations¶\\n\\nThe operations in the following table are supported by most sequence types, both mutable and immutable. The collections.abc.Sequence ABC is provided to make it easier to correctly implement these operations on custom sequence types.\\n\\nThis table lists the sequence operations sorted in ascending priority. In the table, s and t are sequences of the same type, n, i, j and k are integers and x is an arbitrary object that meets any type and value restrictions imposed by s.\\n\\nThe in and not in operations have the same priorities as the comparison operations. The + (concatenation) and * (repetition) operations have the same priority as the corresponding numeric operations. [3]\\n\\nOperation Result Notes x in s True if an item of s is\\nequal to x , else False (1) x not in s False if an item of s is\\nequal to x , else True (1) s + t the concatenation of s and t (6)(7) s * n or n * s equivalent to adding s to\\nitself n times (2)(7) s[i] i th item of s , origin 0 (3)(8) s[i:j] slice of s from i to j (3)(4) s[i:j:k] slice of s from i to j with step k (3)(5) len(s) length of s min(s) smallest item of s max(s) largest item of s\\n\\nSequences of the same type also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length. (For full details see Comparisons in the language reference.)\\n\\nForward and reversed iterators over mutable sequences access values using an index. That index will continue to march forward (or backward) even if the underlying sequence is mutated. The iterator terminates only when an IndexError or a StopIteration is encountered (or when the index drops below zero).\\n\\nNotes:\\n\\nWhile the in and not in operations are used only for simple containment testing in the general case, some specialised sequences (such as str, bytes and bytearray) also use them for subsequence testing:\\n\\n>>> \"gg\" in \"eggs\"\\nTrue\\n\\nValues of n less than 0 are treated as 0 (which yields an empty sequence of the same type as s). Note that items in the sequence s are not copied; they are referenced multiple times. This often haunts new Python programmers; consider:\\n\\n>>> lists = [[]] * 3\\n>>> lists\\n[[], [], []]\\n>>> lists[0].append(3)\\n>>> lists\\n[[3], [3], [3]]\\n\\nWhat has happened is that [[]] is a one-element list containing an empty list, so all three elements of [[]] * 3 are references to this single empty list. Modifying any of the elements of lists modifies this single list. You can create a list of different lists this way:\\n\\n>>> lists = [[] for i in range(3)]\\n>>> lists[0].append(3)\\n>>> lists[1].append(5)\\n>>> lists[2].append(7)\\n>>> lists\\n[[3], [5], [7]]\\n\\nFurther explanation is available in the FAQ entry How do I create a multidimensional list?.\\n\\nIf i or j is negative, the index is relative to the end of sequence s: len(s) + i or len(s) + j is substituted. But note that -0 is still 0.\\n\\nThe slice of s from i to j is defined as the sequence of items with index k such that i <= k < j.\\n\\nIf i is omitted or None, use 0.\\n\\nIf j is omitted or None, use len(s).\\n\\nIf i or j is less than -len(s), use 0.\\n\\nIf i or j is greater than len(s), use len(s).\\n\\nIf i is greater than or equal to j, the slice is empty.\\n\\nThe slice of s from i to j with step k is defined as the sequence of items with index x = i + n*k such that 0 <= n < (j-i)/k. In other words, the indices are i, i+k, i+2*k, i+3*k and so on, stopping when j is reached (but never including j). When k is positive, i and j are reduced to len(s) if they are greater. When k is negative, i and j are reduced to len(s) - 1 if they are greater. If i or j are omitted or None, they become “end” values (which end depends on the sign of k). Note, k cannot be zero. If k is None, it is treated like 1.\\n\\nConcatenating immutable sequences always results in a new object. This means that building up a sequence by repeated concatenation will have a quadratic runtime cost in the total sequence length. To get a linear runtime cost, you must switch to one of the alternatives below:\\n\\nif concatenating str objects, you can build a list and use str.join() at the end or else write to an io.StringIO instance and retrieve its value when complete\\n\\nif concatenating bytes objects, you can similarly use bytes.join() or io.BytesIO, or you can do in-place concatenation with a bytearray object. bytearray objects are mutable and have an efficient overallocation mechanism\\n\\nif concatenating tuple objects, extend a list instead\\n\\nfor other types, investigate the relevant class documentation\\n\\nSome sequence types (such as range) only support item sequences that follow specific patterns, and hence don’t support sequence concatenation or repetition.\\n\\nAn IndexError is raised if i is outside the sequence range.\\n\\nSequence Methods\\n\\nSequence types also support the following methods:\\n\\nImmutable Sequence Types¶\\n\\nThe only operation that immutable sequence types generally implement that is not also implemented by mutable sequence types is support for the hash() built-in.\\n\\nThis support allows immutable sequences, such as tuple instances, to be used as dict keys and stored in set and frozenset instances.\\n\\nAttempting to hash an immutable sequence that contains unhashable values will result in TypeError.\\n\\nMutable Sequence Types¶\\n\\nThe operations in the following table are defined on mutable sequence types. The collections.abc.MutableSequence ABC is provided to make it easier to correctly implement these operations on custom sequence types.\\n\\nIn the table s is an instance of a mutable sequence type, t is any iterable object and x is an arbitrary object that meets any type and value restrictions imposed by s (for example, bytearray only accepts integers that meet the value restriction 0 <= x <= 255).\\n\\nOperation Result Notes s[i] = x item i of s is replaced by x del s[i] removes item i of s s[i:j] = t slice of s from i to j is replaced by the contents of\\nthe iterable t del s[i:j] removes the elements of s[i:j] from the list\\n(same as s[i:j] = [] ) s[i:j:k] = t the elements of s[i:j:k] are replaced by those of t (1) del s[i:j:k] removes the elements of s[i:j:k] from the list s += t extends s with the\\ncontents of t (for the\\nmost part the same as s[len(s):len(s)] = t ) s *= n updates s with its contents\\nrepeated n times (2)\\n\\nNotes:\\n\\nIf k is not equal to 1, t must have the same length as the slice it is replacing.\\n\\nThe value n is an integer, or an object implementing __index__(). Zero and negative values of n clear the sequence. Items in the sequence are not copied; they are referenced multiple times, as explained for s * n under Common Sequence Operations.\\n\\nMutable Sequence Methods\\n\\nMutable sequence types also support the following methods:\\n\\nLists¶\\n\\nLists are mutable sequences, typically used to store collections of homogeneous items (where the precise degree of similarity will vary by application).\\n\\nSee also\\n\\nFor detailed information on thread-safety guarantees for list objects, see Thread safety for list objects.\\n\\nTuples¶\\n\\nTuples are immutable sequences, typically used to store collections of heterogeneous data (such as the 2-tuples produced by the enumerate() built-in). Tuples are also used for cases where an immutable sequence of homogeneous data is needed (such as allowing storage in a set or dict instance).\\n\\nFor heterogeneous collections of data where access by name is clearer than access by index, collections.namedtuple() may be a more appropriate choice than a simple tuple object.\\n\\nRanges¶\\n\\nThe range type represents an immutable sequence of numbers and is commonly used for looping a specific number of times in for loops.\\n\\nThe advantage of the range type over a regular list or tuple is that a range object will always take the same (small) amount of memory, no matter the size of the range it represents (as it only stores the start, stop and step values, calculating individual items and subranges as needed).\\n\\nRange objects implement the collections.abc.Sequence ABC, and provide features such as containment tests, element index lookup, slicing and support for negative indices (see Sequence Types — list, tuple, range):\\n\\n>>> r = range(0, 20, 2)\\n>>> r\\nrange(0, 20, 2)\\n>>> 11 in r\\nFalse\\n>>> 10 in r\\nTrue\\n>>> r.index(10)\\n5\\n>>> r[5]\\n10\\n>>> r[:5]\\nrange(0, 10, 2)\\n>>> r[-1]\\n18\\n\\nTesting range objects for equality with == and != compares them as sequences. That is, two range objects are considered equal if they represent the same sequence of values. (Note that two range objects that compare equal might have different start, stop and step attributes, for example range(0) == range(2, 1, 3) or range(0, 3, 2) == range(0, 4, 2).)\\n\\nChanged in version 3.2: Implement the Sequence ABC. Support slicing and negative indices. Test int objects for membership in constant time instead of iterating through all items.\\n\\nChanged in version 3.3: Define ‘==’ and ‘!=’ to compare range objects based on the sequence of values they define (instead of comparing based on object identity).\\n\\nAdded the start, stop and step attributes.\\n\\nSee also\\n\\nThe linspace recipe shows how to implement a lazy version of range suitable for floating-point applications.\\n\\nText and Binary Sequence Type Methods Summary¶\\n\\nThe following table summarizes the text and binary sequence types methods by category.\\n\\nCategory str methods bytes and bytearray methods Formatting str.format() str.format_map() f-strings printf-style String Formatting printf-style Bytes Formatting Searching and Replacing str.find() str.rfind() bytes.find() bytes.rfind() str.index() str.rindex() bytes.index() bytes.rindex() str.startswith() bytes.startswith() str.endswith() bytes.endswith() str.count() bytes.count() str.replace() bytes.replace() Splitting and Joining str.split() str.rsplit() bytes.split() bytes.rsplit() str.splitlines() bytes.splitlines() str.partition() bytes.partition() str.rpartition() bytes.rpartition() str.join() bytes.join() String Classification str.isalpha() bytes.isalpha() str.isdecimal() str.isdigit() bytes.isdigit() str.isnumeric() str.isalnum() bytes.isalnum() str.isidentifier() str.islower() bytes.islower() str.isupper() bytes.isupper() str.istitle() bytes.istitle() str.isspace() bytes.isspace() str.isprintable() Case Manipulation str.lower() bytes.lower() str.upper() bytes.upper() str.casefold() str.capitalize() bytes.capitalize() str.title() bytes.title() str.swapcase() bytes.swapcase() Padding and Stripping str.ljust() str.rjust() bytes.ljust() bytes.rjust() str.center() bytes.center() str.expandtabs() bytes.expandtabs() str.strip() bytes.strip() str.lstrip() str.rstrip() bytes.lstrip() bytes.rstrip() Translation and Encoding str.translate() bytes.translate() str.maketrans() bytes.maketrans() str.encode() bytes.decode()\\n\\nText Sequence Type — str¶\\n\\nTextual data in Python is handled with str objects, or strings. Strings are immutable sequences of Unicode code points. String literals are written in a variety of ways:\\n\\nSingle quotes: \\'allows embedded \"double\" quotes\\'\\n\\nDouble quotes: \"allows embedded \\'single\\' quotes\"\\n\\nTriple quoted: \\'\\'\\'Three single quotes\\'\\'\\', \"\"\"Three double quotes\"\"\"\\n\\nTriple quoted strings may span multiple lines - all associated whitespace will be included in the string literal.\\n\\nString literals that are part of a single expression and have only whitespace between them will be implicitly converted to a single string literal. That is, (\"spam \" \"eggs\") == \"spam eggs\".\\n\\nSee String and Bytes literals for more about the various forms of string literal, including supported escape sequences, and the r (“raw”) prefix that disables most escape sequence processing.\\n\\nStrings may also be created from other objects using the str constructor.\\n\\nSince there is no separate “character” type, indexing a string produces strings of length 1. That is, for a non-empty string s, s[0] == s[0:1].\\n\\nThere is also no mutable string type, but str.join() or io.StringIO can be used to efficiently construct strings from multiple fragments.\\n\\nChanged in version 3.3: For backwards compatibility with the Python 2 series, the u prefix is once again permitted on string literals. It has no effect on the meaning of string literals and cannot be combined with the r prefix.\\n\\nString Methods¶\\n\\nStrings implement all of the common sequence operations, along with the additional methods described below.\\n\\nStrings also support two styles of string formatting, one providing a large degree of flexibility and customization (see str.format(), Format String Syntax and Custom String Formatting) and the other based on C printf style formatting that handles a narrower range of types and is slightly harder to use correctly, but is often faster for the cases it can handle (printf-style String Formatting).\\n\\nThe Text Processing Services section of the standard library covers a number of other modules that provide various text related utilities (including regular expression support in the re module).\\n\\nFormatted String Literals (f-strings)¶\\n\\nAdded in version 3.6.\\n\\nChanged in version 3.7: The await and async for can be used in expressions within f-strings.\\n\\nChanged in version 3.8: Added the debug specifier (=)\\n\\nChanged in version 3.12: Many restrictions on expressions within f-strings have been removed. Notably, nested strings, comments, and backslashes are now permitted.\\n\\nAn f-string (formally a formatted string literal) is a string literal that is prefixed with f or F. This type of string literal allows embedding the results of arbitrary Python expressions within replacement fields, which are delimited by curly brackets ({}). Each replacement field must contain an expression, optionally followed by:\\n\\na debug specifier – an equal sign (=);\\n\\na conversion specifier – !s, !r or !a; and/or\\n\\na format specifier prefixed with a colon (:).\\n\\nSee the Lexical Analysis section on f-strings for details on the syntax of these fields.\\n\\nDebug specifier¶\\n\\nAdded in version 3.8.\\n\\nIf a debug specifier – an equal sign (=) – 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:\\n\\n>>> number = 14.3\\n>>> f\\'{number=}\\'\\n\\'number=14.3\\'\\n\\nWhitespace before, inside and after the expression, as well as whitespace after the equal sign, is significant — it is retained in the result:\\n\\n>>> f\\'{ number - 4 = }\\'\\n\\' number - 4 = 10.3\\'\\n\\nConversion specifier¶\\n\\nBy default, the value of a replacement field expression is converted to a string using str():\\n\\n>>> from fractions import Fraction\\n>>> one_third = Fraction(1, 3)\\n>>> f\\'{one_third}\\'\\n\\'1/3\\'\\n\\nWhen a debug specifier but no format specifier is used, the default conversion instead uses repr():\\n\\n>>> f\\'{one_third = }\\'\\n\\'one_third = Fraction(1, 3)\\'\\n\\nThe conversion can be specified explicitly using one of these specifiers:\\n\\n!s for str()\\n\\n!r for repr()\\n\\n!a for ascii()\\n\\nFor example:\\n\\n>>> str(one_third)\\n\\'1/3\\'\\n>>> repr(one_third)\\n\\'Fraction(1, 3)\\'\\n\\n>>> f\\'{one_third!s} is {one_third!r}\\'\\n\\'1/3 is Fraction(1, 3)\\'\\n\\n>>> string = \"¡kočka 😸!\"\\n>>> ascii(string)\\n\"\\'\\\\\\\\xa1ko\\\\\\\\u010dka \\\\\\\\U0001f638!\\'\"\\n\\n>>> f\\'{string = !a}\\'\\n\"string = \\'\\\\\\\\xa1ko\\\\\\\\u010dka \\\\\\\\U0001f638!\\'\"\\n\\nFormat specifier¶\\n\\nAfter the expression has been evaluated, and possibly converted using an explicit conversion specifier, it is formatted using the format() function. If the replacement field includes a format specifier introduced by a colon (:), the specifier is passed to format() as the second argument. The result of format() is then used as the final value for the replacement field. For example:\\n\\n>>> from fractions import Fraction\\n>>> one_third = Fraction(1, 3)\\n>>> f\\'{one_third:.6f}\\'\\n\\'0.333333\\'\\n>>> f\\'{one_third:_^+10}\\'\\n\\'___+1/3___\\'\\n>>> >>> f\\'{one_third!r:_^20}\\'\\n\\'___Fraction(1, 3)___\\'\\n>>> f\\'{one_third = :~>10}~\\'\\n\\'one_third = ~~~~~~~1/3~\\'\\n\\nTemplate String Literals (t-strings)¶\\n\\nAn t-string (formally a template string literal) is a string literal that is prefixed with t or T.\\n\\nThese strings follow the same syntax and evaluation rules as formatted string literals, with for the following differences:\\n\\nRather than evaluating to a str object, template string literals evaluate to a string.templatelib.Template object.\\n\\nThe format() protocol is not used. Instead, the format specifier and conversions (if any) are passed to a new Interpolation object that is created for each evaluated expression. It is up to code that processes the resulting Template object to decide how to handle format specifiers and conversions.\\n\\nFormat specifiers containing nested replacement fields are evaluated eagerly, prior to being passed to the Interpolation object. For instance, an interpolation of the form {amount:.{precision}f} will evaluate the inner expression {precision} to determine the value of the format_spec attribute. If precision were to be 2, the resulting format specifier would be \\'.2f\\'.\\n\\nWhen the equals sign \\'=\\' 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 Interpolation instance for the expression will be created as normal, except that conversion will be set to ‘r’ (repr()) by default. If an explicit conversion or format specifier are provided, this will override the default behaviour.\\n\\nprintf-style String Formatting¶\\n\\nNote\\n\\nThe 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).\\n\\nUsing formatted string literals, the str.format() interface, or string.Template may help avoid these errors. Each of these alternatives provides their own trade-offs and benefits of simplicity, flexibility, and/or extensibility.\\n\\nString objects have one unique built-in operation: the % operator (modulo). This is also known as the string formatting or interpolation operator. Given format % values (where format is a string), % conversion specifications in format are replaced with zero or more elements of values. The effect is similar to using the sprintf() function in the C language. For example:\\n\\n>>> print(\\'%s has %d quote types.\\' % (\\'Python\\', 2))\\nPython has 2 quote types.\\n\\nIf format requires a single argument, values may be a single non-tuple object. [5] Otherwise, values must be a tuple with exactly the number of items specified by the format string, or a single mapping object (for example, a dictionary).\\n\\nA conversion specifier contains two or more characters and has the following components, which must occur in this order:\\n\\nThe \\'%\\' character, which marks the start of the specifier.\\n\\nMapping key (optional), consisting of a parenthesised sequence of characters (for example, (somename)).\\n\\nConversion flags (optional), which affect the result of some conversion types.\\n\\nMinimum field width (optional). If specified as an \\'*\\' (asterisk), the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precision.\\n\\nPrecision (optional), given as a \\'.\\' (dot) followed by the precision. If specified as \\'*\\' (an asterisk), the actual precision is read from the next element of the tuple in values, and the value to convert comes after the precision.\\n\\nLength modifier (optional).\\n\\nConversion type.\\n\\nWhen the right argument is a dictionary (or other mapping type), then the formats in the string must include a parenthesised mapping key into that dictionary inserted immediately after the \\'%\\' character. The mapping key selects the value to be formatted from the mapping. For example:\\n\\n>>> print(\\'%(language)s has %(number)03d quote types.\\' %\\n... {\\'language\\': \"Python\", \"number\": 2})\\nPython has 002 quote types.\\n\\nIn this case no * specifiers may occur in a format (since they require a sequential parameter list).\\n\\nThe conversion flag characters are:\\n\\nFlag Meaning \\'#\\' The value conversion will use the “alternate form” (where defined\\nbelow). \\'0\\' The conversion will be zero padded for numeric values. \\'-\\' The converted value is left adjusted (overrides the \\'0\\' conversion if both are given). \\' \\' (a space) A blank should be left before a positive number (or empty\\nstring) produced by a signed conversion. \\'+\\' A sign character ( \\'+\\' or \\'-\\' ) will precede the conversion\\n(overrides a “space” flag).\\n\\nA length modifier (h, l, or L) may be present, but is ignored as it is not necessary for Python – so e.g. %ld is identical to %d.\\n\\nThe conversion types are:\\n\\nConversion Meaning Notes \\'d\\' Signed integer decimal. \\'i\\' Signed integer decimal. \\'o\\' Signed octal value. (1) \\'u\\' Obsolete type – it is identical to \\'d\\' . (6) \\'x\\' Signed hexadecimal (lowercase). (2) \\'X\\' Signed hexadecimal (uppercase). (2) \\'e\\' Floating-point exponential format (lowercase). (3) \\'E\\' Floating-point exponential format (uppercase). (3) \\'f\\' Floating-point decimal format. (3) \\'F\\' Floating-point decimal format. (3) \\'g\\' Floating-point format. Uses lowercase exponential\\nformat if exponent is less than -4 or not less than\\nprecision, decimal format otherwise. (4) \\'G\\' Floating-point format. Uses uppercase exponential\\nformat if exponent is less than -4 or not less than\\nprecision, decimal format otherwise. (4) \\'c\\' Single character (accepts integer or single\\ncharacter string). \\'r\\' String (converts any Python object using repr() ). (5) \\'s\\' String (converts any Python object using str() ). (5) \\'a\\' String (converts any Python object using ascii() ). (5) \\'%\\' No argument is converted, results in a \\'%\\' character in the result.\\n\\nNotes:\\n\\nThe alternate form causes a leading octal specifier (\\'0o\\') to be inserted before the first digit.\\n\\nThe alternate form causes a leading \\'0x\\' or \\'0X\\' (depending on whether the \\'x\\' or \\'X\\' format was used) to be inserted before the first digit.\\n\\nThe alternate form causes the result to always contain a decimal point, even if no digits follow it.\\n\\nThe precision determines the number of digits after the decimal point and defaults to 6.\\n\\nThe alternate form causes the result to always contain a decimal point, and trailing zeroes are not removed as they would otherwise be.\\n\\nThe precision determines the number of significant digits before and after the decimal point and defaults to 6.\\n\\nIf precision is N, the output is truncated to N characters.\\n\\nSee PEP 237.\\n\\nSince Python strings have an explicit length, %s conversions do not assume that \\'\\\\0\\' is the end of the string.\\n\\nChanged in version 3.1: %f conversions for numbers whose absolute value is over 1e50 are no longer replaced by %g conversions.\\n\\nBinary Sequence Types — bytes, bytearray, memoryview¶\\n\\nThe core built-in types for manipulating binary data are bytes and bytearray. They are supported by memoryview which uses the buffer protocol to access the memory of other binary objects without needing to make a copy.\\n\\nThe array module supports efficient storage of basic data types like 32-bit integers and IEEE754 double-precision floating values.\\n\\nBytes Objects¶\\n\\nBytes objects are immutable sequences of single bytes. Since many major binary protocols are based on the ASCII text encoding, bytes objects offer several methods that are only valid when working with ASCII compatible data and are closely related to string objects in a variety of other ways.\\n\\nSince bytes objects are sequences of integers (akin to a tuple), for a bytes object b, b[0] will be an integer, while b[0:1] will be a bytes object of length 1. (This contrasts with text strings, where both indexing and slicing will produce a string of length 1)\\n\\nThe representation of bytes objects uses the literal format (b\\'...\\') since it is often more useful than e.g. bytes([46, 46, 46]). You can always convert a bytes object into a list of integers using list(b).\\n\\nBytearray Objects¶\\n\\nbytearray objects are a mutable counterpart to bytes objects.\\n\\nSince bytearray objects are sequences of integers (akin to a list), for a bytearray object b, b[0] will be an integer, while b[0:1] will be a bytearray object of length 1. (This contrasts with text strings, where both indexing and slicing will produce a string of length 1)\\n\\nThe representation of bytearray objects uses the bytes literal format (bytearray(b\\'...\\')) since it is often more useful than e.g. bytearray([46, 46, 46]). You can always convert a bytearray object into a list of integers using list(b).\\n\\nBytes and Bytearray Operations¶\\n\\nBoth bytes and bytearray objects support the common sequence operations. They interoperate not just with operands of the same type, but with any bytes-like object. Due to this flexibility, they can be freely mixed in operations without causing errors. However, the return type of the result may depend on the order of operands.\\n\\nNote\\n\\nThe methods on bytes and bytearray objects don’t accept strings as their arguments, just as the methods on strings don’t accept bytes as their arguments. For example, you have to write:\\n\\na = \"abc\"\\nb = a.replace(\"a\", \"f\")\\n\\nand:\\n\\na = b\"abc\"\\nb = a.replace(b\"a\", b\"f\")\\n\\nSome bytes and bytearray operations assume the use of ASCII compatible binary formats, and hence should be avoided when working with arbitrary binary data. These restrictions are covered below.\\n\\nNote\\n\\nUsing these ASCII based operations to manipulate binary data that is not stored in an ASCII based format may lead to data corruption.\\n\\nThe following methods on bytes and bytearray objects can be used with arbitrary binary data.\\n\\nThe following methods on bytes and bytearray objects have default behaviours that assume the use of ASCII compatible binary formats, but can still be used with arbitrary binary data by passing appropriate arguments. Note that all of the bytearray methods in this section do not operate in place, and instead produce new objects.\\n\\nThe following methods on bytes and bytearray objects assume the use of ASCII compatible binary formats and should not be applied to arbitrary binary data. Note that all of the bytearray methods in this section do not operate in place, and instead produce new objects.\\n\\nprintf-style Bytes Formatting¶\\n\\nNote\\n\\nThe 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). If the value being printed may be a tuple or dictionary, wrap it in a tuple.\\n\\nBytes objects (bytes/bytearray) have one unique built-in operation: the % operator (modulo). This is also known as the bytes formatting or interpolation operator. Given format % values (where format is a bytes object), % conversion specifications in format are replaced with zero or more elements of values. The effect is similar to using the sprintf() in the C language.\\n\\nIf format requires a single argument, values may be a single non-tuple object. [5] Otherwise, values must be a tuple with exactly the number of items specified by the format bytes object, or a single mapping object (for example, a dictionary).\\n\\nA conversion specifier contains two or more characters and has the following components, which must occur in this order:\\n\\nThe \\'%\\' character, which marks the start of the specifier.\\n\\nMapping key (optional), consisting of a parenthesised sequence of characters (for example, (somename)).\\n\\nConversion flags (optional), which affect the result of some conversion types.\\n\\nMinimum field width (optional). If specified as an \\'*\\' (asterisk), the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precision.\\n\\nPrecision (optional), given as a \\'.\\' (dot) followed by the precision. If specified as \\'*\\' (an asterisk), the actual precision is read from the next element of the tuple in values, and the value to convert comes after the precision.\\n\\nLength modifier (optional).\\n\\nConversion type.\\n\\nWhen the right argument is a dictionary (or other mapping type), then the formats in the bytes object must include a parenthesised mapping key into that dictionary inserted immediately after the \\'%\\' character. The mapping key selects the value to be formatted from the mapping. For example:\\n\\n>>> print(b\\'%(language)s has %(number)03d quote types.\\' %\\n... {b\\'language\\': b\"Python\", b\"number\": 2})\\nb\\'Python has 002 quote types.\\'\\n\\nIn this case no * specifiers may occur in a format (since they require a sequential parameter list).\\n\\nThe conversion flag characters are:\\n\\nFlag Meaning \\'#\\' The value conversion will use the “alternate form” (where defined\\nbelow). \\'0\\' The conversion will be zero padded for numeric values. \\'-\\' The converted value is left adjusted (overrides the \\'0\\' conversion if both are given). \\' \\' (a space) A blank should be left before a positive number (or empty\\nstring) produced by a signed conversion. \\'+\\' A sign character ( \\'+\\' or \\'-\\' ) will precede the conversion\\n(overrides a “space” flag).\\n\\nA length modifier (h, l, or L) may be present, but is ignored as it is not necessary for Python – so e.g. %ld is identical to %d.\\n\\nThe conversion types are:\\n\\nConversion Meaning Notes \\'d\\' Signed integer decimal. \\'i\\' Signed integer decimal. \\'o\\' Signed octal value. (1) \\'u\\' Obsolete type – it is identical to \\'d\\' . (8) \\'x\\' Signed hexadecimal (lowercase). (2) \\'X\\' Signed hexadecimal (uppercase). (2) \\'e\\' Floating-point exponential format (lowercase). (3) \\'E\\' Floating-point exponential format (uppercase). (3) \\'f\\' Floating-point decimal format. (3) \\'F\\' Floating-point decimal format. (3) \\'g\\' Floating-point format. Uses lowercase exponential\\nformat if exponent is less than -4 or not less than\\nprecision, decimal format otherwise. (4) \\'G\\' Floating-point format. Uses uppercase exponential\\nformat if exponent is less than -4 or not less than\\nprecision, decimal format otherwise. (4) \\'c\\' Single byte (accepts integer or single\\nbyte objects). \\'b\\' Bytes (any object that follows the buffer protocol or has __bytes__() ). (5) \\'s\\' \\'s\\' is an alias for \\'b\\' and should only\\nbe used for Python2/3 code bases. (6) \\'a\\' Bytes (converts any Python object using repr(obj).encode(\\'ascii\\', \\'backslashreplace\\') ). (5) \\'r\\' \\'r\\' is an alias for \\'a\\' and should only\\nbe used for Python2/3 code bases. (7) \\'%\\' No argument is converted, results in a \\'%\\' character in the result.\\n\\nNotes:\\n\\nThe alternate form causes a leading octal specifier (\\'0o\\') to be inserted before the first digit.\\n\\nThe alternate form causes a leading \\'0x\\' or \\'0X\\' (depending on whether the \\'x\\' or \\'X\\' format was used) to be inserted before the first digit.\\n\\nThe alternate form causes the result to always contain a decimal point, even if no digits follow it.\\n\\nThe precision determines the number of digits after the decimal point and defaults to 6.\\n\\nThe alternate form causes the result to always contain a decimal point, and trailing zeroes are not removed as they would otherwise be.\\n\\nThe precision determines the number of significant digits before and after the decimal point and defaults to 6.\\n\\nIf precision is N, the output is truncated to N characters.\\n\\nb\\'%s\\' is deprecated, but will not be removed during the 3.x series.\\n\\nb\\'%r\\' is deprecated, but will not be removed during the 3.x series.\\n\\nSee PEP 237.\\n\\nNote\\n\\nThe bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.\\n\\nSee also\\n\\nPEP 461 - Adding % formatting to bytes and bytearray\\n\\nAdded in version 3.5.\\n\\nMemory Views¶\\n\\nmemoryview objects allow Python code to access the internal data of an object that supports the buffer protocol without copying.\\n\\nSet Types — set, frozenset¶\\n\\nA set object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. (For other containers see the built-in dict, list, and tuple classes, and the collections module.)\\n\\nLike other collections, sets support x in set, len(set), and for x in set. Being an unordered collection, sets do not record element position or order of insertion. Accordingly, sets do not support indexing, slicing, or other sequence-like behavior.\\n\\nThere are currently two built-in set types, set and frozenset. The set type is mutable — the contents can be changed using methods like add() and 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 frozenset type is immutable and 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.\\n\\nNon-empty sets (not frozensets) can be created by placing a comma-separated list of elements within braces, for example: {\\'jack\\', \\'sjoerd\\'}, in addition to the set constructor.\\n\\nThe constructors for both classes work the same:\\n\\nSets can be created by several means:\\n\\nUse a comma-separated list of elements within braces: {\\'jack\\', \\'sjoerd\\'}\\n\\nUse a set comprehension: {c for c in \\'abracadabra\\' if c not in \\'abc\\'}\\n\\nUse the type constructor: set(), set(\\'foobar\\'), set([\\'a\\', \\'b\\', \\'foo\\'])\\n\\nInstances of set and frozenset provide the following operations:\\n\\nNote, the non-operator versions of union(), intersection(), difference(), symmetric_difference(), issubset(), and 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 set(\\'abc\\') & \\'cbs\\' in favor of the more readable set(\\'abc\\').intersection(\\'cbs\\').\\n\\nBoth set and frozenset support set to set comparisons. Two sets are equal if and only if every element of each set is contained in the other (each is a subset of the other). A set is less than another set if and only if the first set is a proper subset of the second set (is a subset, but is not equal). A set is greater than another set if and only if the first set is a proper superset of the second set (is a superset, but is not equal).\\n\\nInstances of set are compared to instances of frozenset based on their members. For example, set(\\'abc\\') == frozenset(\\'abc\\') returns True and so does set(\\'abc\\') in set([frozenset(\\'abc\\')]).\\n\\nThe subset and equality comparisons do not generalize to a total ordering function. For example, any two nonempty disjoint sets are not equal and are not subsets of each other, so all of the following return False: ab.\\n\\nSince sets only define partial ordering (subset relationships), the output of the list.sort() method is undefined for lists of sets.\\n\\nSet elements, like dictionary keys, must be hashable.\\n\\nBinary operations that mix set instances with frozenset return the type of the first operand. For example: frozenset(\\'ab\\') | set(\\'bc\\') returns an instance of frozenset.\\n\\nThe following table lists operations available for set that do not apply to immutable instances of frozenset:\\n\\nNote, the non-operator versions of the update(), intersection_update(), difference_update(), and symmetric_difference_update() methods will accept any iterable as an argument.\\n\\nNote, the elem argument to the __contains__(), remove(), and discard() methods may be a set. To support searching for an equivalent frozenset, a temporary one is created from elem.\\n\\nMapping types — dict, frozendict¶\\n\\nA mapping object maps hashable values to arbitrary objects. There are currently two standard mapping types, the dictionary and frozendict. (For other containers see the built-in list, set, and tuple classes, and the collections module.)\\n\\nA dictionary’s keys are almost arbitrary values. Values that are not hashable, that is, values containing lists, dictionaries or other mutable types (that are compared by value rather than by object identity) may not be used as keys. Values that compare equal (such as 1, 1.0, and True) can be used interchangeably to index the same dictionary entry.\\n\\nSee also\\n\\nFor detailed information on thread-safety guarantees for dict objects, see Thread safety for dict objects.\\n\\nDictionary view objects¶\\n\\nThe objects returned by dict.keys(), dict.values() and dict.items() are view objects. They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes.\\n\\nDictionary views can be iterated over to yield their respective data, and support membership tests:\\n\\nKeys views are set-like since their entries are unique and hashable. Items views also have set-like operations since the (key, value) pairs are unique and the keys are hashable. If all values in an items view are hashable as well, then the items view can interoperate with other sets. (Values views are not treated as set-like since the entries are generally not unique.) For set-like views, all of the operations defined for the abstract base class collections.abc.Set are available (for example, ==, <, or ^). While using set operators, set-like views accept any iterable as the other operand, unlike sets which only accept sets as the input.\\n\\nAn example of dictionary view usage:\\n\\n>>> dishes = {\\'eggs\\': 2, \\'sausage\\': 1, \\'bacon\\': 1, \\'spam\\': 500}\\n>>> keys = dishes.keys()\\n>>> values = dishes.values()\\n\\n>>> # iteration\\n>>> n = 0\\n>>> for val in values:\\n... n += val\\n...\\n>>> print(n)\\n504\\n\\n>>> # keys and values are iterated over in the same order (insertion order)\\n>>> list(keys)\\n[\\'eggs\\', \\'sausage\\', \\'bacon\\', \\'spam\\']\\n>>> list(values)\\n[2, 1, 1, 500]\\n\\n>>> # view objects are dynamic and reflect dict changes\\n>>> del dishes[\\'eggs\\']\\n>>> del dishes[\\'sausage\\']\\n>>> list(keys)\\n[\\'bacon\\', \\'spam\\']\\n\\n>>> # set operations\\n>>> keys & {\\'eggs\\', \\'bacon\\', \\'salad\\'}\\n{\\'bacon\\'}\\n>>> keys ^ {\\'sausage\\', \\'juice\\'} == {\\'juice\\', \\'sausage\\', \\'bacon\\', \\'spam\\'}\\nTrue\\n>>> keys | [\\'juice\\', \\'juice\\', \\'juice\\'] == {\\'bacon\\', \\'spam\\', \\'juice\\'}\\nTrue\\n\\n>>> # get back a read-only proxy for the original dictionary\\n>>> values.mapping\\nmappingproxy({\\'bacon\\': 1, \\'spam\\': 500})\\n>>> values.mapping[\\'spam\\']\\n500\\n\\nFrozen dictionaries¶\\n\\nContext Manager Types¶\\n\\nPython’s with statement supports the concept of a runtime context defined by a context manager. This is implemented using a pair of methods that allow user-defined classes to define a runtime context that is entered before the statement body is executed and exited when the statement ends:\\n\\nPython defines several context managers to support easy thread synchronisation, prompt closure of files or other objects, and simpler manipulation of the active decimal arithmetic context. The specific types are not treated specially beyond their implementation of the context management protocol. See the contextlib module for some examples.\\n\\nPython’s generators and the contextlib.contextmanager decorator provide a convenient way to implement these protocols. If a generator function is decorated with the contextlib.contextmanager decorator, it will return a context manager implementing the necessary __enter__() and __exit__() methods, rather than the iterator produced by an undecorated generator function.\\n\\nNote that there is no specific slot for any of these methods in the type structure for Python objects in the Python/C API. Extension types wanting to define these methods must provide them as a normal Python accessible method. Compared to the overhead of setting up the runtime context, the overhead of a single class dictionary lookup is negligible.\\n\\nType Annotation Types — Generic Alias, Union¶\\n\\nThe core built-in types for type annotations are Generic Alias and Union.\\n\\nGeneric Alias Type¶\\n\\nGenericAlias objects are generally created by subscripting a class. They are most often used with container classes, such as list or dict. For example, list[int] is a GenericAlias object created by subscripting the list class with the argument int. GenericAlias objects are intended primarily for use with type annotations.\\n\\nNote\\n\\nIt is generally only possible to subscript a class if the class implements the special method __class_getitem__().\\n\\nA GenericAlias object acts as a proxy for a generic type, implementing parameterized generics.\\n\\nFor a container class, the argument(s) supplied to a subscription of the class may indicate the type(s) of the elements an object contains. For example, set[bytes] can be used in type annotations to signify a set in which all the elements are of type bytes.\\n\\nFor a class which defines __class_getitem__() but is not a container, the argument(s) supplied to a subscription of the class will often indicate the return type(s) of one or more methods defined on an object. For example, regular expressions can be used on both the str data type and the bytes data type:\\n\\nIf x = re.search(\\'foo\\', \\'foo\\'), x will be a re.Match object where the return values of x.group(0) and x[0] will both be of type str. We can represent this kind of object in type annotations with the GenericAlias re.Match[str].\\n\\nIf y = re.search(b\\'bar\\', b\\'bar\\'), (note the b for bytes), y will also be an instance of re.Match, but the return values of y.group(0) and y[0] will both be of type bytes. In type annotations, we would represent this variety of re.Match objects with re.Match[bytes].\\n\\nGenericAlias objects are instances of the class types.GenericAlias, which can also be used to create GenericAlias objects directly.\\n\\nThe builtin functions isinstance() and issubclass() do not accept GenericAlias types for their second argument:\\n\\n>>> isinstance([1, 2], list[str])\\nTraceback (most recent call last):\\n File \"\", line 1, in \\nTypeError: isinstance() argument 2 cannot be a parameterized generic\\n\\nThe Python runtime does not enforce type annotations. This extends to generic types and their type parameters. When creating a container object from a GenericAlias, the elements in the container are not checked against their type. For example, the following code is discouraged, but will run without errors:\\n\\n>>> t = list[str]\\n>>> t([1, 2, 3])\\n[1, 2, 3]\\n\\nFurthermore, parameterized generics erase type parameters during object creation:\\n\\n>>> t = list[str]\\n>>> type(t)\\n\\n\\n>>> l = t()\\n>>> type(l)\\n\\n\\nCalling repr() or str() on a generic shows the parameterized type:\\n\\n>>> repr(list[int])\\n\\'list[int]\\'\\n\\n>>> str(list[int])\\n\\'list[int]\\'\\n\\nThe __getitem__() method of generic containers will raise an exception to disallow mistakes like dict[str][str]:\\n\\n>>> dict[str][str]\\nTraceback (most recent call last):\\n ...\\nTypeError: dict[str] is not a generic class\\n\\nHowever, such expressions are valid when type variables are used. The index must have as many elements as there are type variable items in the GenericAlias object’s __args__.\\n\\n>>> from typing import TypeVar\\n>>> Y = TypeVar(\\'Y\\')\\n>>> dict[str, Y][int]\\ndict[str, int]\\n\\nStandard Generic Classes¶\\n\\nThe following standard library classes support parameterized generics. This list is non-exhaustive.\\n\\ntuple\\n\\nlist\\n\\ndict\\n\\nset\\n\\nfrozendict\\n\\nfrozenset\\n\\ntype\\n\\nasyncio.Future\\n\\nasyncio.Task\\n\\ncollections.deque\\n\\ncollections.defaultdict\\n\\ncollections.OrderedDict\\n\\ncollections.Counter\\n\\ncollections.ChainMap\\n\\ncollections.abc.Awaitable\\n\\ncollections.abc.Coroutine\\n\\ncollections.abc.AsyncIterable\\n\\ncollections.abc.AsyncIterator\\n\\ncollections.abc.AsyncGenerator\\n\\ncollections.abc.Iterable\\n\\ncollections.abc.Iterator\\n\\ncollections.abc.Generator\\n\\ncollections.abc.Reversible\\n\\ncollections.abc.Container\\n\\ncollections.abc.Collection\\n\\ncollections.abc.Callable\\n\\ncollections.abc.Set\\n\\ncollections.abc.MutableSet\\n\\ncollections.abc.Mapping\\n\\ncollections.abc.MutableMapping\\n\\ncollections.abc.Sequence\\n\\ncollections.abc.MutableSequence\\n\\ncollections.abc.ByteString\\n\\ncollections.abc.MappingView\\n\\ncollections.abc.KeysView\\n\\ncollections.abc.ItemsView\\n\\ncollections.abc.ValuesView\\n\\ncontextlib.AbstractContextManager\\n\\ncontextlib.AbstractAsyncContextManager\\n\\ndataclasses.Field\\n\\nfunctools.cached_property\\n\\nfunctools.partialmethod\\n\\nos.PathLike\\n\\nqueue.LifoQueue\\n\\nqueue.Queue\\n\\nqueue.PriorityQueue\\n\\nqueue.SimpleQueue\\n\\nre.Pattern\\n\\nre.Match\\n\\nshelve.BsdDbShelf\\n\\nshelve.DbfilenameShelf\\n\\nshelve.Shelf\\n\\ntypes.MappingProxyType\\n\\nweakref.WeakKeyDictionary\\n\\nweakref.WeakMethod\\n\\nweakref.WeakSet\\n\\nweakref.WeakValueDictionary\\n\\nSpecial Attributes of GenericAlias objects¶\\n\\nAll parameterized generics implement special read-only attributes.\\n\\nSee also\\n\\nAdded in version 3.9.\\n\\nUnion Type¶\\n\\nA union object holds the value of the | (bitwise or) operation on multiple type objects. These types are intended primarily for type annotations. The union type expression enables cleaner type hinting syntax compared to subscripting typing.Union.\\n\\nThe user-exposed type for the union object can be accessed from typing.Union and used for isinstance() checks:\\n\\n>>> import typing\\n>>> isinstance(int | str, typing.Union)\\nTrue\\n>>> typing.Union()\\nTraceback (most recent call last):\\n File \"\", line 1, in \\nTypeError: cannot create \\'typing.Union\\' instances\\n\\nNote\\n\\nThe __or__() method for type objects was added to support the syntax X | Y. If a metaclass implements __or__(), the Union may override it:\\n\\n>>> class M(type):\\n... def __or__(self, other):\\n... return \"Hello\"\\n...\\n>>> class C(metaclass=M):\\n... pass\\n...\\n>>> C | int\\n\\'Hello\\'\\n>>> int | C\\nint | C\\n\\nSee also\\n\\nPEP 604 – PEP proposing the X | Y syntax and the Union type.\\n\\nAdded in version 3.10.\\n\\nChanged in version 3.14: Union objects are now instances of typing.Union. Previously, they were instances of types.UnionType, which remains an alias for typing.Union.\\n\\nOther Built-in Types¶\\n\\nThe interpreter supports several other kinds of objects. Most of these support only one or two operations.\\n\\nModules¶\\n\\nThe only special operation on a module is attribute access: m.name, where m is a module and name accesses a name defined in m’s symbol table. Module attributes can be assigned to. (Note that the import statement is not, strictly speaking, an operation on a module object; import foo does not require a module object named foo to exist, rather it requires an (external) definition for a module named foo somewhere.)\\n\\nA special attribute of every module is __dict__. This is the dictionary containing the module’s symbol table. Modifying this dictionary will actually change the module’s symbol table, but direct assignment to the __dict__ attribute is not possible (you can write m.__dict__[\\'a\\'] = 1, which defines m.a to be 1, but you can’t write m.__dict__ = {}). Modifying __dict__ directly is not recommended.\\n\\nModules built into the interpreter are written like this: . If loaded from a file, they are written as .\\n\\nClasses and Class Instances¶\\n\\nSee Objects, values and types and Class definitions for these.\\n\\nFunctions¶\\n\\nFunction objects are created by function definitions. The only operation on a function object is to call it: func(argument-list).\\n\\nThere are really two flavors of function objects: built-in functions and user-defined functions. Both support the same operation (to call the function), but the implementation is different, hence the different object types.\\n\\nSee Function definitions for more information.\\n\\nMethods¶\\n\\nMethods are functions that are called using the attribute notation. There are two flavors: built-in methods (such as append() on lists) and class instance method. Built-in methods are described with the types that support them.\\n\\nIf you access a method (a function defined in a class namespace) through an instance, you get a special object: a bound method (also called instance method) object. When called, it will add the self argument to the argument list. Bound methods have two special read-only attributes: m.__self__ is the object on which the method operates, and m.__func__ is the function implementing the method. Calling m(arg-1, arg-2, ..., arg-n) is completely equivalent to calling m.__func__(m.__self__, arg-1, arg-2, ..., arg-n).\\n\\nLike function objects, bound method objects support getting arbitrary attributes. However, since method attributes are actually stored on the underlying function object (method.__func__), setting method attributes on bound methods is disallowed. Attempting to set an attribute on a method results in an AttributeError being raised. In order to set a method attribute, you need to explicitly set it on the underlying function object:\\n\\n>>> class C:\\n... def method(self):\\n... pass\\n...\\n>>> c = C()\\n>>> c.method.whoami = \\'my name is method\\' # can\\'t set on the method\\nTraceback (most recent call last):\\n File \"\", line 1, in \\nAttributeError: \\'method\\' object has no attribute \\'whoami\\'\\n>>> c.method.__func__.whoami = \\'my name is method\\'\\n>>> c.method.whoami\\n\\'my name is method\\'\\n\\nSee Instance methods for more information.\\n\\nCode Objects¶\\n\\nCode objects are used by the implementation to represent “pseudo-compiled” executable Python code such as a function body. They differ from function objects because they don’t contain a reference to their global execution environment. Code objects are returned by the built-in compile() function and can be extracted from function objects through their __code__ attribute. See also the code module.\\n\\nAccessing __code__ raises an auditing event object.__getattr__ with arguments obj and \"__code__\".\\n\\nA code object can be executed or evaluated by passing it (instead of a source string) to the exec() or eval() built-in functions.\\n\\nSee The standard type hierarchy for more information.\\n\\nType Objects¶\\n\\nType objects represent the various object types. An object’s type is accessed by the built-in function type(). There are no special operations on types. The standard module types defines names for all standard built-in types.\\n\\nTypes are written like this: .\\n\\nThe Null Object¶\\n\\nThis object is returned by functions that don’t explicitly return a value. It supports no special operations. There is exactly one null object, named None (a built-in name). type(None)() produces the same singleton.\\n\\nIt is written as None.\\n\\nThe Ellipsis Object¶\\n\\nThis object is commonly used to indicate that something is omitted. It supports no special operations. There is exactly one ellipsis object, named Ellipsis (a built-in name). type(Ellipsis)() produces the Ellipsis singleton.\\n\\nIt is written as Ellipsis or ....\\n\\nIn typical use, ... as the Ellipsis object appears in a few different places, for instance:\\n\\nIn type annotations, such as callable arguments or tuple elements.\\n\\nAs the body of a function instead of a pass statement.\\n\\nIn third-party libraries, such as Numpy’s slicing and striding.\\n\\nPython also uses three dots in ways that are not Ellipsis objects, for instance:\\n\\nDoctest’s ELLIPSIS, as a pattern for missing content.\\n\\nThe default Python prompt of the interactive shell when partial input is incomplete.\\n\\nLastly, 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 Ellipsis.\\n\\nThe NotImplemented Object¶\\n\\nThis object is returned from comparisons and binary operations when they are asked to operate on types they don’t support. See Comparisons for more information. There is exactly one NotImplemented object. type(NotImplemented)() produces the singleton instance.\\n\\nIt is written as NotImplemented.\\n\\nInternal Objects¶\\n\\nSee The standard type hierarchy for this information. It describes stack frame objects, traceback objects, and slice objects.\\n\\nSpecial Attributes¶\\n\\nThe implementation adds a few special read-only attributes to several object types, where they are relevant. Some of these are not reported by the dir() built-in function.\\n\\nInteger string conversion length limitation¶\\n\\nCPython has a global limit for converting between int and str to mitigate denial of service attacks. This limit only applies to decimal or other non-power-of-two number bases. Hexadecimal, octal, and binary conversions are unlimited. The limit can be configured.\\n\\nThe int type in CPython is an arbitrary length number stored in binary form (commonly known as a “bignum”). There exists no algorithm that can convert a string to a binary integer or a binary integer to a string in linear time, unless the base is a power of 2. Even the best known algorithms for base 10 have sub-quadratic complexity. Converting a large value such as int(\\'1\\' * 500_000) can take over a second on a fast CPU.\\n\\nLimiting conversion size offers a practical way to avoid CVE 2020-10735.\\n\\nThe limit is applied to the number of digit characters in the input or output string when a non-linear conversion algorithm would be involved. Underscores and the sign are not counted towards the limit.\\n\\nWhen an operation would exceed the limit, a ValueError is raised:\\n\\n>>> import sys\\n>>> sys.set_int_max_str_digits(4300) # Illustrative, this is the default.\\n>>> _ = int(\\'2\\' * 5432)\\nTraceback (most recent call last):\\n...\\nValueError: Exceeds the limit (4300 digits) for integer string conversion: value has 5432 digits; use sys.set_int_max_str_digits() to increase the limit\\n>>> i = int(\\'2\\' * 4300)\\n>>> len(str(i))\\n4300\\n>>> i_squared = i*i\\n>>> len(str(i_squared))\\nTraceback (most recent call last):\\n...\\nValueError: Exceeds the limit (4300 digits) for integer string conversion; use sys.set_int_max_str_digits() to increase the limit\\n>>> len(hex(i_squared))\\n7144\\n>>> assert int(hex(i_squared), base=16) == i*i # Hexadecimal is unlimited.\\n\\nThe default limit is 4300 digits as provided in sys.int_info.default_max_str_digits. The lowest limit that can be configured is 640 digits as provided in sys.int_info.str_digits_check_threshold.\\n\\nVerification:\\n\\n>>> import sys\\n>>> assert sys.int_info.default_max_str_digits == 4300, sys.int_info\\n>>> assert sys.int_info.str_digits_check_threshold == 640, sys.int_info\\n>>> msg = int(\\'578966293710682886880994035146873798396722250538762761564\\'\\n... \\'9252925514383915483333812743580549779436104706260696366600\\'\\n... \\'571186405732\\').to_bytes(53, \\'big\\')\\n...\\n\\nAdded in version 3.11.\\n\\nAffected APIs¶\\n\\nThe limitation only applies to potentially slow conversions between int and str or bytes:\\n\\nint(string) with default base 10.\\n\\nint(string, base) for all bases that are not a power of 2.\\n\\nstr(integer).\\n\\nrepr(integer).\\n\\nany other string conversion to base 10, for example f\"{integer}\", \"{}\".format(integer), or b\"%d\" % integer.\\n\\nThe limitations do not apply to functions with a linear algorithm:\\n\\nint(string, base) with base 2, 4, 8, 16, or 32.\\n\\nint.from_bytes() and int.to_bytes().\\n\\nhex(), oct(), bin().\\n\\nFormat Specification Mini-Language for hex, octal, and binary numbers.\\n\\nstr to float.\\n\\nstr to decimal.Decimal.\\n\\nConfiguring the limit¶\\n\\nBefore Python starts up you can use an environment variable or an interpreter command line flag to configure the limit:\\n\\nPYTHONINTMAXSTRDIGITS, e.g. PYTHONINTMAXSTRDIGITS=640 python3 to set the limit to 640 or PYTHONINTMAXSTRDIGITS=0 python3 to disable the limitation.\\n\\nX int_max_str_digits, e.g. python3 -X int_max_str_digits=640\\n\\nsys.flags.int_max_str_digits contains the value of PYTHONINTMAXSTRDIGITS or -X int_max_str_digits. If both the env var and the -X option are set, the -X option takes precedence. A value of -1 indicates that both were unset, thus a value of sys.int_info.default_max_str_digits was used during initialization.\\n\\nFrom code, you can inspect the current limit and set a new one using these sys APIs:\\n\\nsys.get_int_max_str_digits() and sys.set_int_max_str_digits() are a getter and setter for the interpreter-wide limit. Subinterpreters have their own limit.\\n\\nInformation about the default and minimum can be found in sys.int_info:\\n\\nsys.int_info.default_max_str_digits is the compiled-in default limit.\\n\\nsys.int_info.str_digits_check_threshold is the lowest accepted value for the limit (other than 0 which disables it).\\n\\nAdded in version 3.11.\\n\\nCaution\\n\\nSetting a low limit can lead to problems. While rare, code exists that contains integer constants in decimal in their source that exceed the minimum threshold. A consequence of setting the limit is that Python source code containing decimal integer literals longer than the limit will encounter an error during parsing, usually at startup time or import time or even at installation time - anytime an up to date .pyc does not already exist for the code. A workaround for source that contains such large constants is to convert them to 0x hexadecimal form as it has no limit.\\n\\nTest your application thoroughly if you use a low limit. Ensure your tests run with the limit set early via the environment or flag so that it applies during startup and even during any installation step that may invoke Python to precompile .py sources to .pyc files.\\n\\nRecommended configuration¶\\n\\nThe default sys.int_info.default_max_str_digits is expected to be reasonable for most applications. If your application requires a different limit, set it from your main entry point using Python version agnostic code as these APIs were added in security patch releases in versions before 3.12.\\n\\nExample:\\n\\n>>> import sys\\n>>> if hasattr(sys, \"set_int_max_str_digits\"):\\n... upper_bound = 68000\\n... lower_bound = 4004\\n... current_limit = sys.get_int_max_str_digits()\\n... if current_limit == 0 or current_limit > upper_bound:\\n... sys.set_int_max_str_digits(upper_bound)\\n... elif current_limit < lower_bound:\\n... sys.set_int_max_str_digits(lower_bound)\\n\\nIf you need to disable it entirely, set it to 0.\\n\\nFootnotes\\n\\n[1]\\n\\nAdditional information on these special methods may be found in the Python Reference Manual (Basic customization).\\n\\n[2]\\n\\nAs a consequence, the list [1, 2] is considered equal to [1.0, 2.0], and similarly for tuples.\\n\\n[3]\\n\\nThey must have since the parser can’t tell the type of the operands.\\n\\n[4] (1,2,3,4)\\n\\nCased characters are those with general category property being one of “Lu” (Letter, uppercase), “Ll” (Letter, lowercase), or “Lt” (Letter, titlecase).\\n\\n[5] (1,2)\\n\\nTo format only a tuple you should therefore provide a singleton tuple whose only element is the tuple to be formatted.\\n\\nTable of Contents\\n\\nBuilt-in Types\\n\\nTruth Value Testing\\n\\nBoolean Operations — and, or, not\\n\\nComparisons\\n\\nNumeric Types — int, float, complex\\n\\nBitwise Operations on Integer Types\\n\\nAdditional Methods on Integer Types\\n\\nAdditional Methods on Float\\n\\nAdditional Methods on Complex\\n\\nHashing of numeric types\\n\\nBoolean Type - bool\\n\\nIterator Types\\n\\nGenerator Types\\n\\nSequence Types — list, tuple, range\\n\\nCommon Sequence Operations\\n\\nImmutable Sequence Types\\n\\nMutable Sequence Types\\n\\nLists\\n\\nTuples\\n\\nRanges\\n\\nText and Binary Sequence Type Methods Summary\\n\\nText Sequence Type — str\\n\\nString Methods\\n\\nFormatted String Literals (f-strings)\\n\\nDebug specifier\\n\\nConversion specifier\\n\\nFormat specifier\\n\\nTemplate String Literals (t-strings)\\n\\nprintf-style String Formatting\\n\\nBinary Sequence Types — bytes, bytearray, memoryview\\n\\nBytes Objects\\n\\nBytearray Objects\\n\\nBytes and Bytearray Operations\\n\\nprintf-style Bytes Formatting\\n\\nMemory Views\\n\\nSet Types — set, frozenset\\n\\nMapping types — dict, frozendict\\n\\nDictionary view objects\\n\\nFrozen dictionaries\\n\\nContext Manager Types\\n\\nType Annotation Types — Generic Alias, Union\\n\\nGeneric Alias Type\\n\\nStandard Generic Classes\\n\\nSpecial Attributes of GenericAlias objects\\n\\nUnion Type\\n\\nOther Built-in Types\\n\\nModules\\n\\nClasses and Class Instances\\n\\nFunctions\\n\\nMethods\\n\\nCode Objects\\n\\nType Objects\\n\\nThe Null Object\\n\\nThe Ellipsis Object\\n\\nThe NotImplemented Object\\n\\nInternal Objects\\n\\nSpecial Attributes\\n\\nInteger string conversion length limitation\\n\\nAffected APIs\\n\\nConfiguring the limit\\n\\nRecommended configuration\\n\\nPrevious topic\\n\\nBuilt-in Constants\\n\\nNext topic\\n\\nBuilt-in Exceptions\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nBuilt-in Types\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\string.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nText Processing Services »\\n\\nstring — Common string operations\\n\\n|\\n\\nstring — Common string operations¶\\n\\nSource code: Lib/string/__init__.py\\n\\nSee also\\n\\nText Sequence Type — str\\n\\nString Methods\\n\\nString constants¶\\n\\nThe constants defined in this module are:\\n\\nCustom String Formatting¶\\n\\nThe built-in string class provides the ability to do complex variable substitutions and value formatting via the format() method described in PEP 3101. The Formatter class in the string module allows you to create and customize your own string formatting behaviors using the same implementation as the built-in format() method.\\n\\nFormat String Syntax¶\\n\\nThe str.format() method and the Formatter class share the same syntax for format strings (although in the case of Formatter, subclasses can define their own format string syntax). The syntax is related to that of formatted string literals and template string literals, but it is less sophisticated and, in particular, does not support arbitrary expressions in interpolations.\\n\\nFormat strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.\\n\\nThe grammar for a replacement field is as follows:\\n\\nreplacement_field: \"{\" [field_name] [\"!\" conversion] [\":\" format_spec] \"}\"\\nfield_name: arg_name (\".\" attribute_name | \"[\" element_index \"]\")*\\narg_name: [identifier | digit+]\\nattribute_name: identifier\\nelement_index: digit+ | index_string\\nindex_string: +\\nconversion: \"r\" | \"s\" | \"a\"\\nformat_spec: format-spec:format_spec\\n\\nIn less formal terms, the replacement field can start with a field_name that specifies the object whose value is to be formatted and inserted into the output instead of the replacement field. The field_name is optionally followed by a conversion field, which is preceded by an exclamation point \\'!\\', and a format_spec, which is preceded by a colon \\':\\'. These specify a non-default format for the replacement value.\\n\\nSee also the Format Specification Mini-Language section.\\n\\nThe field_name itself begins with an arg_name that is either a number or a keyword. If it’s a number, it refers to a positional argument, and if it’s a keyword, it refers to a named keyword argument. An arg_name is treated as a number if a call to str.isdecimal() on the string would return true. If the numerical arg_names in a format string are 0, 1, 2, … in sequence, they can all be omitted (not just some) and the numbers 0, 1, 2, … will be automatically inserted in that order. Because arg_name is not quote-delimited, it is not possible to specify arbitrary dictionary keys (e.g., the strings \\'10\\' or \\':-]\\') within a format string. The arg_name can be followed by any number of index or attribute expressions. An expression of the form \\'.name\\' selects the named attribute using getattr(), while an expression of the form \\'[index]\\' does an index lookup using __getitem__().\\n\\nChanged in version 3.1: The positional argument specifiers can be omitted for str.format(), so \\'{} {}\\'.format(a, b) is equivalent to \\'{0} {1}\\'.format(a, b).\\n\\nChanged in version 3.4: The positional argument specifiers can be omitted for Formatter.\\n\\nSome simple format string examples:\\n\\n\"First, thou shalt count to {0}\" # References first positional argument\\n\"Bring me a {}\" # Implicitly references the first positional argument\\n\"From {} to {}\" # Same as \"From {0} to {1}\"\\n\"My quest is {name}\" # References keyword argument \\'name\\'\\n\"Weight in tons {0.weight}\" # \\'weight\\' attribute of first positional arg\\n\"Units destroyed: {players[0]}\" # First element of keyword argument \\'players\\'.\\n\\nThe conversion field causes a type coercion before formatting. Normally, the job of formatting a value is done by the __format__() method of the value itself. However, in some cases it is desirable to force a type to be formatted as a string, overriding its own definition of formatting. By converting the value to a string before calling __format__(), the normal formatting logic is bypassed.\\n\\nThree conversion flags are currently supported: \\'!s\\' which calls str() on the value, \\'!r\\' which calls repr() and \\'!a\\' which calls ascii().\\n\\nSome examples:\\n\\n\"Harold\\'s a clever {0!s}\" # Calls str() on the argument first\\n\"Bring out the holy {name!r}\" # Calls repr() on the argument first\\n\"More {!a}\" # Calls ascii() on the argument first\\n\\nThe format_spec field contains a specification of how the value should be presented, including such details as field width, alignment, padding, decimal precision and so on. Each value type can define its own “formatting mini-language” or interpretation of the format_spec.\\n\\nMost built-in types support a common formatting mini-language, which is described in the next section.\\n\\nA format_spec field can also include nested replacement fields within it. These nested replacement fields may contain a field name, conversion flag and format specification, but deeper nesting is not allowed. The replacement fields within the format_spec are substituted before the format_spec string is interpreted. This allows the formatting of a value to be dynamically specified.\\n\\nSee the Format examples section for some examples.\\n\\nFormat Specification Mini-Language¶\\n\\n“Format specifications” are used within replacement fields contained within a format string to define how individual values are presented (see Format String Syntax, f-strings, and t-strings). They can also be passed directly to the built-in format() function. Each formattable type may define how the format specification is to be interpreted.\\n\\nMost built-in types implement the following options for format specifications, although some of the formatting options are only supported by the numeric types.\\n\\nA general convention is that an empty format specification produces the same result as if you had called str() on the value. A non-empty format specification typically modifies the result.\\n\\nThe general form of a standard format specifier is:\\n\\nformat_spec: [options][width_and_precision][type]\\noptions: [[fill]align][sign][\"z\"][\"#\"][\"0\"]\\nfill: \\nalign: \"<\" | \">\" | \"=\" | \"^\"\\nsign: \"+\" | \"-\" | \" \"\\nwidth_and_precision: [width_with_grouping][precision_with_grouping]\\nwidth_with_grouping: [width][grouping]\\nprecision_with_grouping: \".\" [precision][grouping] | \".\" grouping\\nwidth: digit+\\nprecision: digit+\\ngrouping: \",\" | \"_\"\\ntype: \"b\" | \"c\" | \"d\" | \"e\" | \"E\" | \"f\" | \"F\" | \"g\"\\n | \"G\" | \"n\" | \"o\" | \"s\" | \"x\" | \"X\" | \"%\"\\n\\nIf a valid align value is specified, it can be preceded by a fill character that can be any character and defaults to a space if omitted. It is not possible to use a literal curly brace (”{” or “}”) as the fill character in a formatted string literal or when using the str.format() method. However, it is possible to insert a curly brace with a nested replacement field. This limitation doesn’t affect the format() function.\\n\\nThe meaning of the various alignment options is as follows:\\n\\nOption Meaning \\'<\\' Forces the field to be left-aligned within the available\\nspace (this is the default for most objects). \\'>\\' Forces the field to be right-aligned within the\\navailable space (this is the default for numbers). \\'=\\' Forces the padding to be placed after the sign (if any)\\nbut before the digits. This is used for printing fields\\nin the form ‘+000000120’. This alignment option is only\\nvalid for numeric types, excluding complex .\\nIt becomes the default for numbers when ‘0’ immediately\\nprecedes the field width. \\'^\\' Forces the field to be centered within the available\\nspace.\\n\\nNote that unless a minimum field width is defined, the field width will always be the same size as the data to fill it, so that the alignment option has no meaning in this case.\\n\\nThe sign option is only valid for number types, and can be one of the following:\\n\\nOption Meaning \\'+\\' Indicates that a sign should be used for both\\npositive as well as negative numbers. \\'-\\' Indicates that a sign should be used only for negative\\nnumbers (this is the default behavior). space Indicates that a leading space should be used on\\npositive numbers, and a minus sign on negative numbers.\\n\\nThe \\'z\\' option coerces negative zero floating-point values to positive zero after rounding to the format precision. This option is only valid for floating-point presentation types.\\n\\nChanged in version 3.11: Added the \\'z\\' option (see also PEP 682).\\n\\nThe \\'#\\' option causes the “alternate form” to be used for the conversion. The alternate form is defined differently for different types. This option is only valid for integer, float and complex types. For integers, when binary, octal, or hexadecimal output is used, this option adds the respective prefix \\'0b\\', \\'0o\\', \\'0x\\', or \\'0X\\' to the output value. For float and complex the alternate form causes the result of the conversion to always contain a decimal-point character, even if no digits follow it. Normally, a decimal-point character appears in the result of these conversions only if a digit follows it. In addition, for \\'g\\' and \\'G\\' conversions, trailing zeros are not removed from the result.\\n\\nThe 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.\\n\\nWhen no explicit alignment is given, preceding the width field by a zero (\\'0\\') character enables sign-aware zero-padding for numeric types, excluding complex. This is equivalent to a fill character of \\'0\\' with an alignment type of \\'=\\'.\\n\\nChanged in version 3.10: Preceding the width field by \\'0\\' no longer affects the default alignment for strings.\\n\\nThe precision is a decimal integer indicating how many digits should be displayed after the decimal point for presentation types \\'f\\' and \\'F\\', or before and after the decimal point for presentation types \\'g\\' or \\'G\\'. For string presentation types the field indicates the maximum field size - in other words, how many characters will be used from the field content. The precision is not allowed for integer presentation types.\\n\\nThe 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:\\n\\nOption Meaning \\',\\' Inserts a comma every 3 digits for\\ninteger presentation type \\'d\\' and\\nfloating-point presentation types, excluding \\'n\\' .\\nFor other presentation types,\\nthis option is not supported. \\'_\\' Inserts an underscore every 3 digits for\\ninteger presentation type \\'d\\' and\\nfloating-point presentation types, excluding \\'n\\' .\\nFor integer presentation types \\'b\\' , \\'o\\' , \\'x\\' , and \\'X\\' ,\\nunderscores are inserted every 4 digits.\\nFor other presentation types,\\nthis option is not supported.\\n\\nFor a locale aware separator, use the \\'n\\' presentation type instead.\\n\\nChanged in version 3.1: Added the \\',\\' option (see also PEP 378).\\n\\nChanged in version 3.6: Added the \\'_\\' option (see also PEP 515).\\n\\nChanged in version 3.14: Support the grouping option for the fractional part.\\n\\nFinally, the type determines how the data should be presented.\\n\\nThe available string presentation types are:\\n\\nType Meaning \\'s\\' String format. This is the default type for strings and\\nmay be omitted. None The same as \\'s\\' .\\n\\nThe available integer presentation types are:\\n\\nType Meaning \\'b\\' Binary format. Outputs the number in base 2. \\'c\\' Character. Converts the integer to the corresponding\\nunicode character before printing. \\'d\\' Decimal Integer. Outputs the number in base 10. \\'o\\' Octal format. Outputs the number in base 8. \\'x\\' Hex format. Outputs the number in base 16, using\\nlower-case letters for the digits above 9. \\'X\\' Hex format. Outputs the number in base 16, using\\nupper-case letters for the digits above 9.\\nIn case \\'#\\' is specified, the prefix \\'0x\\' will\\nbe upper-cased to \\'0X\\' as well. \\'n\\' Number. This is the same as \\'d\\' , except that it uses\\nthe current locale setting to insert the appropriate\\ndigit group separators. None The same as \\'d\\' .\\n\\nIn addition to the above presentation types, integers can be formatted with the floating-point presentation types listed below (except \\'n\\' and None). When doing so, float() is used to convert the integer to a floating-point number before formatting.\\n\\nThe available presentation types for float and Decimal values are:\\n\\nType Meaning \\'e\\' Scientific notation. For a given precision p ,\\nformats the number in scientific notation with the\\nletter ‘e’ separating the coefficient from the exponent.\\nThe coefficient has one digit before and p digits\\nafter the decimal point, for a total of p + 1 significant digits. With no precision given, uses a\\nprecision of 6 digits after the decimal point for float , and shows all coefficient digits\\nfor Decimal . If p=0 , the decimal\\npoint is omitted unless the # option is used. For float , the exponent always contains at\\nleast two digits, and is zero if the value is zero. \\'E\\' Scientific notation. Same as \\'e\\' except it uses\\nan upper case ‘E’ as the separator character. \\'f\\' Fixed-point notation. For a given precision p ,\\nformats the number as a decimal number with exactly p digits following the decimal point. With no\\nprecision given, uses a precision of 6 digits after\\nthe decimal point for float , and uses a\\nprecision large enough to show all coefficient digits\\nfor Decimal . If p=0 , the decimal\\npoint is omitted unless the # option is used. \\'F\\' Fixed-point notation. Same as \\'f\\' , but converts nan to NAN and inf to INF . \\'g\\' General format. For a given precision p >= 1 ,\\nthis rounds the number to p significant digits and\\nthen formats the result in either fixed-point format\\nor in scientific notation, depending on its magnitude.\\nA precision of 0 is treated as equivalent to a\\nprecision of 1 . The precise rules are as follows: suppose that the\\nresult formatted with presentation type \\'e\\' and\\nprecision p-1 would have exponent exp . Then,\\nif m <= exp < p , where m is -4 for floats and -6\\nfor Decimals , the number is\\nformatted with presentation type \\'f\\' and precision p-1-exp . Otherwise, the number is formatted\\nwith presentation type \\'e\\' and precision p-1 .\\nIn both cases insignificant trailing zeros are removed\\nfrom the significand, and the decimal point is also\\nremoved if there are no remaining digits following it,\\nunless the \\'#\\' option is used. With no precision given, uses a precision of 6 significant digits for float . For Decimal , the coefficient of the result\\nis formed from the coefficient digits of the value;\\nscientific notation is used for values smaller than 1e-6 in absolute value and values where the place\\nvalue of the least significant digit is larger than 1,\\nand fixed-point notation is used otherwise. Positive and negative infinity, positive and negative\\nzero, and nans, are formatted as inf , -inf , 0 , -0 and nan respectively, regardless of\\nthe precision. \\'G\\' General format. Same as \\'g\\' except switches to \\'E\\' if the number gets too large. The\\nrepresentations of infinity and NaN are uppercased, too. \\'n\\' Number. This is the same as \\'g\\' , except that it uses\\nthe current locale setting to insert the appropriate\\ndigit group separators\\nfor the integral part of a number. \\'%\\' Percentage. Multiplies the number by 100 and displays\\nin fixed ( \\'f\\' ) format, followed by a percent sign. None For float this is like the \\'g\\' type, except\\nthat when fixed-point notation is used to format the\\nresult, it always includes at least one digit past the\\ndecimal point, and switches to the scientific notation\\nwhen exp >= p - 1 . When the precision is not\\nspecified, the latter will be as large as needed to\\nrepresent the given value faithfully. For Decimal , this is the same as\\neither \\'g\\' or \\'G\\' depending on the value of context.capitals for the current decimal context. The overall effect is to match the output of str() as altered by the other format modifiers.\\n\\nThe result should be correctly rounded to a given precision p of digits after the decimal point. The rounding mode for float matches that of the round() builtin. For Decimal, the rounding mode of the current context will be used.\\n\\nThe available presentation types for complex are the same as those for float (\\'%\\' 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 j suffix. If the presentation type is missing, the result will match the output of str() (complex numbers with a non-zero real part are also surrounded by parentheses), possibly altered by other format modifiers.\\n\\nFormat examples¶\\n\\nThis section contains examples of the str.format() syntax and comparison with the old %-formatting.\\n\\nIn most of the cases the syntax is similar to the old %-formatting, with the addition of the {} and with : used instead of %. For example, \\'%03.2f\\' can be translated to \\'{:03.2f}\\'.\\n\\nThe new format syntax also supports new and different options, shown in the following examples.\\n\\nAccessing arguments by position:\\n\\n>>> \\'{0}, {1}, {2}\\'.format(\\'a\\', \\'b\\', \\'c\\')\\n\\'a, b, c\\'\\n>>> \\'{}, {}, {}\\'.format(\\'a\\', \\'b\\', \\'c\\') # 3.1+ only\\n\\'a, b, c\\'\\n>>> \\'{2}, {1}, {0}\\'.format(\\'a\\', \\'b\\', \\'c\\')\\n\\'c, b, a\\'\\n>>> \\'{2}, {1}, {0}\\'.format(*\\'abc\\') # unpacking argument sequence\\n\\'c, b, a\\'\\n>>> \\'{0}{1}{0}\\'.format(\\'abra\\', \\'cad\\') # arguments\\' indices can be repeated\\n\\'abracadabra\\'\\n\\nAccessing arguments by name:\\n\\n>>> \\'Coordinates: {latitude}, {longitude}\\'.format(latitude=\\'37.24N\\', longitude=\\'-115.81W\\')\\n\\'Coordinates: 37.24N, -115.81W\\'\\n>>> coord = {\\'latitude\\': \\'37.24N\\', \\'longitude\\': \\'-115.81W\\'}\\n>>> \\'Coordinates: {latitude}, {longitude}\\'.format(**coord)\\n\\'Coordinates: 37.24N, -115.81W\\'\\n\\nAccessing arguments’ attributes:\\n\\n>>> c = 3-5j\\n>>> (\\'The complex number {0} is formed from the real part {0.real} \\'\\n... \\'and the imaginary part {0.imag}.\\').format(c)\\n\\'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.\\'\\n>>> class Point:\\n... def __init__(self, x, y):\\n... self.x, self.y = x, y\\n... def __str__(self):\\n... return \\'Point({self.x}, {self.y})\\'.format(self=self)\\n...\\n>>> str(Point(4, 2))\\n\\'Point(4, 2)\\'\\n\\nAccessing arguments’ items:\\n\\n>>> coord = (3, 5)\\n>>> \\'X: {0[0]}; Y: {0[1]}\\'.format(coord)\\n\\'X: 3; Y: 5\\'\\n\\nReplacing %s and %r:\\n\\n>>> \"repr() shows quotes: {!r}; str() doesn\\'t: {!s}\".format(\\'test1\\', \\'test2\\')\\n\"repr() shows quotes: \\'test1\\'; str() doesn\\'t: test2\"\\n\\nAligning the text and specifying a width:\\n\\n>>> \\'{:<30}\\'.format(\\'left aligned\\')\\n\\'left aligned \\'\\n>>> \\'{:>30}\\'.format(\\'right aligned\\')\\n\\' right aligned\\'\\n>>> \\'{:^30}\\'.format(\\'centered\\')\\n\\' centered \\'\\n>>> \\'{:*^30}\\'.format(\\'centered\\') # use \\'*\\' as a fill char\\n\\'***********centered***********\\'\\n\\nReplacing %+f, %-f, and % f and specifying a sign:\\n\\n>>> \\'{:+f}; {:+f}\\'.format(3.14, -3.14) # show it always\\n\\'+3.140000; -3.140000\\'\\n>>> \\'{: f}; {: f}\\'.format(3.14, -3.14) # show a space for positive numbers\\n\\' 3.140000; -3.140000\\'\\n>>> \\'{:-f}; {:-f}\\'.format(3.14, -3.14) # show only the minus -- same as \\'{:f}; {:f}\\'\\n\\'3.140000; -3.140000\\'\\n\\nReplacing %x and %o and converting the value to different bases:\\n\\n>>> # format also supports binary numbers\\n>>> \"int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}\".format(42)\\n\\'int: 42; hex: 2a; oct: 52; bin: 101010\\'\\n>>> # with 0x, 0o, or 0b as prefix:\\n>>> \"int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}\".format(42)\\n\\'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010\\'\\n\\nUsing the comma or the underscore as a digit group separator:\\n\\n>>> \\'{:,}\\'.format(1234567890)\\n\\'1,234,567,890\\'\\n>>> \\'{:_}\\'.format(1234567890)\\n\\'1_234_567_890\\'\\n>>> \\'{:_b}\\'.format(1234567890)\\n\\'100_1001_1001_0110_0000_0010_1101_0010\\'\\n>>> \\'{:_x}\\'.format(1234567890)\\n\\'4996_02d2\\'\\n>>> \\'{:_}\\'.format(123456789.123456789)\\n\\'123_456_789.12345679\\'\\n>>> \\'{:.,}\\'.format(123456789.123456789)\\n\\'123456789.123,456,79\\'\\n>>> \\'{:,._}\\'.format(123456789.123456789)\\n\\'123,456,789.123_456_79\\'\\n\\nExpressing a percentage:\\n\\n>>> points = 19\\n>>> total = 22\\n>>> \\'Correct answers: {:.2%}\\'.format(points/total)\\n\\'Correct answers: 86.36%\\'\\n\\nUsing type-specific formatting:\\n\\n>>> import datetime\\n>>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)\\n>>> \\'{:%Y-%m-%d %H:%M:%S}\\'.format(d)\\n\\'2010-07-04 12:15:58\\'\\n\\nNesting arguments and more complex examples:\\n\\n>>> for align, text in zip(\\'<^>\\', [\\'left\\', \\'center\\', \\'right\\']):\\n... \\'{0:{fill}{align}16}\\'.format(text, fill=align, align=align)\\n...\\n\\'left<<<<<<<<<<<<\\'\\n\\'^^^^^center^^^^^\\'\\n\\'>>>>>>>>>>>right\\'\\n>>>\\n>>> octets = [192, 168, 0, 1]\\n>>> \\'{:02X}{:02X}{:02X}{:02X}\\'.format(*octets)\\n\\'C0A80001\\'\\n>>> int(_, 16)\\n3232235521\\n>>>\\n>>> width = 5\\n>>> for num in range(5,12):\\n... for base in \\'dXob\\':\\n... print(\\'{0:{width}{base}}\\'.format(num, base=base, width=width), end=\\' \\')\\n... print()\\n...\\n 5 5 5 101\\n 6 6 6 110\\n 7 7 7 111\\n 8 8 10 1000\\n 9 9 11 1001\\n 10 A 12 1010\\n 11 B 13 1011\\n\\nTemplate strings ($-strings)¶\\n\\nNote\\n\\nThe feature described here was introduced in Python 2.4; a simple templating method based upon regular expressions. It predates str.format(), formatted string literals, and template string literals.\\n\\nIt is unrelated to template string literals (t-strings), which were introduced in Python 3.14. These evaluate to string.templatelib.Template objects, found in the string.templatelib module.\\n\\nTemplate strings provide simpler string substitutions as described in PEP 292. A primary use case for template strings is for internationalization (i18n) since in that context, the simpler syntax and functionality makes it easier to translate than other built-in string formatting facilities in Python. As an example of a library built on template strings for i18n, see the flufl.i18n package.\\n\\nTemplate strings support $-based substitutions, using the following rules:\\n\\n$$ is an escape; it is replaced with a single $.\\n\\n$identifier names a substitution placeholder matching a mapping key of \"identifier\". By default, \"identifier\" is restricted to any case-insensitive ASCII alphanumeric string (including underscores) that starts with an underscore or ASCII letter. The first non-identifier character after the $ character terminates this placeholder specification.\\n\\n${identifier} is equivalent to $identifier. It is required when valid identifier characters follow the placeholder but are not part of the placeholder, such as \"${noun}ification\".\\n\\nAny other appearance of $ in the string will result in a ValueError being raised.\\n\\nThe string module provides a Template class that implements these rules. The methods of Template are:\\n\\nHere is an example of how to use a Template:\\n\\n>>> from string import Template\\n>>> s = Template(\\'$who likes $what\\')\\n>>> s.substitute(who=\\'tim\\', what=\\'kung pao\\')\\n\\'tim likes kung pao\\'\\n>>> d = dict(who=\\'tim\\')\\n>>> Template(\\'Give $who $100\\').substitute(d)\\nTraceback (most recent call last):\\n...\\nValueError: Invalid placeholder in string: line 1, col 11\\n>>> Template(\\'$who likes $what\\').substitute(d)\\nTraceback (most recent call last):\\n...\\nKeyError: \\'what\\'\\n>>> Template(\\'$who likes $what\\').safe_substitute(d)\\n\\'tim likes $what\\'\\n\\nAdvanced usage: you can derive subclasses of Template to customize the placeholder syntax, delimiter character, or the entire regular expression used to parse template strings. To do this, you can override these class attributes:\\n\\ndelimiter – This is the literal string describing a placeholder introducing delimiter. The default value is $. Note that this should not be a regular expression, as the implementation will call re.escape() on this string as needed. Note further that you cannot change the delimiter after class creation (i.e. a different delimiter must be set in the subclass’s class namespace).\\n\\nidpattern – This is the regular expression describing the pattern for non-braced placeholders. The default value is the regular expression (?a:[_a-z][_a-z0-9]*). If this is given and braceidpattern is None this pattern will also apply to braced placeholders.\\n\\nNote\\n\\nSince default flags is re.IGNORECASE, pattern [a-z] can match with some non-ASCII characters. That’s why we use the local a flag here.\\n\\nChanged in version 3.7: braceidpattern can be used to define separate patterns used inside and outside the braces.\\n\\nbraceidpattern – This is like idpattern but describes the pattern for braced placeholders. Defaults to None which means to fall back to idpattern (i.e. the same pattern is used both inside and outside braces). If given, this allows you to define different patterns for braced and unbraced placeholders.\\n\\nAdded in version 3.7.\\n\\nflags – The regular expression flags that will be applied when compiling the regular expression used for recognizing substitutions. The default value is re.IGNORECASE. Note that re.VERBOSE will always be added to the flags, so custom idpatterns must follow conventions for verbose regular expressions.\\n\\nAdded in version 3.2.\\n\\nAlternatively, you can provide the entire regular expression pattern by overriding the class attribute pattern. If you do this, the value must be a regular expression object with four named capturing groups. The capturing groups correspond to the rules given above, along with the invalid placeholder rule:\\n\\nescaped – This group matches the escape sequence, e.g. $$, in the default pattern.\\n\\nnamed – This group matches the unbraced placeholder name; it should not include the delimiter in capturing group.\\n\\nbraced – This group matches the brace enclosed placeholder name; it should not include either the delimiter or braces in the capturing group.\\n\\ninvalid – This group matches any other delimiter pattern (usually a single delimiter), and it should appear last in the regular expression.\\n\\nThe methods on this class will raise ValueError if the pattern matches the template without one of these named groups matching.\\n\\nHelper functions¶\\n\\nTable of Contents\\n\\nstring — Common string operations\\n\\nString constants\\n\\nCustom String Formatting\\n\\nFormat String Syntax\\n\\nFormat Specification Mini-Language\\n\\nFormat examples\\n\\nTemplate strings ($-strings)\\n\\nHelper functions\\n\\nPrevious topic\\n\\nText Processing Services\\n\\nNext topic\\n\\nstring.templatelib — Support for template string literals\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nText Processing Services »\\n\\nstring — Common string operations\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\string.templatelib.html'}, page_content=\"Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nText Processing Services »\\n\\nstring.templatelib — Support for template string literals\\n\\n|\\n\\nstring.templatelib — Support for template string literals¶\\n\\nSource code: Lib/string/templatelib.py\\n\\nSee also\\n\\nFormat strings\\n\\nTemplate string literal (t-string) syntax\\n\\nPEP 750\\n\\nTemplate strings¶\\n\\nAdded in version 3.14.\\n\\nTemplate strings are a mechanism for custom string processing. They have the full flexibility of Python’s f-strings, but return a Template instance that gives access to the static and interpolated (in curly brackets) parts of a string before they are combined.\\n\\nTo write a t-string, use a 't' prefix instead of an 'f', like so:\\n\\n>>> pi = 3.14\\n>>> t't-strings are new in Python {pi!s}!'\\nTemplate(\\n strings=('t-strings are new in Python ', '!'),\\n interpolations=(Interpolation(3.14, 'pi', 's', ''),)\\n)\\n\\nTypes¶\\n\\nHelper functions¶\\n\\nTable of Contents\\n\\nstring.templatelib — Support for template string literals\\n\\nTemplate strings\\n\\nTypes\\n\\nHelper functions\\n\\nPrevious topic\\n\\nstring — Common string operations\\n\\nNext topic\\n\\nre — Regular expression operations\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nText Processing Services »\\n\\nstring.templatelib — Support for template string literals\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.\"), Document(metadata={'source': '..\\\\..\\\\docs\\\\stringprep.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nText Processing Services »\\n\\nstringprep — Internet String Preparation\\n\\n|\\n\\nstringprep — Internet String Preparation¶\\n\\nSource code: Lib/stringprep.py\\n\\nWhen identifying things (such as host names) in the internet, it is often necessary to compare such identifications for “equality”. Exactly how this comparison is executed may depend on the application domain, e.g. whether it should be case-insensitive or not. It may be also necessary to restrict the possible identifications, to allow only identifications consisting of “printable” characters.\\n\\nRFC 3454 defines a procedure for “preparing” Unicode strings in internet protocols. Before passing strings onto the wire, they are processed with the preparation procedure, after which they have a certain normalized form. The RFC defines a set of tables, which can be combined into profiles. Each profile must define which tables it uses, and what other optional parts of the stringprep procedure are part of the profile. One example of a stringprep profile is nameprep, which is used for internationalized domain names.\\n\\nThe module stringprep only exposes the tables from RFC 3454. 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 mkstringprep.py utility.\\n\\nAs 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, stringprep provides the “characteristic function”, i.e. a function that returns 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.\\n\\nPrevious topic\\n\\nunicodedata — Unicode Database\\n\\nNext topic\\n\\nreadline — GNU readline interface\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nText Processing Services »\\n\\nstringprep — Internet String Preparation\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\struct.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nBinary Data Services »\\n\\nstruct — Interpret bytes as packed binary data\\n\\n|\\n\\nstruct — Interpret bytes as packed binary data¶\\n\\nSource code: Lib/struct.py\\n\\nThis module converts between Python values and C structs represented as Python bytes objects. Compact 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.\\n\\nNote\\n\\nWhen 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 Byte Order, Size, and Alignment for details.\\n\\nSeveral struct functions (and methods of Struct) take a buffer argument. This refers to objects that implement the Buffer Protocol and provide either a readable or read-writable buffer. The most common types used for that purpose are bytes and 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 bytes object.\\n\\nFunctions and Exceptions¶\\n\\nThe module defines the following exception and functions:\\n\\nFormat Strings¶\\n\\nFormat strings describe the data layout when packing and unpacking data. They are built up from format characters, which specify the type of data being packed/unpacked. In addition, special characters control the byte order, 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.\\n\\nByte Order, Size, and Alignment¶\\n\\nBy 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.\\n\\nAlternatively, the first character of the format string can be used to indicate the byte order, size and alignment of the packed data, according to the following table:\\n\\nCharacter Byte order Size Alignment @ native native native = native standard none < little-endian standard none > big-endian standard none ! network (= big-endian) standard none\\n\\nIf the first character is not one of these, \\'@\\' is assumed.\\n\\nNote\\n\\nThe number 1023 (0x3ff in hexadecimal) has the following byte representations:\\n\\n03 ff in big-endian (>)\\n\\nff 03 in little-endian (<)\\n\\nPython example:\\n\\n>>> import struct\\n>>> struct.pack(\\'>h\\', 1023)\\nb\\'\\\\x03\\\\xff\\'\\n>>> struct.pack(\\'\\'.\\n\\nNotes:\\n\\nPadding is only automatically added between successive structure members. No padding is added at the beginning or the end of the encoded struct.\\n\\nNo padding is added when using non-native size and alignment, e.g. with ‘<’, ‘>’, ‘=’, and ‘!’.\\n\\nTo align the end of a structure to the alignment requirement of a particular type, end the format with the code for that type with a repeat count of zero. See Examples.\\n\\nFormat Characters¶\\n\\nFormat characters have the following meaning; the conversion between C and Python values should be obvious given their types. The ‘Standard size’ column refers to the size of the packed value in bytes when using standard size; that is, when the format string starts with one of \\'<\\', \\'>\\', \\'!\\' or \\'=\\'. When using native size, the size of the packed value is platform-dependent.\\n\\nFormat C Type Python type Standard size Notes x pad byte no value (7) c char bytes of length 1 1 b signed char integer 1 (1), (2) B unsigned char integer 1 (2) ? _Bool bool 1 (1) h short integer 2 (2) H unsigned short integer 2 (2) i int integer 4 (2) I unsigned int integer 4 (2) l long integer 4 (2) L unsigned long integer 4 (2) q long long integer 8 (2) Q unsigned long long integer 8 (2) n ssize_t integer (3) N size_t integer (3) e (6) float 2 (4) f float float 4 (4) d double float 8 (4) F float complex complex 8 (10) D double complex complex 16 (10) s char [ ] bytes (9) p char [ ] bytes (8) P void * integer (5)\\n\\nChanged in version 3.3: Added support for the \\'n\\' and \\'N\\' formats.\\n\\nChanged in version 3.6: Added support for the \\'e\\' format.\\n\\nChanged in version 3.14: Added support for the \\'F\\' and \\'D\\' formats.\\n\\nNotes:\\n\\nThe \\'?\\' conversion code corresponds to the _Bool type defined by C standards since C99. In standard mode, it is represented by one byte.\\n\\nWhen attempting to pack a non-integer using any of the integer conversion codes, if the non-integer has a __index__() method then that method is called to convert the argument to an integer before packing.\\n\\nChanged in version 3.2: Added use of the __index__() method for non-integers.\\n\\nThe \\'n\\' and \\'N\\' conversion codes are only available for the native size (selected as the default or with the \\'@\\' byte order character). For the standard size, you can use whichever of the other integer formats fits your application.\\n\\nFor the \\'f\\', \\'d\\' and \\'e\\' conversion codes, the packed representation uses the IEEE 754 binary32, binary64 or binary16 format (for \\'f\\', \\'d\\' or \\'e\\' respectively), regardless of the floating-point format used by the platform.\\n\\nThe \\'P\\' format character is only available for the native byte ordering (selected as the default or with the \\'@\\' byte order character). The byte order character \\'=\\' chooses to use little- or big-endian ordering based on the host system. The struct module does not interpret this as native ordering, so the \\'P\\' format is not available.\\n\\nThe IEEE 754 binary16 “half precision” type was introduced in the 2008 revision of the IEEE 754 standard. It has a sign bit, a 5-bit exponent and 11-bit precision (with 10 bits explicitly stored), and can represent numbers between approximately 6.1e-05 and 6.5e+04 at full precision. This type is not widely supported by C compilers: on a typical machine, an unsigned short can be used for storage, but not for math operations. See the Wikipedia page on the half-precision floating-point format for more information.\\n\\nWhen packing, \\'x\\' inserts one NUL byte.\\n\\nThe \\'p\\' format character encodes a “Pascal string”, meaning a short variable-length string stored in a fixed number of bytes, given by the count. The first byte stored is the length of the string, or 255, whichever is smaller. The bytes of the string follow. If the string passed in to pack() is too long (longer than the count minus 1), only the leading count-1 bytes of the string are stored. If the string is shorter than count-1, it is padded with null bytes so that exactly count bytes in all are used. Note that for unpack(), the \\'p\\' format character consumes count bytes, but that the string returned can never contain more than 255 bytes.\\n\\nFor the \\'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, \\'10s\\' means a single 10-byte string mapping to or from a single Python byte string, while \\'10c\\' means 10 separate one byte character elements (e.g., cccccccccc) mapping to or from ten different Python byte objects. (See Examples 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, \\'0s\\' means a single, empty string (while \\'0c\\' means 0 characters).\\n\\nFor the \\'F\\' and \\'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 (F and 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.\\n\\nA format character may be preceded by an integral repeat count. For example, the format string \\'4h\\' means exactly the same as \\'hhhh\\'.\\n\\nWhitespace characters between formats are ignored; a count and its format must not contain whitespace though.\\n\\nWhen packing a value x using one of the integer formats (\\'b\\', \\'B\\', \\'h\\', \\'H\\', \\'i\\', \\'I\\', \\'l\\', \\'L\\', \\'q\\', \\'Q\\'), if x is outside the valid range for that format then struct.error is raised.\\n\\nChanged in version 3.1: Previously, some of the integer formats wrapped out-of-range values and raised DeprecationWarning instead of struct.error.\\n\\nFor the \\'?\\' format character, the return value is either True or False. When packing, the truth value of the argument object is used. Either 0 or 1 in the native or standard bool representation will be packed, and any non-zero value will be True when unpacking.\\n\\nExamples¶\\n\\nNote\\n\\nNative byte order examples (designated by the \\'@\\' 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.\\n\\nPack and unpack integers of three different sizes, using big endian ordering:\\n\\n>>> from struct import *\\n>>> pack(\">bhl\", 1, 2, 3)\\nb\\'\\\\x01\\\\x00\\\\x02\\\\x00\\\\x00\\\\x00\\\\x03\\'\\n>>> unpack(\\'>bhl\\', b\\'\\\\x01\\\\x00\\\\x02\\\\x00\\\\x00\\\\x00\\\\x03\\')\\n(1, 2, 3)\\n>>> calcsize(\\'>bhl\\')\\n7\\n\\nAttempt to pack an integer which is too large for the defined field:\\n\\n>>> pack(\">h\", 99999)\\nTraceback (most recent call last):\\n File \"\", line 1, in \\nstruct.error: \\'h\\' format requires -32768 <= number <= 32767\\n\\nDemonstrate the difference between \\'s\\' and \\'c\\' format characters:\\n\\n>>> pack(\"@ccc\", b\\'1\\', b\\'2\\', b\\'3\\')\\nb\\'123\\'\\n>>> pack(\"@3s\", b\\'123\\')\\nb\\'123\\'\\n\\nUnpacked fields can be named by assigning them to variables or by wrapping the result in a named tuple:\\n\\n>>> record = b\\'raymond \\\\x32\\\\x12\\\\x08\\\\x01\\\\x08\\'\\n>>> name, serialnum, school, gradelevel = unpack(\\'<10sHHb\\', record)\\n\\n>>> from collections import namedtuple\\n>>> Student = namedtuple(\\'Student\\', \\'name serialnum school gradelevel\\')\\n>>> Student._make(unpack(\\'<10sHHb\\', record))\\nStudent(name=b\\'raymond \\', serialnum=4658, school=264, gradelevel=8)\\n\\nThe 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 pack call below that three NUL bytes were added after the packed \\'#\\' to align the following integer on a four-byte boundary. In this example, the output was produced on a little endian machine:\\n\\n>>> pack(\\'@ci\\', b\\'#\\', 0x12131415)\\nb\\'#\\\\x00\\\\x00\\\\x00\\\\x15\\\\x14\\\\x13\\\\x12\\'\\n>>> pack(\\'@ic\\', 0x12131415, b\\'#\\')\\nb\\'\\\\x15\\\\x14\\\\x13\\\\x12#\\'\\n>>> calcsize(\\'@ci\\')\\n8\\n>>> calcsize(\\'@ic\\')\\n5\\n\\nThe following format \\'llh0l\\' results in two pad bytes being added at the end, assuming the platform’s longs are aligned on 4-byte boundaries:\\n\\n>>> pack(\\'@llh0l\\', 1, 2, 3)\\nb\\'\\\\x00\\\\x00\\\\x00\\\\x01\\\\x00\\\\x00\\\\x00\\\\x02\\\\x00\\\\x03\\\\x00\\\\x00\\'\\n\\nSee also\\n\\nApplications¶\\n\\nTwo main applications for the struct module exist, data interchange between Python and C code within an application or another application compiled using the same compiler (native formats), and data interchange between applications using agreed upon data layout (standard formats). Generally speaking, the format strings constructed for these two domains are distinct.\\n\\nNative Formats¶\\n\\nWhen constructing format strings which mimic native layouts, the compiler and machine architecture determine byte ordering and padding. In such cases, the @ 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.\\n\\nConsider these two simple examples (on a 64-bit, little-endian machine):\\n\\n>>> calcsize(\\'@lhl\\')\\n24\\n>>> calcsize(\\'@llh\\')\\n18\\n\\nData 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:\\n\\n>>> calcsize(\\'@llh0l\\')\\n24\\n\\nThe \\'x\\' format code can be used to specify the repeat, but for native formats it is better to use a zero-repeat format like \\'0l\\'.\\n\\nBy default, native byte ordering and alignment is used, but it is better to be explicit and use the \\'@\\' prefix character.\\n\\nStandard Formats¶\\n\\nWhen 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 < or > (or !). Padding is the responsibility of the programmer. The zero-repeat format character won’t work. Instead, the user must explicitly add \\'x\\' pad bytes where needed. Revisiting the examples from the previous section, we have:\\n\\n>>> calcsize(\\'>> pack(\\'>> calcsize(\\'@llh\\')\\n18\\n>>> pack(\\'@llh\\', 1, 2, 3) == pack(\\'>> calcsize(\\'>> calcsize(\\'@llh0l\\')\\n24\\n>>> pack(\\'@llh0l\\', 1, 2, 3) == pack(\\'>> calcsize(\\'>> calcsize(\\'@llh0l\\')\\n12\\n>>> pack(\\'@llh0l\\', 1, 2, 3) == pack(\\'\\npid = Popen([\"/bin/mycmd\", \"myarg\"]).pid\\n\\nP_WAIT example:\\n\\nretcode = os.spawnlp(os.P_WAIT, \"/bin/mycmd\", \"mycmd\", \"myarg\")\\n==>\\nretcode = call([\"/bin/mycmd\", \"myarg\"])\\n\\nVector example:\\n\\nos.spawnvp(os.P_NOWAIT, path, args)\\n==>\\nPopen([path] + args[1:])\\n\\nEnvironment example:\\n\\nos.spawnlpe(os.P_NOWAIT, \"/bin/mycmd\", \"mycmd\", \"myarg\", env)\\n==>\\nPopen([\"/bin/mycmd\", \"myarg\"], env={\"PATH\": \"/usr/bin\"})\\n\\nReplacing os.popen()¶\\n\\nReturn code handling translates as follows:\\n\\npipe = os.popen(cmd, \\'w\\')\\n...\\nrc = pipe.close()\\nif rc is not None and rc >> 8:\\n print(\"There were some errors\")\\n==>\\nprocess = Popen(cmd, stdin=PIPE)\\n...\\nprocess.stdin.close()\\nif process.wait() != 0:\\n print(\"There were some errors\")\\n\\nLegacy Shell Invocation Functions¶\\n\\nThis module also provides the following legacy functions from the 2.x commands module. These operations implicitly invoke the system shell and none of the guarantees described above regarding security and exception handling consistency are valid for these functions.\\n\\nNotes¶\\n\\nTimeout Behavior¶\\n\\nWhen using the timeout parameter in functions like run(), Popen.wait(), or Popen.communicate(), users should be aware of the following behaviors:\\n\\nProcess 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.\\n\\nExtremely Small Timeout Values: Setting very small timeout values (such as a few milliseconds) may result in almost immediate TimeoutExpired exceptions because process creation and system scheduling inherently require time.\\n\\nConverting an argument sequence to a string on Windows¶\\n\\nOn Windows, an args sequence is converted to a string that can be parsed using the following rules (which correspond to the rules used by the MS C runtime):\\n\\nArguments are delimited by white space, which is either a space or a tab.\\n\\nA string surrounded by double quotation marks is interpreted as a single argument, regardless of white space contained within. A quoted string can be embedded in an argument.\\n\\nA double quotation mark preceded by a backslash is interpreted as a literal double quotation mark.\\n\\nBackslashes are interpreted literally, unless they immediately precede a double quotation mark.\\n\\nIf backslashes immediately precede a double quotation mark, every pair of backslashes is interpreted as a literal backslash. If the number of backslashes is odd, the last backslash escapes the next double quotation mark as described in rule 3.\\n\\nSee also\\n\\nDisable use of posix_spawn()¶\\n\\nOn Linux, subprocess defaults to using the vfork() system call internally when it is safe to do so rather than fork(). This greatly improves performance.\\n\\nsubprocess._USE_POSIX_SPAWN = False # See CPython issue gh-NNNNNN.\\n\\nIt 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.\\n\\nPlease 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.\\n\\nAdded in version 3.8: _USE_POSIX_SPAWN\\n\\nTable of Contents\\n\\nsubprocess — Subprocess management\\n\\nUsing the subprocess Module\\n\\nFrequently Used Arguments\\n\\nPopen Constructor\\n\\nExceptions\\n\\nSecurity Considerations\\n\\nPopen Objects\\n\\nWindows Popen Helpers\\n\\nWindows Constants\\n\\nOlder high-level API\\n\\nReplacing Older Functions with the subprocess Module\\n\\nReplacing /bin/sh shell command substitution\\n\\nReplacing shell pipeline\\n\\nReplacing os.system()\\n\\nReplacing the os.spawn family\\n\\nReplacing os.popen()\\n\\nLegacy Shell Invocation Functions\\n\\nNotes\\n\\nTimeout Behavior\\n\\nConverting an argument sequence to a string on Windows\\n\\nDisable use of posix_spawn()\\n\\nPrevious topic\\n\\nconcurrent.interpreters — Multiple interpreters in the same process\\n\\nNext topic\\n\\nsched — Event scheduler\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nConcurrent Execution »\\n\\nsubprocess — Subprocess management\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\sunau.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nRemoved Modules »\\n\\nsunau — Read and write Sun AU files\\n\\n|\\n\\nsunau — Read and write Sun AU files¶\\n\\nDeprecated since version 3.11, removed in version 3.13.\\n\\nThis module is no longer part of the Python standard library. It was removed in Python 3.13 after being deprecated in Python 3.11. The removal was decided in PEP 594.\\n\\nThe last version of Python that provided the sunau module was Python 3.12.\\n\\nPrevious topic\\n\\nspwd — The shadow password database\\n\\nNext topic\\n\\ntelnetlib — Telnet client\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nRemoved Modules »\\n\\nsunau — Read and write Sun AU files\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\superseded.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nSuperseded modules\\n\\n|\\n\\nSuperseded modules¶\\n\\nThe modules described in this chapter have been superseded by other modules for most use cases, and are retained primarily to preserve backwards compatibility.\\n\\nModules 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, getopt covers the very specific task of “mimic the C getopt() API in Python”, rather than the broader command line option parsing and argument parsing capabilities offered by optparse and argparse).\\n\\nAlternatively, modules may appear in this chapter because they are deprecated outright, and awaiting removal in a future release, or they are soft deprecated and their use is actively discouraged in new projects. With the removal of various obsolete modules through PEP 594, there are currently no modules in this latter category.\\n\\ngetopt — C-style parser for command line options\\n\\nprofile — Pure Python profiler\\n\\nPrevious topic\\n\\nModules command-line interface (CLI)\\n\\nNext topic\\n\\ngetopt — C-style parser for command line options\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nSuperseded modules\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\symtable.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Language Services »\\n\\nsymtable — Access to the compiler’s symbol tables\\n\\n|\\n\\nsymtable — Access to the compiler’s symbol tables¶\\n\\nSource code: Lib/symtable.py\\n\\nSymbol 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. symtable provides an interface to examine these tables.\\n\\nGenerating Symbol Tables¶\\n\\nExamining Symbol Tables¶\\n\\nCommand-Line Usage¶\\n\\nAdded in version 3.13.\\n\\nThe symtable module can be executed as a script from the command line.\\n\\npython -m symtable [infile...]\\n\\nSymbol 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.\\n\\nTable of Contents\\n\\nsymtable — Access to the compiler’s symbol tables\\n\\nGenerating Symbol Tables\\n\\nExamining Symbol Tables\\n\\nCommand-Line Usage\\n\\nPrevious topic\\n\\nast — Abstract syntax trees\\n\\nNext topic\\n\\ntoken — Constants used with Python parse trees\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Language Services »\\n\\nsymtable — Access to the compiler’s symbol tables\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\sys.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Runtime Services »\\n\\nsys — System-specific parameters and functions\\n\\n|\\n\\nsys — System-specific parameters and functions¶\\n\\nThis 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.\\n\\nCitations\\n\\n[C99]\\n\\nISO/IEC 9899:1999. “Programming languages – C.” A public draft of this standard is available at https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf.\\n\\nPrevious topic\\n\\nPython Runtime Services\\n\\nNext topic\\n\\nsys.monitoring — Execution event monitoring\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Runtime Services »\\n\\nsys — System-specific parameters and functions\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\sys.monitoring.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Runtime Services »\\n\\nsys.monitoring — Execution event monitoring\\n\\n|\\n\\nsys.monitoring — Execution event monitoring¶\\n\\nAdded in version 3.12.\\n\\nNote\\n\\nsys.monitoring is a namespace within the sys module, not an independent module, so there is no need to import sys.monitoring, simply import sys and then use sys.monitoring.\\n\\nThis namespace provides access to the functions and constants necessary to activate and control event monitoring.\\n\\nAs programs execute, events occur that might be of interest to tools that monitor execution. The sys.monitoring namespace provides means to receive callbacks when events of interest occur.\\n\\nThe monitoring API consists of three components:\\n\\nTool identifiers\\n\\nEvents\\n\\nCallbacks\\n\\nTool identifiers¶\\n\\nA 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.\\n\\nBefore registering or activating events, a tool should choose an identifier. Identifiers are integers in the range 0 to 5 inclusive.\\n\\nRegistering and using tools¶\\n\\nAll 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:\\n\\nsys.monitoring.DEBUGGER_ID = 0\\nsys.monitoring.COVERAGE_ID = 1\\nsys.monitoring.PROFILER_ID = 2\\nsys.monitoring.OPTIMIZER_ID = 5\\n\\nEvents¶\\n\\nThe following events are supported:\\n\\nMore events may be added in the future.\\n\\nThese events are attributes of the 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 PY_RETURN and PY_START events, use the expression PY_RETURN | PY_START.\\n\\nLocal events¶\\n\\nLocal 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:\\n\\nPY_START\\n\\nPY_RESUME\\n\\nPY_RETURN\\n\\nPY_YIELD\\n\\nCALL\\n\\nLINE\\n\\nINSTRUCTION\\n\\nJUMP\\n\\nBRANCH_LEFT\\n\\nBRANCH_RIGHT\\n\\nSTOP_ITERATION\\n\\nDeprecated event¶\\n\\nBRANCH\\n\\nThe BRANCH event is deprecated in 3.14. Using BRANCH_LEFT and BRANCH_RIGHT events will give much better performance as they can be disabled independently.\\n\\nAncillary events¶\\n\\nAncillary events can be monitored like other events, but are controlled by another event:\\n\\nC_RAISE\\n\\nC_RETURN\\n\\nThe C_RETURN and C_RAISE events are controlled by the CALL event. C_RETURN and C_RAISE events will only be seen if the corresponding CALL event is being monitored.\\n\\nOther events¶\\n\\nOther events are not necessarily tied to a specific location in the program and cannot be individually disabled via DISABLE.\\n\\nThe other events that can be monitored are:\\n\\nPY_THROW\\n\\nPY_UNWIND\\n\\nRAISE\\n\\nEXCEPTION_HANDLED\\n\\nThe STOP_ITERATION event¶\\n\\nPEP 380 specifies that a 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.\\n\\nTo allow tools to monitor for real exceptions without slowing down generators and coroutines, the STOP_ITERATION event is provided. STOP_ITERATION can be locally disabled, unlike RAISE.\\n\\nNote that the STOP_ITERATION event and the RAISE event for a StopIteration exception are equivalent, and are treated as interchangeable when generating events. Implementations will favor STOP_ITERATION for performance reasons, but may generate a RAISE event with a StopIteration.\\n\\nTurning events on and off¶\\n\\nIn 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.\\n\\nSetting events globally¶\\n\\nEvents can be controlled globally by modifying the set of events being monitored.\\n\\nNo events are active by default.\\n\\nPer code object events¶\\n\\nEvents can also be controlled on a per code object basis. The functions defined below which accept a types.CodeType should be prepared to accept a look-alike object from functions which are not defined in Python (see Monitoring C API).\\n\\nDisabling events¶\\n\\nLocal events can be disabled for a specific code location by returning sys.monitoring.DISABLE from a callback function. This does not change which events are set, or any other code locations for the same event.\\n\\nDisabling 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.\\n\\nIf DISABLE is returned by a callback for a global event, ValueError will be raised by the interpreter in a non-specific location (that is, no traceback will be provided).\\n\\nRegistering callback functions¶\\n\\nFunctions can be unregistered by calling sys.monitoring.register_callback(tool_id, event, None).\\n\\nCallback functions can be registered and unregistered at any time.\\n\\nCallbacks 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.\\n\\nCallback function arguments¶\\n\\nWhen an active event occurs, the registered callback function is called. Callback functions returning an object other than DISABLE will have no effect. Different events will provide the callback function with different arguments, as follows:\\n\\nPY_START and PY_RESUME:\\n\\nfunc(code: CodeType, instruction_offset: int) -> object\\n\\nPY_RETURN and PY_YIELD:\\n\\nfunc(code: CodeType, instruction_offset: int, retval: object) -> object\\n\\nCALL, C_RAISE and C_RETURN (arg0 can be MISSING specifically):\\n\\nfunc(code: CodeType, instruction_offset: int, callable: object, arg0: object) -> object\\n\\ncode 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 sys.monitoring.MISSING.\\n\\nFor instance methods, callable will be the function object as found on the class with arg0 set to the instance (i.e. the self argument to the method).\\n\\nRAISE, RERAISE, EXCEPTION_HANDLED, PY_UNWIND, PY_THROW and STOP_ITERATION:\\n\\nfunc(code: CodeType, instruction_offset: int, exception: BaseException) -> object\\n\\nLINE:\\n\\nfunc(code: CodeType, line_number: int) -> object\\n\\nBRANCH_LEFT, BRANCH_RIGHT and JUMP:\\n\\nfunc(code: CodeType, instruction_offset: int, destination_offset: int) -> object\\n\\nNote that the destination_offset is where the code will next execute.\\n\\nINSTRUCTION:\\n\\nfunc(code: CodeType, instruction_offset: int) -> object\\n\\nTable of Contents\\n\\nsys.monitoring — Execution event monitoring\\n\\nTool identifiers\\n\\nRegistering and using tools\\n\\nEvents\\n\\nLocal events\\n\\nDeprecated event\\n\\nAncillary events\\n\\nOther events\\n\\nThe STOP_ITERATION event\\n\\nTurning events on and off\\n\\nSetting events globally\\n\\nPer code object events\\n\\nDisabling events\\n\\nRegistering callback functions\\n\\nCallback function arguments\\n\\nPrevious topic\\n\\nsys — System-specific parameters and functions\\n\\nNext topic\\n\\nsysconfig — Provide access to Python’s configuration information\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Runtime Services »\\n\\nsys.monitoring — Execution event monitoring\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\sysconfig.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Runtime Services »\\n\\nsysconfig — Provide access to Python’s configuration information\\n\\n|\\n\\nsysconfig — Provide access to Python’s configuration information¶\\n\\nAdded in version 3.2.\\n\\nSource code: Lib/sysconfig\\n\\nThe sysconfig module provides access to Python’s configuration information like the list of installation paths and the configuration variables relevant for the current platform.\\n\\nConfiguration variables¶\\n\\nA Python distribution contains a Makefile and a pyconfig.h header file that are necessary to build both the Python binary itself and third-party C extensions compiled using setuptools.\\n\\nsysconfig puts all variables found in these files in a dictionary that can be accessed using get_config_vars() or get_config_var().\\n\\nNotice that on Windows, it’s a much smaller set.\\n\\nExample of usage:\\n\\n>>> import sysconfig\\n>>> sysconfig.get_config_var(\\'Py_ENABLE_SHARED\\')\\n0\\n>>> sysconfig.get_config_var(\\'LIBDIR\\')\\n\\'/usr/local/lib\\'\\n>>> sysconfig.get_config_vars(\\'AR\\', \\'CXX\\')\\n[\\'ar\\', \\'g++\\']\\n\\nInstallation paths¶\\n\\nPython uses an installation scheme that differs depending on the platform and on the installation options. These schemes are stored in sysconfig under unique identifiers based on the value returned by os.name. The schemes are used by package installers to determine where to copy files to.\\n\\nPython currently supports nine schemes:\\n\\nposix_prefix: scheme for POSIX platforms like Linux or macOS. This is the default scheme used when Python or a component is installed.\\n\\nposix_home: scheme for POSIX platforms, when the home option is used. This scheme defines paths located under a specific home prefix.\\n\\nposix_user: scheme for POSIX platforms, when the user option is used. This scheme defines paths located under the user’s home directory (site.USER_BASE).\\n\\nposix_venv: scheme for Python virtual environments on POSIX platforms; by default it is the same as posix_prefix.\\n\\nnt: scheme for Windows. This is the default scheme used when Python or a component is installed.\\n\\nnt_user: scheme for Windows, when the user option is used.\\n\\nnt_venv: scheme for Python virtual environments on Windows; by default it is the same as nt.\\n\\nvenv: a scheme with values from either posix_venv or nt_venv depending on the platform Python runs on.\\n\\nosx_framework_user: scheme for macOS, when the user option is used.\\n\\nEach scheme is itself composed of a series of paths and each path has a unique identifier. Python currently uses eight paths:\\n\\nstdlib: directory containing the standard Python library files that are not platform-specific.\\n\\nplatstdlib: directory containing the standard Python library files that are platform-specific.\\n\\nplatlib: directory for site-specific, platform-specific files.\\n\\npurelib: directory for site-specific, non-platform-specific files (‘pure’ Python).\\n\\ninclude: directory for non-platform-specific header files for the Python C-API.\\n\\nplatinclude: directory for platform-specific header files for the Python C-API.\\n\\nscripts: directory for script files.\\n\\ndata: directory for data files.\\n\\nUser scheme¶\\n\\nThis 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.\\n\\nFiles will be installed into subdirectories of site.USER_BASE (written as userbase hereafter). This scheme installs pure Python modules and extension modules in the same location (also known as site.USER_SITE).\\n\\nposix_user¶\\n\\nPath Installation directory stdlib userbase /lib/python X.Y platstdlib userbase /lib/python X.Y platlib userbase /lib/python X.Y /site-packages purelib userbase /lib/python X.Y /site-packages include userbase /include/python X.Y scripts userbase /bin data userbase\\n\\nnt_user¶\\n\\nPath Installation directory stdlib userbase \\\\Python XY platstdlib userbase \\\\Python XY platlib userbase \\\\Python XY \\\\site-packages purelib userbase \\\\Python XY \\\\site-packages include userbase \\\\Python XY \\\\Include scripts userbase \\\\Python XY \\\\Scripts data userbase\\n\\nosx_framework_user¶\\n\\nPath Installation directory stdlib userbase /lib/python platstdlib userbase /lib/python platlib userbase /lib/python/site-packages purelib userbase /lib/python/site-packages include userbase /include/python X.Y scripts userbase /bin data userbase\\n\\nHome scheme¶\\n\\nThe idea behind the “home scheme” is that you build and maintain a personal stash of Python modules. This scheme’s name is derived from the idea of a “home” directory on Unix, since it’s not unusual for a Unix user to make their home directory have a layout similar to /usr/ or /usr/local/. This scheme can be used by anyone, regardless of the operating system they are installing for.\\n\\nposix_home¶\\n\\nPath Installation directory stdlib home /lib/python platstdlib home /lib/python platlib home /lib/python purelib home /lib/python include home /include/python platinclude home /include/python scripts home /bin data home\\n\\nPrefix scheme¶\\n\\nThe “prefix scheme” is useful when you wish to use one Python installation to perform the build/install (i.e., to run the setup script), but install modules into the third-party module directory of a different Python installation (or something that looks like a different Python installation). If this sounds a trifle unusual, it is—that’s why the user and home schemes come before. However, there are at least two known cases where the prefix scheme will be useful.\\n\\nFirst, consider that many Linux distributions put Python in /usr, rather than the more traditional /usr/local. This is entirely appropriate, since in those cases Python is part of “the system” rather than a local add-on. However, if you are installing Python modules from source, you probably want them to go in /usr/local/lib/python2.X rather than /usr/lib/python2.X.\\n\\nAnother possibility is a network filesystem where the name used to write to a remote directory is different from the name used to read it: for example, the Python interpreter accessed as /usr/local/bin/python might search for modules in /usr/local/lib/python2.X, but those modules would have to be installed to, say, /mnt/@server/export/lib/python2.X.\\n\\nposix_prefix¶\\n\\nPath Installation directory stdlib prefix /lib/python X.Y platstdlib prefix /lib/python X.Y platlib prefix /lib/python X.Y /site-packages purelib prefix /lib/python X.Y /site-packages include prefix /include/python X.Y platinclude prefix /include/python X.Y scripts prefix /bin data prefix\\n\\nnt¶\\n\\nPath Installation directory stdlib prefix \\\\Lib platstdlib prefix \\\\Lib platlib prefix \\\\Lib\\\\site-packages purelib prefix \\\\Lib\\\\site-packages include prefix \\\\Include platinclude prefix \\\\Include scripts prefix \\\\Scripts data prefix\\n\\nInstallation path functions¶\\n\\nsysconfig provides some functions to determine these installation paths.\\n\\nOther functions¶\\n\\nCommand-line usage¶\\n\\nYou can use sysconfig as a script with Python’s -m option:\\n\\n$ python -m sysconfig\\nPlatform: \"macosx-10.4-i386\"\\nPython version: \"3.2\"\\nCurrent installation scheme: \"posix_prefix\"\\n\\nPaths:\\n data = \"/usr/local\"\\n include = \"/Users/tarek/Dev/svn.python.org/py3k/Include\"\\n platinclude = \".\"\\n platlib = \"/usr/local/lib/python3.2/site-packages\"\\n platstdlib = \"/usr/local/lib/python3.2\"\\n purelib = \"/usr/local/lib/python3.2/site-packages\"\\n scripts = \"/usr/local/bin\"\\n stdlib = \"/usr/local/lib/python3.2\"\\n\\nVariables:\\n AC_APPLE_UNIVERSAL_BUILD = \"0\"\\n AIX_GENUINE_CPLUSPLUS = \"0\"\\n AR = \"ar\"\\n ARFLAGS = \"rc\"\\n ...\\n\\nThis call will print in the standard output the information returned by get_platform(), get_python_version(), get_path() and get_config_vars().\\n\\nTable of Contents\\n\\nsysconfig — Provide access to Python’s configuration information\\n\\nConfiguration variables\\n\\nInstallation paths\\n\\nUser scheme\\n\\nposix_user\\n\\nnt_user\\n\\nosx_framework_user\\n\\nHome scheme\\n\\nposix_home\\n\\nPrefix scheme\\n\\nposix_prefix\\n\\nnt\\n\\nInstallation path functions\\n\\nOther functions\\n\\nCommand-line usage\\n\\nPrevious topic\\n\\nsys.monitoring — Execution event monitoring\\n\\nNext topic\\n\\nbuiltins — Built-in objects\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Runtime Services »\\n\\nsysconfig — Provide access to Python’s configuration information\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\syslog.html'}, page_content=\"Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nUnix-specific services »\\n\\nsyslog — Unix syslog library routines\\n\\n|\\n\\nsyslog — Unix syslog library routines¶\\n\\nThis module provides an interface to the Unix syslog library routines. Refer to the Unix manual pages for a detailed description of the syslog facility.\\n\\nAvailability: Unix, not WASI, not iOS.\\n\\nThis module wraps the system syslog family of routines. A pure Python library that can speak to a syslog server is available in the logging.handlers module as SysLogHandler.\\n\\nThe module defines the following functions:\\n\\nThe module defines the following constants:\\n\\nExamples¶\\n\\nSimple example¶\\n\\nA simple set of examples:\\n\\nimport syslog\\n\\nsyslog.syslog('Processing started')\\nif error:\\n syslog.syslog(syslog.LOG_ERR, 'Processing started')\\n\\nAn example of setting some log options, these would include the process ID in logged messages, and write the messages to the destination facility used for mail logging:\\n\\nsyslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_MAIL)\\nsyslog.syslog('E-mail processing initiated...')\\n\\nTable of Contents\\n\\nsyslog — Unix syslog library routines\\n\\nExamples\\n\\nSimple example\\n\\nPrevious topic\\n\\nresource — Resource usage information\\n\\nNext topic\\n\\nModules command-line interface (CLI)\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nUnix-specific services »\\n\\nsyslog — Unix syslog library routines\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.\"), Document(metadata={'source': '..\\\\..\\\\docs\\\\sys_path_init.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nImporting Modules »\\n\\nThe initialization of the sys.path module search path\\n\\n|\\n\\nThe initialization of the sys.path module search path¶\\n\\nA module search path is initialized when Python starts. This module search path may be accessed at sys.path.\\n\\nThe 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 -c command, or -m module.\\n\\nThe 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.\\n\\nNote\\n\\nPYTHONPATH will affect all installed Python versions/environments. Be wary of setting this in your shell profile or global environment variables. The site module offers more nuanced techniques as mentioned below.\\n\\nThe next items added are the directories containing standard Python modules as well as any extension modules that these modules depend on. Extension modules are .pyd files on Windows and .so files on other platforms. The directory with the platform-independent Python modules is called prefix. The directory with the extension modules is called exec_prefix.\\n\\nThe PYTHONHOME environment variable may be used to set the prefix and 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 home.\\n\\nOnce home is determined, the prefix directory is found by first looking for pythonmajorversionminorversion.zip (python311.zip). On Windows the zip archive is searched for in home and on Unix the archive is expected to be in 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 prefix by looking for Lib\\\\os.py. Python on Unix will look for lib/pythonmajorversion.minorversion/os.py (lib/python3.11/os.py). On Windows prefix and exec_prefix are the same, however on other platforms lib/pythonmajorversion.minorversion/lib-dynload (lib/python3.11/lib-dynload) is searched for and used as an anchor for exec_prefix. On some platforms lib may be lib64 or another value, see sys.platlibdir and PYTHONPLATLIBDIR.\\n\\nOnce found, prefix and exec_prefix are available at sys.base_prefix and sys.base_exec_prefix respectively.\\n\\nIf PYTHONHOME is not set, and a pyvenv.cfg file is found alongside the main executable, or in its parent directory, sys.prefix and sys.exec_prefix get set to the directory containing pyvenv.cfg, otherwise they are set to the same value as sys.base_prefix and sys.base_exec_prefix, respectively. This is used by Virtual Environments.\\n\\nFinally, the site module is processed and site-packages directories are added to the module search path. The PYTHONUSERBASE environment variable controls where is searched for user site-packages and the PYTHONNOUSERSITE environment variable prevents searching for user site-packages all together. A common way to customize the search path is to create sitecustomize or usercustomize modules as described in the site module documentation.\\n\\nNote\\n\\nThe command line options -E, -P, -I, -S and -s further affect path calculations, see their documentation for details.\\n\\nChanged in version 3.14: sys.prefix and sys.exec_prefix are now set to the pyvenv.cfg directory during the path initialization. This was previously done by site, therefore affected by -S.\\n\\nVirtual Environments¶\\n\\nVirtual environments place a pyvenv.cfg file in their prefix, which causes sys.prefix and sys.exec_prefix to point to them, instead of the base installation.\\n\\nThe prefix and exec_prefix values of the base installation are available at sys.base_prefix and sys.base_exec_prefix.\\n\\nAs well as being used as a marker to identify virtual environments, pyvenv.cfg may also be used to configure the site initialization. Please refer to site’s virtual environments documentation.\\n\\nNote\\n\\nPYTHONHOME overrides the pyvenv.cfg detection.\\n\\nNote\\n\\nThere are other ways “virtual environments” could be implemented. This documentation refers to implementations based on the pyvenv.cfg mechanism, such as venv, that many virtual environment implementations follow.\\n\\n_pth files¶\\n\\nTo completely override sys.path create a ._pth file with the same name as the shared library or executable (python._pth or python311._pth). The shared library path is always known on Windows, however it may not be available on other platforms. In the ._pth file specify one line for each path to add to 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.\\n\\nWhen the file exists, all registry and environment variables are ignored, isolated mode is enabled, and site is not imported unless one line in the file specifies import site. Blank paths and lines starting with # are ignored. Each path may be absolute or relative to the location of the file. Import statements other than to site are not permitted, and arbitrary code cannot be specified.\\n\\nNote that .pth files (without leading underscore) will be processed normally by the site module when import site has been specified.\\n\\nEmbedded Python¶\\n\\nIf Python is embedded within another application Py_InitializeFromConfig() and the PyConfig structure can be used to initialize Python. The path specific details are described at Python Path Configuration.\\n\\nSee also\\n\\nFinding modules for detailed Windows notes.\\n\\nUsing Python on Unix platforms for Unix details.\\n\\nTable of Contents\\n\\nThe initialization of the sys.path module search path\\n\\nVirtual Environments\\n\\n_pth files\\n\\nEmbedded Python\\n\\nPrevious topic\\n\\nimportlib.metadata – Accessing package metadata\\n\\nNext topic\\n\\nPython Language Services\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nImporting Modules »\\n\\nThe initialization of the sys.path module search path\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\tabnanny.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Language Services »\\n\\ntabnanny — Detection of ambiguous indentation\\n\\n|\\n\\ntabnanny — Detection of ambiguous indentation¶\\n\\nSource code: Lib/tabnanny.py\\n\\nFor the time being this module is intended to be called as a script. However it is possible to import it into an IDE and use the function check() described below.\\n\\nNote\\n\\nThe API provided by this module is likely to change in future releases; such changes may not be backward compatible.\\n\\nSee also\\n\\nPrevious topic\\n\\ntokenize — Tokenizer for Python source\\n\\nNext topic\\n\\npyclbr — Python module browser support\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Language Services »\\n\\ntabnanny — Detection of ambiguous indentation\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\tarfile.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Compression and Archiving »\\n\\ntarfile — Read and write tar archive files\\n\\n|\\n\\ntarfile — Read and write tar archive files¶\\n\\nSource code: Lib/tarfile.py\\n\\nThe tarfile module makes it possible to read and write tar archives, including those using gzip, bz2 and lzma compression. Use the zipfile module to read or write .zip files, or the higher-level functions in shutil.\\n\\nSome facts and figures:\\n\\nreads and writes gzip, bz2, compression.zstd, and lzma compressed archives if the respective modules are available.\\n\\nIf any of these 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 Requirements for optional modules.\\n\\nread/write support for the POSIX.1-1988 (ustar) format.\\n\\nread/write support for the GNU tar format including longname and longlink extensions, read-only support for all variants of the sparse extension including restoration of sparse files.\\n\\nread/write support for the POSIX.1-2001 (pax) format.\\n\\nhandles directories, regular files, hardlinks, symbolic links, fifos, character devices and block devices and is able to acquire and restore file information like timestamp, access permissions and owner.\\n\\nChanged in version 3.3: Added support for lzma compression.\\n\\nChanged in version 3.12: Archives are extracted using a filter, which makes it possible to either limit surprising/dangerous features, or to acknowledge that they are expected and the archive is fully trusted.\\n\\nChanged in version 3.14: Set the default extraction filter to 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 fully_trusted.\\n\\nChanged in version 3.14: Added support for Zstandard compression using compression.zstd.\\n\\nThe tarfile module defines the following exceptions:\\n\\nThe following constants are available at the module level:\\n\\nEach of the following constants defines a tar archive format that the tarfile module is able to create. See section Supported tar formats for details.\\n\\nSee also\\n\\nTarFile Objects¶\\n\\nThe TarFile object provides an interface to a tar archive. A tar archive is a sequence of blocks. An archive member (a stored file) is made up of a header block followed by data blocks. It is possible to store a file in a tar archive several times. Each archive member is represented by a TarInfo object, see TarInfo Objects for details.\\n\\nA TarFile object can be used as a context manager in a with statement. It will automatically be closed when the block is completed. Please note that in the event of an exception an archive opened for writing will not be finalized; only the internally used file object will be closed. See the Examples section for a use case.\\n\\nAdded in version 3.2: Added support for the context management protocol.\\n\\nTarInfo Objects¶\\n\\nA TarInfo object represents one member in a TarFile. Aside from storing all required attributes of a file (like file type, size, time, permissions, owner etc.), it provides some useful methods to determine its type. It does not contain the file’s data itself.\\n\\nTarInfo objects are returned by TarFile’s methods getmember(), getmembers() and gettarinfo().\\n\\nModifying the objects returned by getmember() or getmembers() will affect all subsequent operations on the archive. For cases where this is unwanted, you can use copy.copy() or call the replace() method to create a modified copy in one step.\\n\\nSeveral attributes can be set to None to indicate that a piece of metadata is unused or unknown. Different TarInfo methods handle None differently:\\n\\nThe extract() or extractall() methods will ignore the corresponding metadata, leaving it set to a default.\\n\\naddfile() will fail.\\n\\nlist() will print a placeholder string.\\n\\nA TarInfo object has the following public data attributes:\\n\\nA TarInfo object also provides some convenient query methods:\\n\\nExtraction filters¶\\n\\nAdded in version 3.12.\\n\\nThe 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, .. path components, or symlinks that affect later members).\\n\\nIn 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.\\n\\nWarning\\n\\nNone of the available filters blocks all dangerous archive features. Never extract archives from untrusted sources without prior inspection. See also Hints for further verification.\\n\\nSee also\\n\\nThe filter argument to TarFile.extract() or extractall() can be:\\n\\nthe string \\'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.\\n\\nthe string \\'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 tar_filter() for details.\\n\\nthe string \\'data\\': Ignore or block most features specific to UNIX-like filesystems. Intended for extracting cross-platform data archives. See data_filter() for details.\\n\\nNone (default): Use TarFile.extraction_filter.\\n\\nIf that is also None (the default), the \\'data\\' filter will be used.\\n\\nChanged in version 3.14: The default filter is set to data. Previously, the default was equivalent to fully_trusted.\\n\\nA callable which will be called for each extracted member with a TarInfo describing the member and the destination path to where the archive is extracted (i.e. the same path is used for all members):\\n\\nfilter(member: TarInfo, path: str, /) -> TarInfo | None\\n\\nThe callable is called just before each member is extracted, so it can take the current state of the disk into account. It can:\\n\\nreturn a TarInfo object which will be used instead of the metadata in the archive, or\\n\\nreturn None, in which case the member will be skipped, or\\n\\nraise an exception to abort the operation or skip the member, depending on errorlevel. Note that when extraction is aborted, extractall() may leave the archive partially extracted. It does not attempt to clean up.\\n\\nDefault named filters¶\\n\\nThe pre-defined, named filters are available as functions, so they can be reused in custom filters:\\n\\nFilter errors¶\\n\\nWhen a filter refuses to extract a file, it will raise an appropriate exception, a subclass of FilterError. This will abort the extraction if TarFile.errorlevel is 1 or more. With errorlevel=0 the error will be logged and the member will be skipped, but extraction will continue.\\n\\nHints for further verification¶\\n\\nEven with 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.\\n\\nHere is an incomplete list of things to consider:\\n\\nExtract to a new temporary directory to prevent e.g. exploiting pre-existing links, and to make it easier to clean up after a failed extraction.\\n\\nDisallow symbolic links if you do not need the functionality.\\n\\nWhen working with untrusted data, use external (e.g. OS-level) limits on disk, memory and CPU usage.\\n\\nCheck filenames against an allow-list of characters (to filter out control characters, confusables, foreign path separators, and so on).\\n\\nCheck that filenames have expected extensions (discouraging files that execute when you “click on them”, or extension-less files like Windows special device names).\\n\\nLimit the number of extracted files, total size of extracted data, filename length (including symlink length), and size of individual files.\\n\\nCheck for files that would be shadowed on case-insensitive filesystems.\\n\\nAlso note that:\\n\\nTar 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.\\n\\ntarfile 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.\\n\\nSupporting older Python versions¶\\n\\nExtraction 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. hasattr(tarfile, \\'data_filter\\') rather than checking the Python version.\\n\\nThe following examples show how to support Python versions with and without the feature. Note that setting extraction_filter will affect any subsequent operations.\\n\\nFully trusted archive:\\n\\nmy_tarfile.extraction_filter = (lambda member, path: member)\\nmy_tarfile.extractall()\\n\\nUse the \\'data\\' filter if available, but revert to Python 3.11 behavior (\\'fully_trusted\\') if this feature is not available:\\n\\nmy_tarfile.extraction_filter = getattr(tarfile, \\'data_filter\\',\\n (lambda member, path: member))\\nmy_tarfile.extractall()\\n\\nUse the \\'data\\' filter; fail if it is not available:\\n\\nmy_tarfile.extractall(filter=tarfile.data_filter)\\n\\nor:\\n\\nmy_tarfile.extraction_filter = tarfile.data_filter\\nmy_tarfile.extractall()\\n\\nUse the \\'data\\' filter; warn if it is not available:\\n\\nif hasattr(tarfile, \\'data_filter\\'):\\n my_tarfile.extractall(filter=\\'data\\')\\nelse:\\n # remove this when no longer needed\\n warn_the_user(\\'Extracting may be unsafe; consider updating Python\\')\\n my_tarfile.extractall()\\n\\nStateful extraction filter example¶\\n\\nWhile 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:\\n\\nwith StatefulFilter() as filter_func:\\n tar.extractall(path, filter=filter_func)\\n\\nSuch a filter can be written as, for example:\\n\\nclass StatefulFilter:\\n def __init__(self):\\n self.file_count = 0\\n\\n def __enter__(self):\\n return self\\n\\n def __call__(self, member, path):\\n self.file_count += 1\\n return member\\n\\n def __exit__(self, *exc_info):\\n print(f\\'{self.file_count} files extracted\\')\\n\\nCommand-Line Interface¶\\n\\nAdded in version 3.4.\\n\\nThe tarfile module provides a simple command-line interface to interact with tar archives.\\n\\nIf you want to create a new tar archive, specify its name after the -c option and then list the filename(s) that should be included:\\n\\n$ python -m tarfile -c monty.tar spam.txt eggs.txt\\n\\nPassing a directory is also acceptable:\\n\\n$ python -m tarfile -c monty.tar life-of-brian_1979/\\n\\nIf you want to extract a tar archive into the current directory, use the -e option:\\n\\n$ python -m tarfile -e monty.tar\\n\\nYou can also extract a tar archive into a different directory by passing the directory’s name:\\n\\n$ python -m tarfile -e monty.tar other-dir/\\n\\nFor a list of the files in a tar archive, use the -l option:\\n\\n$ python -m tarfile -l monty.tar\\n\\nCommand-line options¶\\n\\nExamples¶\\n\\nReading examples¶\\n\\nHow to extract an entire tar archive to the current working directory:\\n\\nimport tarfile\\ntar = tarfile.open(\"sample.tar.gz\")\\ntar.extractall(filter=\\'data\\')\\ntar.close()\\n\\nHow to extract a subset of a tar archive with TarFile.extractall() using a generator function instead of a list:\\n\\nimport os\\nimport tarfile\\n\\ndef py_files(members):\\n for tarinfo in members:\\n if os.path.splitext(tarinfo.name)[1] == \".py\":\\n yield tarinfo\\n\\ntar = tarfile.open(\"sample.tar.gz\")\\ntar.extractall(members=py_files(tar))\\ntar.close()\\n\\nHow to read a gzip compressed tar archive and display some member information:\\n\\nimport tarfile\\ntar = tarfile.open(\"sample.tar.gz\", \"r:gz\")\\nfor tarinfo in tar:\\n print(tarinfo.name, \"is\", tarinfo.size, \"bytes in size and is \", end=\"\")\\n if tarinfo.isreg():\\n print(\"a regular file.\")\\n elif tarinfo.isdir():\\n print(\"a directory.\")\\n else:\\n print(\"something else.\")\\ntar.close()\\n\\nWriting examples¶\\n\\nHow to create an uncompressed tar archive from a list of filenames:\\n\\nimport tarfile\\ntar = tarfile.open(\"sample.tar\", \"w\")\\nfor name in [\"foo\", \"bar\", \"quux\"]:\\n tar.add(name)\\ntar.close()\\n\\nThe same example using the with statement:\\n\\nimport tarfile\\nwith tarfile.open(\"sample.tar\", \"w\") as tar:\\n for name in [\"foo\", \"bar\", \"quux\"]:\\n tar.add(name)\\n\\nHow to create and write an archive to stdout using sys.stdout.buffer in the fileobj parameter in TarFile.add():\\n\\nimport sys\\nimport tarfile\\nwith tarfile.open(\"sample.tar.gz\", \"w|gz\", fileobj=sys.stdout.buffer) as tar:\\n for name in [\"foo\", \"bar\", \"quux\"]:\\n tar.add(name)\\n\\nHow to create an archive and reset the user information using the filter parameter in TarFile.add():\\n\\nimport tarfile\\ndef reset(tarinfo):\\n tarinfo.uid = tarinfo.gid = 0\\n tarinfo.uname = tarinfo.gname = \"root\"\\n return tarinfo\\ntar = tarfile.open(\"sample.tar.gz\", \"w:gz\")\\ntar.add(\"foo\", filter=reset)\\ntar.close()\\n\\nSupported tar formats¶\\n\\nThere are three tar formats that can be created with the tarfile module:\\n\\nThe POSIX.1-1988 ustar format (USTAR_FORMAT). It supports filenames up to a length of at best 256 characters and linknames up to 100 characters. The maximum file size is 8 GiB. This is an old and limited but widely supported format.\\n\\nThe GNU tar format (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. tarfile fully supports the GNU tar extensions for long names, sparse file support is read-only.\\n\\nThe POSIX.1-2001 pax format (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.\\n\\nIt 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.\\n\\nThere are some more variants of the tar format which can be read, but not created:\\n\\nThe ancient V7 format. This is the first tar format from Unix Seventh Edition, storing only regular files and directories. Names must not be longer than 100 characters, there is no user/group name information. Some archives have miscalculated header checksums in case of fields with non-ASCII characters.\\n\\nThe SunOS tar extended format. This format is a variant of the POSIX.1-2001 pax format, but is not compatible.\\n\\nUnicode issues¶\\n\\nThe tar format was originally conceived to make backups on tape drives with the main focus on preserving file system information. Nowadays tar archives are commonly used for file distribution and exchanging archives over networks. One problem of the original format (which is the basis of all other formats) is that there is no concept of supporting different character encodings. For example, an ordinary tar archive created on a UTF-8 system cannot be read correctly on a Latin-1 system if it contains non-ASCII characters. Textual metadata (like filenames, linknames, user/group names) will appear damaged. Unfortunately, there is no way to autodetect the encoding of an archive. The pax format was designed to solve this problem. It stores non-ASCII metadata using the universal character encoding UTF-8.\\n\\nThe details of character conversion in tarfile are controlled by the encoding and errors keyword arguments of the TarFile class.\\n\\nencoding defines the character encoding to use for the metadata in the archive. The default value is sys.getfilesystemencoding() or \\'ascii\\' as a fallback. Depending on whether the archive is read or written, the metadata must be either decoded or encoded. If encoding is not set appropriately, this conversion may fail.\\n\\nThe errors argument defines how characters are treated that cannot be converted. Possible values are listed in section Error Handlers. The default scheme is \\'surrogateescape\\' which Python also uses for its file system calls, see File Names, Command Line Arguments, and Environment Variables.\\n\\nFor PAX_FORMAT archives (the default), encoding is generally not needed because all the metadata is stored using UTF-8. encoding is only used in the rare cases when binary pax headers are decoded or when strings with surrogate characters are stored.\\n\\nTable of Contents\\n\\ntarfile — Read and write tar archive files\\n\\nTarFile Objects\\n\\nTarInfo Objects\\n\\nExtraction filters\\n\\nDefault named filters\\n\\nFilter errors\\n\\nHints for further verification\\n\\nSupporting older Python versions\\n\\nStateful extraction filter example\\n\\nCommand-Line Interface\\n\\nCommand-line options\\n\\nExamples\\n\\nReading examples\\n\\nWriting examples\\n\\nSupported tar formats\\n\\nUnicode issues\\n\\nPrevious topic\\n\\nzipfile — Work with ZIP archives\\n\\nNext topic\\n\\nFile Formats\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Compression and Archiving »\\n\\ntarfile — Read and write tar archive files\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\telnetlib.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nRemoved Modules »\\n\\ntelnetlib — Telnet client\\n\\n|\\n\\ntelnetlib — Telnet client¶\\n\\nDeprecated since version 3.11, removed in version 3.13.\\n\\nThis module is no longer part of the Python standard library. It was removed in Python 3.13 after being deprecated in Python 3.11. The removal was decided in PEP 594.\\n\\nPossible replacements are third-party libraries from PyPI: telnetlib3 or Exscript. These are not supported or maintained by the Python core team.\\n\\nThe last version of Python that provided the telnetlib module was Python 3.12.\\n\\nPrevious topic\\n\\nsunau — Read and write Sun AU files\\n\\nNext topic\\n\\nuu — Encode and decode uuencode files\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nRemoved Modules »\\n\\ntelnetlib — Telnet client\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\tempfile.html'}, page_content=\"Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nFile and Directory Access »\\n\\ntempfile — Generate temporary files and directories\\n\\n|\\n\\ntempfile — Generate temporary files and directories¶\\n\\nSource code: Lib/tempfile.py\\n\\nThis module creates temporary files and directories. It works on all supported platforms. TemporaryFile, NamedTemporaryFile, TemporaryDirectory, and SpooledTemporaryFile are high-level interfaces which provide automatic cleanup and can be used as context managers. mkstemp() and mkdtemp() are lower-level functions which require manual cleanup.\\n\\nAll the user-callable functions and constructors take additional arguments which allow direct control over the location and name of temporary files and directories. Files names used by this module include a string of random characters which allows those files to be securely created in shared temporary directories. To maintain backward compatibility, the argument order is somewhat odd; it is recommended to use keyword arguments for clarity.\\n\\nThe module defines the following user-callable items:\\n\\nThe module uses a global variable to store the name of the directory used for temporary files returned by 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.\\n\\nExamples¶\\n\\nHere are some examples of typical usage of the tempfile module:\\n\\n>>> import tempfile\\n\\n# create a temporary file and write some data to it\\n>>> fp = tempfile.TemporaryFile()\\n>>> fp.write(b'Hello world!')\\n# read data from file\\n>>> fp.seek(0)\\n>>> fp.read()\\nb'Hello world!'\\n# close the file, it will be removed\\n>>> fp.close()\\n\\n# create a temporary file using a context manager\\n>>> with tempfile.TemporaryFile() as fp:\\n... fp.write(b'Hello world!')\\n... fp.seek(0)\\n... fp.read()\\nb'Hello world!'\\n>>>\\n# file is now closed and removed\\n\\n# create a temporary file using a context manager\\n# close the file, use the name to open the file again\\n>>> with tempfile.NamedTemporaryFile(delete_on_close=False) as fp:\\n... fp.write(b'Hello world!')\\n... fp.close()\\n... # the file is closed, but not removed\\n... # open the file again by using its name\\n... with open(fp.name, mode='rb') as f:\\n... f.read()\\nb'Hello world!'\\n>>>\\n# file is now removed\\n\\n# create a temporary directory using the context manager\\n>>> with tempfile.TemporaryDirectory() as tmpdirname:\\n... print('created temporary directory', tmpdirname)\\n>>>\\n# directory and contents have been removed\\n\\nDeprecated functions and variables¶\\n\\nA historical way to create temporary files was to first generate a file name with the mktemp() function and then create a file using this name. Unfortunately this is not secure, because a different process may create a file with this name in the time between the call to mktemp() and the subsequent attempt to create the file by the first process. The solution is to combine the two steps and create the file immediately. This approach is used by mkstemp() and the other functions described above.\\n\\nTable of Contents\\n\\ntempfile — Generate temporary files and directories\\n\\nExamples\\n\\nDeprecated functions and variables\\n\\nPrevious topic\\n\\nfilecmp — File and Directory Comparisons\\n\\nNext topic\\n\\nglob — Unix style pathname pattern expansion\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nFile and Directory Access »\\n\\ntempfile — Generate temporary files and directories\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.\"), Document(metadata={'source': '..\\\\..\\\\docs\\\\termios.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nUnix-specific services »\\n\\ntermios — POSIX style tty control\\n\\n|\\n\\ntermios — POSIX style tty control¶\\n\\nThis module provides an interface to the POSIX calls for tty I/O control. For a complete description of these calls, see termios(3) Unix manual page. It is only available for those Unix versions that support POSIX termios style tty I/O control configured during installation.\\n\\nAvailability: Unix.\\n\\nAll functions in this module take a file descriptor fd as their first argument. This can be an integer file descriptor, such as returned by sys.stdin.fileno(), or a file object, such as sys.stdin itself.\\n\\nThis module also defines all the constants needed to work with the functions provided here; these have the same name as their counterparts in C. Please refer to your system documentation for more information on using these terminal control interfaces.\\n\\nThe module defines the following functions:\\n\\nSee also\\n\\nExample¶\\n\\nHere’s a function that prompts for a password with echoing turned off. Note the technique using a separate tcgetattr() call and a try … finally statement to ensure that the old tty attributes are restored exactly no matter what happens:\\n\\ndef getpass(prompt=\"Password: \"):\\n import termios, sys\\n fd = sys.stdin.fileno()\\n old = termios.tcgetattr(fd)\\n new = termios.tcgetattr(fd)\\n new[3] = new[3] & ~termios.ECHO # lflags\\n try:\\n termios.tcsetattr(fd, termios.TCSADRAIN, new)\\n passwd = input(prompt)\\n finally:\\n termios.tcsetattr(fd, termios.TCSADRAIN, old)\\n return passwd\\n\\nTable of Contents\\n\\ntermios — POSIX style tty control\\n\\nExample\\n\\nPrevious topic\\n\\ngrp — The group database\\n\\nNext topic\\n\\ntty — Terminal control functions\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nUnix-specific services »\\n\\ntermios — POSIX style tty control\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\test.html'}, page_content=\"Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nDevelopment Tools »\\n\\ntest — Regression tests package for Python\\n\\n|\\n\\ntest — Regression tests package for Python¶\\n\\nNote\\n\\nThe 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.\\n\\nThe test package contains all regression tests for Python as well as the modules test.support and test.regrtest. test.support is used to enhance your tests while test.regrtest drives the testing suite.\\n\\nEach module in the test package whose name starts with test_ is a testing suite for a specific module or feature. All new tests should be written using the unittest or doctest module. Some older tests are written using a “traditional” testing style that compares output printed to sys.stdout; this style of test is considered deprecated.\\n\\nSee also\\n\\nWriting Unit Tests for the test package¶\\n\\nIt is preferred that tests that use the unittest module follow a few guidelines. One is to name the test module by starting it with test_ and end it with the name of the module being tested. The test methods in the test module should start with test_ and end with a description of what the method is testing. This is needed so that the methods are recognized by the test driver as test methods. Also, no documentation string for the method should be included. A comment (such as # Tests function returns only True or False) should be used to provide documentation for test methods. This is done because documentation strings get printed out if they exist and thus what test is being run is not stated.\\n\\nA basic boilerplate is often used:\\n\\nimport unittest\\nfrom test import support\\n\\nclass MyTestCase1(unittest.TestCase):\\n\\n # Only use setUp() and tearDown() if necessary\\n\\n def setUp(self):\\n ... code to execute in preparation for tests ...\\n\\n def tearDown(self):\\n ... code to execute to clean up after tests ...\\n\\n def test_feature_one(self):\\n # Test feature one.\\n ... testing code ...\\n\\n def test_feature_two(self):\\n # Test feature two.\\n ... testing code ...\\n\\n ... more test methods ...\\n\\nclass MyTestCase2(unittest.TestCase):\\n ... same structure as MyTestCase1 ...\\n\\n... more test classes ...\\n\\nif __name__ == '__main__':\\n unittest.main()\\n\\nThis code pattern allows the testing suite to be run by test.regrtest, on its own as a script that supports the unittest CLI, or via the python -m unittest CLI.\\n\\nThe goal for regression testing is to try to break code. This leads to a few guidelines to be followed:\\n\\nThe testing suite should exercise all classes, functions, and constants. This includes not just the external API that is to be presented to the outside world but also “private” code.\\n\\nWhitebox testing (examining the code being tested when the tests are being written) is preferred. Blackbox testing (testing only the published user interface) is not complete enough to make sure all boundary and edge cases are tested.\\n\\nMake sure all possible values are tested including invalid ones. This makes sure that not only all valid values are acceptable but also that improper values are handled correctly.\\n\\nExhaust as many code paths as possible. Test where branching occurs and thus tailor input to make sure as many different paths through the code are taken.\\n\\nAdd an explicit test for any bugs discovered for the tested code. This will make sure that the error does not crop up again if the code is changed in the future.\\n\\nMake sure to clean up after your tests (such as close and remove all temporary files).\\n\\nIf a test is dependent on a specific condition of the operating system then verify the condition already exists before attempting the test.\\n\\nImport as few modules as possible and do it as soon as possible. This minimizes external dependencies of tests and also minimizes possible anomalous behavior from side-effects of importing a module.\\n\\nTry to maximize code reuse. On occasion, tests will vary by something as small as what type of input is used. Minimize code duplication by subclassing a basic test class with a class that specifies the input:\\n\\nclass TestFuncAcceptsSequencesMixin:\\n\\n func = mySuperWhammyFunction\\n\\n def test_func(self):\\n self.func(self.arg)\\n\\nclass AcceptLists(TestFuncAcceptsSequencesMixin, unittest.TestCase):\\n arg = [1, 2, 3]\\n\\nclass AcceptStrings(TestFuncAcceptsSequencesMixin, unittest.TestCase):\\n arg = 'abc'\\n\\nclass AcceptTuples(TestFuncAcceptsSequencesMixin, unittest.TestCase):\\n arg = (1, 2, 3)\\n\\nWhen using this pattern, remember that all classes that inherit from unittest.TestCase are run as tests. The 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 unittest.TestCase.\\n\\nSee also\\n\\nRunning tests using the command-line interface¶\\n\\nThe test package can be run as a script to drive Python’s regression test suite, thanks to the -m option: python -m test. Under the hood, it uses test.regrtest; the call python -m test.regrtest used in previous Python versions still works. Running the script by itself automatically starts running all regression tests in the test package. It does this by finding all modules in the package whose name starts with test_, importing them, and executing the function test_main() if present or loading the tests via unittest.TestLoader.loadTestsFromModule if test_main does not exist. The names of tests to execute may also be passed to the script. Specifying a single regression test (python -m test test_spam) will minimize output and only print whether the test passed or failed.\\n\\nRunning test directly allows what resources are available for tests to use to be set. You do this by using the -u command-line option. Specifying all as the value for the -u option enables all possible resources: python -m test -uall. If all but one resource is desired (a more common case), a comma-separated list of resources that are not desired may be listed after all. The command python -m test -uall,-audio,-largefile will run test with all resources except the audio and largefile resources. For a list of all resources and more command-line options, run python -m test -h.\\n\\nSome other ways to execute the regression tests depend on what platform the tests are being executed on. On Unix, you can run make test at the top-level directory where Python was built. On Windows, executing rt.bat from your PCbuild directory will run all regression tests.\\n\\nAdded in version 3.14: Output is colorized by default and can be controlled using environment variables.\\n\\ntest.support — Utilities for the Python test suite¶\\n\\nThe test.support module provides support for Python’s regression test suite.\\n\\nNote\\n\\ntest.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.\\n\\nThis module defines the following exceptions:\\n\\nThe test.support module defines the following constants:\\n\\nThe test.support module defines the following functions:\\n\\nThe test.support module defines the following classes:\\n\\ntest.support.socket_helper — Utilities for socket tests¶\\n\\nThe test.support.socket_helper module provides support for socket tests.\\n\\nAdded in version 3.9.\\n\\ntest.support.script_helper — Utilities for the Python execution tests¶\\n\\nThe test.support.script_helper module provides support for Python’s script execution tests.\\n\\ntest.support.bytecode_helper — Support tools for testing correct bytecode generation¶\\n\\nThe test.support.bytecode_helper module provides support for testing and inspecting bytecode generation.\\n\\nAdded in version 3.9.\\n\\nThe module defines the following class:\\n\\ntest.support.threading_helper — Utilities for threading tests¶\\n\\nThe test.support.threading_helper module provides support for threading tests.\\n\\nAdded in version 3.10.\\n\\ntest.support.os_helper — Utilities for os tests¶\\n\\nThe test.support.os_helper module provides support for os tests.\\n\\nAdded in version 3.10.\\n\\ntest.support.import_helper — Utilities for import tests¶\\n\\nThe test.support.import_helper module provides support for import tests.\\n\\nAdded in version 3.10.\\n\\ntest.support.warnings_helper — Utilities for warnings tests¶\\n\\nThe test.support.warnings_helper module provides support for warnings tests.\\n\\nAdded in version 3.10.\\n\\nTable of Contents\\n\\ntest — Regression tests package for Python\\n\\nWriting Unit Tests for the test package\\n\\nRunning tests using the command-line interface\\n\\ntest.support — Utilities for the Python test suite\\n\\ntest.support.socket_helper — Utilities for socket tests\\n\\ntest.support.script_helper — Utilities for the Python execution tests\\n\\ntest.support.bytecode_helper — Support tools for testing correct bytecode generation\\n\\ntest.support.threading_helper — Utilities for threading tests\\n\\ntest.support.os_helper — Utilities for os tests\\n\\ntest.support.import_helper — Utilities for import tests\\n\\ntest.support.warnings_helper — Utilities for warnings tests\\n\\nPrevious topic\\n\\nunittest.mock — getting started\\n\\nNext topic\\n\\nDebugging and profiling\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nDevelopment Tools »\\n\\ntest — Regression tests package for Python\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.\"), Document(metadata={'source': '..\\\\..\\\\docs\\\\text.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nText Processing Services\\n\\n|\\n\\nText Processing Services¶\\n\\nThe modules described in this chapter provide a wide range of string manipulation operations and other text processing services.\\n\\nThe codecs module described under Binary Data Services is also highly relevant to text processing. In addition, see the documentation for Python’s built-in string type in Text Sequence Type — str.\\n\\nstring — Common string operations\\n\\nString constants\\n\\nCustom String Formatting\\n\\nFormat String Syntax\\n\\nFormat Specification Mini-Language\\n\\nFormat examples\\n\\nTemplate strings ($-strings)\\n\\nHelper functions\\n\\nstring.templatelib — Support for template string literals\\n\\nTemplate strings\\n\\nTypes\\n\\nHelper functions\\n\\nre — Regular expression operations\\n\\nRegular Expression Syntax\\n\\nModule Contents\\n\\nFlags\\n\\nFunctions\\n\\nExceptions\\n\\nRegular Expression Objects\\n\\nMatch Objects\\n\\nRegular Expression Examples\\n\\nChecking for a Pair\\n\\nSimulating scanf()\\n\\nsearch() vs. prefixmatch()\\n\\nprefixmatch() vs. match()\\n\\nMaking a Phonebook\\n\\nText Munging\\n\\nFinding all Adverbs\\n\\nFinding all Adverbs and their Positions\\n\\nRaw String Notation\\n\\nWriting a Tokenizer\\n\\ndifflib — Helpers for computing deltas\\n\\nSequenceMatcher Objects\\n\\nSequenceMatcher Examples\\n\\nDiffer Objects\\n\\nDiffer Example\\n\\nA command-line interface to difflib\\n\\nndiff example\\n\\ntextwrap — Text wrapping and filling\\n\\nunicodedata — Unicode Database\\n\\nstringprep — Internet String Preparation\\n\\nreadline — GNU readline interface\\n\\nInit file\\n\\nLine buffer\\n\\nHistory file\\n\\nHistory list\\n\\nStartup hooks\\n\\nCompletion\\n\\nExample\\n\\nrlcompleter — Completion function for GNU readline\\n\\nPrevious topic\\n\\nThread Safety Guarantees\\n\\nNext topic\\n\\nstring — Common string operations\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nText Processing Services\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\textwrap.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nText Processing Services »\\n\\ntextwrap — Text wrapping and filling\\n\\n|\\n\\ntextwrap — Text wrapping and filling¶\\n\\nSource code: Lib/textwrap.py\\n\\nThe textwrap module provides some convenience functions, as well as 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 TextWrapper for efficiency.\\n\\nwrap(), fill() and shorten() work by creating a TextWrapper instance and calling a single method on it. That instance is not reused, so for applications that process many text strings using wrap() and/or fill(), it may be more efficient to create your own TextWrapper object.\\n\\nText is preferably wrapped on whitespaces and right after the hyphens in hyphenated words; only then will long words be broken if necessary, unless TextWrapper.break_long_words is set to false.\\n\\nPrevious topic\\n\\ndifflib — Helpers for computing deltas\\n\\nNext topic\\n\\nunicodedata — Unicode Database\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nText Processing Services »\\n\\ntextwrap — Text wrapping and filling\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\threading.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nConcurrent Execution »\\n\\nthreading — Thread-based parallelism\\n\\n|\\n\\nthreading — Thread-based parallelism¶\\n\\nSource code: Lib/threading.py\\n\\nThis module constructs higher-level threading interfaces on top of the lower level _thread module.\\n\\nAvailability: not WASI.\\n\\nThis module does not work or is not available on WebAssembly. See WebAssembly platforms for more information.\\n\\nIntroduction¶\\n\\nThe threading module provides a way to run multiple threads (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.\\n\\nA typical use case for 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 Thread:\\n\\nimport threading\\nimport time\\n\\ndef crawl(link, delay=3):\\n print(f\"crawl started for {link}\")\\n time.sleep(delay) # Blocking I/O (simulating a network request)\\n print(f\"crawl ended for {link}\")\\n\\nlinks = [\\n \"https://python.org\",\\n \"https://docs.python.org\",\\n \"https://peps.python.org\",\\n]\\n\\n# Start threads for each link\\nthreads = []\\nfor link in links:\\n # Using `args` to pass positional arguments and `kwargs` for keyword arguments\\n t = threading.Thread(target=crawl, args=(link,), kwargs={\"delay\": 2})\\n threads.append(t)\\n\\n# Start each thread\\nfor t in threads:\\n t.start()\\n\\n# Wait for all threads to finish\\nfor t in threads:\\n t.join()\\n\\nChanged in version 3.7: This module used to be optional, it is now always available.\\n\\nSee also\\n\\nconcurrent.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.\\n\\nqueue provides a thread-safe interface for exchanging data between running threads.\\n\\nasyncio offers an alternative approach to achieving task level concurrency without requiring the use of multiple operating system threads.\\n\\nNote\\n\\nIn the Python 2.x series, this module contained 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.\\n\\nCPython implementation detail: In CPython, due to the Global Interpreter Lock, only one thread can execute Python code at once (even though certain performance-oriented libraries might overcome this limitation). If you want your application to make better use of the computational resources of multi-core machines, you are advised to use multiprocessing or concurrent.futures.ProcessPoolExecutor. However, threading is still an appropriate model if you want to run multiple I/O-bound tasks simultaneously.\\n\\nGIL and performance considerations¶\\n\\nUnlike the multiprocessing module, which uses separate processes to bypass the 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.\\n\\nAs of Python 3.13, free-threaded builds can disable the GIL, enabling true parallel execution of threads, but this feature is not available by default (see PEP 703).\\n\\nReference¶\\n\\nThis module defines the following functions:\\n\\nThis module also defines the following constant:\\n\\nThis module defines a number of classes, which are detailed in the sections below.\\n\\nThe design of this module is loosely based on Java’s threading model. However, where Java makes locks and condition variables basic behavior of every object, they are separate objects in Python. Python’s Thread class supports a subset of the behavior of Java’s Thread class; currently, there are no priorities, no thread groups, and threads cannot be destroyed, stopped, suspended, resumed, or interrupted. The static methods of Java’s Thread class, when implemented, are mapped to module-level functions.\\n\\nAll of the methods described below are executed atomically.\\n\\nThread-local data¶\\n\\nThread-local data is data whose values are thread specific. If you have data that you want to be local to a thread, create a local object and use its attributes:\\n\\n>>> mydata = local()\\n>>> mydata.number = 42\\n>>> mydata.number\\n42\\n\\nYou can also access the local-object’s dictionary:\\n\\n>>> mydata.__dict__\\n{\\'number\\': 42}\\n>>> mydata.__dict__.setdefault(\\'widgets\\', [])\\n[]\\n>>> mydata.widgets\\n[]\\n\\nIf we access the data in a different thread:\\n\\n>>> log = []\\n>>> def f():\\n... items = sorted(mydata.__dict__.items())\\n... log.append(items)\\n... mydata.number = 11\\n... log.append(mydata.number)\\n\\n>>> import threading\\n>>> thread = threading.Thread(target=f)\\n>>> thread.start()\\n>>> thread.join()\\n>>> log\\n[[], 11]\\n\\nwe get different data. Furthermore, changes made in the other thread don’t affect data seen in this thread:\\n\\n>>> mydata.number\\n42\\n\\nOf course, values you get from a local object, including their __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.\\n\\nYou can create custom local objects by subclassing the local class:\\n\\n>>> class MyLocal(local):\\n... number = 2\\n... def __init__(self, /, **kw):\\n... self.__dict__.update(kw)\\n... def squared(self):\\n... return self.number ** 2\\n\\nThis can be useful to support default values, methods and initialization. Note that if you define an __init__() method, it will be called each time the local object is used in a separate thread. This is necessary to initialize each thread’s dictionary.\\n\\nNow if we create a local object:\\n\\n>>> mydata = MyLocal(color=\\'red\\')\\n\\nwe have a default number:\\n\\n>>> mydata.number\\n2\\n\\nan initial color:\\n\\n>>> mydata.color\\n\\'red\\'\\n>>> del mydata.color\\n\\nAnd a method that operates on the data:\\n\\n>>> mydata.squared()\\n4\\n\\nAs before, we can access the data in a separate thread:\\n\\n>>> log = []\\n>>> thread = threading.Thread(target=f)\\n>>> thread.start()\\n>>> thread.join()\\n>>> log\\n[[(\\'color\\', \\'red\\')], 11]\\n\\nwithout affecting this thread’s data:\\n\\n>>> mydata.number\\n2\\n>>> mydata.color\\nTraceback (most recent call last):\\n...\\nAttributeError: \\'MyLocal\\' object has no attribute \\'color\\'\\n\\nNote that subclasses can define __slots__, but they are not thread local. They are shared across threads:\\n\\n>>> class MyLocal(local):\\n... __slots__ = \\'number\\'\\n\\n>>> mydata = MyLocal()\\n>>> mydata.number = 42\\n>>> mydata.color = \\'red\\'\\n\\nSo, the separate thread:\\n\\n>>> thread = threading.Thread(target=f)\\n>>> thread.start()\\n>>> thread.join()\\n\\naffects what we see:\\n\\n>>> mydata.number\\n11\\n\\nThread objects¶\\n\\nThe 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 run() method in a subclass. No other methods (except for the constructor) should be overridden in a subclass. In other words, only override the __init__() and run() methods of this class.\\n\\nOnce a thread object is created, its activity must be started by calling the thread’s start() method. This invokes the run() method in a separate thread of control.\\n\\nOnce the thread’s activity is started, the thread is considered ‘alive’. It stops being alive when its run() method terminates – either normally, or by raising an unhandled exception. The is_alive() method tests whether the thread is alive.\\n\\nOther threads can call a thread’s join() method. This blocks the calling thread until the thread whose join() method is called is terminated.\\n\\nA thread has a name. The name can be passed to the constructor, and read or changed through the name attribute.\\n\\nIf the run() method raises an exception, threading.excepthook() is called to handle it. By default, threading.excepthook() ignores silently SystemExit.\\n\\nA thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. The flag can be set through the daemon property or the daemon constructor argument.\\n\\nNote\\n\\nDaemon threads are abruptly stopped at shutdown. Their resources (such as open files, database transactions, etc.) may not be released properly. If you want your threads to stop gracefully, make them non-daemonic and use a suitable signalling mechanism such as an Event.\\n\\nThere is a “main thread” object; this corresponds to the initial thread of control in the Python program. It is not a daemon thread.\\n\\nThere is the possibility that “dummy thread objects” are created. These are thread objects corresponding to “alien threads”, which are threads of control started outside the threading module, such as directly from C code. Dummy thread objects have limited functionality; they are always considered alive and daemonic, and cannot be joined. They are never deleted, since it is impossible to detect the termination of alien threads.\\n\\nLock objects¶\\n\\nA primitive lock is a synchronization primitive that is not owned by a particular thread when locked. In Python, it is currently the lowest level synchronization primitive available, implemented directly by the _thread extension module.\\n\\nA primitive lock is in one of two states, “locked” or “unlocked”. It is created in the unlocked state. It has two basic methods, acquire() and release(). When the state is unlocked, acquire() changes the state to locked and returns immediately. When the state is locked, acquire() blocks until a call to release() in another thread changes it to unlocked, then the acquire() call resets it to locked and returns. The release() method should only be called in the locked state; it changes the state to unlocked and returns immediately. If an attempt is made to release an unlocked lock, a RuntimeError will be raised.\\n\\nLocks also support the context management protocol.\\n\\nWhen more than one thread is blocked in acquire() waiting for the state to turn to unlocked, only one thread proceeds when a release() call resets the state to unlocked; which one of the waiting threads proceeds is not defined, and may vary across implementations.\\n\\nAll methods are executed atomically.\\n\\nRLock objects¶\\n\\nA reentrant lock is a synchronization primitive that may be acquired multiple times by the same thread. Internally, it uses the concepts of “owning thread” and “recursion level” in addition to the locked/unlocked state used by primitive locks. In the locked state, some thread owns the lock; in the unlocked state, no thread owns it.\\n\\nThreads call a lock’s acquire() method to lock it, and its release() method to unlock it.\\n\\nNote\\n\\nReentrant locks support the context management protocol, so it is recommended to use with instead of manually calling acquire() and release() to handle acquiring and releasing the lock for a block of code.\\n\\nRLock’s acquire()/release() call pairs may be nested, unlike Lock’s acquire()/release(). Only the final release() (the release() of the outermost pair) resets the lock to an unlocked state and allows another thread blocked in acquire() to proceed.\\n\\nacquire()/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.\\n\\nCondition objects¶\\n\\nA condition variable is always associated with some kind of lock; this can be passed in or one will be created by default. Passing one in is useful when several condition variables must share the same lock. The lock is part of the condition object: you don’t have to track it separately.\\n\\nA condition variable obeys the context management protocol: using the with statement acquires the associated lock for the duration of the enclosed block. The acquire() and release() methods also call the corresponding methods of the associated lock.\\n\\nOther methods must be called with the associated lock held. The wait() method releases the lock, and then blocks until another thread awakens it by calling notify() or notify_all(). Once awakened, wait() re-acquires the lock and returns. It is also possible to specify a timeout.\\n\\nThe notify() method wakes up one of the threads waiting for the condition variable, if any are waiting. The notify_all() method wakes up all threads waiting for the condition variable.\\n\\nNote: the notify() and notify_all() methods don’t release the lock; this means that the thread or threads awakened will not return from their wait() call immediately, but only when the thread that called notify() or notify_all() finally relinquishes ownership of the lock.\\n\\nThe typical programming style using condition variables uses the lock to synchronize access to some shared state; threads that are interested in a particular change of state call wait() repeatedly until they see the desired state, while threads that modify the state call notify() or notify_all() when they change the state in such a way that it could possibly be a desired state for one of the waiters. For example, the following code is a generic producer-consumer situation with unlimited buffer capacity:\\n\\n# Consume one item\\nwith cv:\\n while not an_item_is_available():\\n cv.wait()\\n get_an_available_item()\\n\\n# Produce one item\\nwith cv:\\n make_an_item_available()\\n cv.notify()\\n\\nThe while loop checking for the application’s condition is necessary because wait() can return after an arbitrary long time, and the condition which prompted the notify() call may no longer hold true. This is inherent to multi-threaded programming. The wait_for() method can be used to automate the condition checking, and eases the computation of timeouts:\\n\\n# Consume an item\\nwith cv:\\n cv.wait_for(an_item_is_available)\\n get_an_available_item()\\n\\nTo choose between notify() and notify_all(), consider whether one state change can be interesting for only one or several waiting threads. E.g. in a typical producer-consumer situation, adding one item to the buffer only needs to wake up one consumer thread.\\n\\nSemaphore objects¶\\n\\nThis is one of the oldest synchronization primitives in the history of computer science, invented by the early Dutch computer scientist Edsger W. Dijkstra (he used the names P() and V() instead of acquire() and release()).\\n\\nA semaphore manages an internal counter which is decremented by each acquire() call and incremented by each release() call. The counter can never go below zero; when acquire() finds that it is zero, it blocks, waiting until some other thread calls release().\\n\\nSemaphores also support the context management protocol.\\n\\nSemaphore example¶\\n\\nSemaphores are often used to guard resources with limited capacity, for example, a database server. In any situation where the size of the resource is fixed, you should use a bounded semaphore. Before spawning any worker threads, your main thread would initialize the semaphore:\\n\\nmaxconnections = 5\\n# ...\\npool_sema = BoundedSemaphore(value=maxconnections)\\n\\nOnce spawned, worker threads call the semaphore’s acquire and release methods when they need to connect to the server:\\n\\nwith pool_sema:\\n conn = connectdb()\\n try:\\n # ... use connection ...\\n finally:\\n conn.close()\\n\\nThe use of a bounded semaphore reduces the chance that a programming error which causes the semaphore to be released more than it’s acquired will go undetected.\\n\\nEvent objects¶\\n\\nThis is one of the simplest mechanisms for communication between threads: one thread signals an event and other threads wait for it.\\n\\nAn event object manages an internal flag that can be set to true with the set() method and reset to false with the clear() method. The wait() method blocks until the flag is true.\\n\\nTimer objects¶\\n\\nThis class represents an action that should be run only after a certain amount of time has passed — a timer. Timer is a subclass of Thread and as such also functions as an example of creating custom threads.\\n\\nTimers are started, as with threads, by calling their Timer.start method. The timer can be stopped (before its action has begun) by calling the 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.\\n\\nFor example:\\n\\ndef hello():\\n print(\"hello, world\")\\n\\nt = Timer(30.0, hello)\\nt.start() # after 30 seconds, \"hello, world\" will be printed\\n\\nBarrier objects¶\\n\\nAdded in version 3.2.\\n\\nThis class provides a simple synchronization primitive for use by a fixed number of threads that need to wait for each other. Each of the threads tries to pass the barrier by calling the wait() method and will block until all of the threads have made their wait() calls. At this point, the threads are released simultaneously.\\n\\nThe barrier can be reused any number of times for the same number of threads.\\n\\nAs an example, here is a simple way to synchronize a client and server thread:\\n\\nb = Barrier(2, timeout=5)\\n\\ndef server():\\n start_server()\\n b.wait()\\n while True:\\n connection = accept_connection()\\n process_server_connection(connection)\\n\\ndef client():\\n b.wait()\\n while True:\\n connection = make_connection()\\n process_client_connection(connection)\\n\\nUsing locks, conditions, and semaphores in the with statement¶\\n\\nAll of the objects provided by this module that have acquire and release methods can be used as context managers for a with statement. The acquire method will be called when the block is entered, and release will be called when the block is exited. Hence, the following snippet:\\n\\nwith some_lock:\\n # do something...\\n\\nis equivalent to:\\n\\nsome_lock.acquire()\\ntry:\\n # do something...\\nfinally:\\n some_lock.release()\\n\\nCurrently, Lock, RLock, Condition, Semaphore, and BoundedSemaphore objects may be used as with statement context managers.\\n\\nTable of Contents\\n\\nthreading — Thread-based parallelism\\n\\nIntroduction\\n\\nGIL and performance considerations\\n\\nReference\\n\\nThread-local data\\n\\nThread objects\\n\\nLock objects\\n\\nRLock objects\\n\\nCondition objects\\n\\nSemaphore objects\\n\\nSemaphore example\\n\\nEvent objects\\n\\nTimer objects\\n\\nBarrier objects\\n\\nUsing locks, conditions, and semaphores in the with statement\\n\\nPrevious topic\\n\\nConcurrent Execution\\n\\nNext topic\\n\\nmultiprocessing — Process-based parallelism\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nConcurrent Execution »\\n\\nthreading — Thread-based parallelism\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\threadsafety.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nThread Safety Guarantees\\n\\n|\\n\\nThread Safety Guarantees¶\\n\\nThis page documents thread-safety guarantees for built-in types in Python’s free-threaded build. The guarantees described here apply when using Python with the GIL disabled (free-threaded mode). When the GIL is enabled, most operations are implicitly serialized.\\n\\nFor general guidance on writing thread-safe code in free-threaded Python, see Python support for free threading.\\n\\nThread safety for list objects¶\\n\\nReading a single element from a list is atomic:\\n\\nlst[i] # list.__getitem__\\n\\nThe following methods traverse the list and use atomic reads of each item to perform their function. That means that they may return results affected by concurrent modifications:\\n\\nitem in lst\\nlst.index(item)\\nlst.count(item)\\n\\nAll of the above operations avoid acquiring per-object locks. They do not block concurrent modifications. Other operations that hold a lock will not block these from observing intermediate states.\\n\\nAll other operations from here on block using the per-object lock.\\n\\nWriting a single item via lst[i] = x is safe to call from multiple threads and will not corrupt the list.\\n\\nThe following operations return new objects and appear atomic to other threads:\\n\\nlst1 + lst2 # concatenates two lists into a new list\\nx * lst # repeats lst x times into a new list\\nlst.copy() # returns a shallow copy of the list\\n\\nThe following methods that only operate on a single element with no shifting required are atomic:\\n\\nlst.append(x) # append to the end of the list, no shifting required\\nlst.pop() # pop element from the end of the list, no shifting required\\n\\nThe clear() method is also atomic. Other threads cannot observe elements being removed.\\n\\nThe sort() method is not atomic. Other threads cannot observe intermediate states during sorting, but the list appears empty for the duration of the sort.\\n\\nThe following operations may allow lock-free operations to observe intermediate states since they modify multiple elements in place:\\n\\nlst.insert(idx, item) # shifts elements\\nlst.pop(idx) # idx not at the end of the list, shifts elements\\nlst *= x # copies elements in place\\n\\nThe remove() method may allow concurrent modifications since element comparison may execute arbitrary Python code (via __eq__()).\\n\\nextend() is safe to call from multiple threads. However, its guarantees depend on the iterable passed to it. If it is a list, a tuple, a set, a frozenset, a dict or a dictionary view object (but not their subclasses), the 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 lst += iterable.\\n\\nSimilarly, assigning to a list slice with lst[i:j] = iterable is safe to call from multiple threads, but iterable is only locked when it is also a list (but not its subclasses).\\n\\nOperations that involve multiple accesses, as well as iteration, are never atomic. For example:\\n\\n# NOT atomic: read-modify-write\\nlst[i] = lst[i] + 1\\n\\n# NOT atomic: check-then-act\\nif lst:\\n item = lst.pop()\\n\\n# NOT thread-safe: iteration while modifying\\nfor item in lst:\\n process(item) # another thread may modify lst\\n\\nConsider external synchronization when sharing list instances across threads.\\n\\nThread safety for dict objects¶\\n\\nCreating a dictionary with the dict constructor is atomic when the argument to it is a dict or a tuple. When using the dict.fromkeys() method, dictionary creation is atomic when the argument is a dict, tuple, set or frozenset.\\n\\nThe following operations and functions are lock-free and atomic.\\n\\nd[key] # dict.__getitem__\\nd.get(key) # dict.get\\nkey in d # dict.__contains__\\nlen(d) # dict.__len__\\n\\nAll other operations from here on hold the per-object lock.\\n\\nWriting or removing a single item is safe to call from multiple threads and will not corrupt the dictionary:\\n\\nd[key] = value # write\\ndel d[key] # delete\\nd.pop(key) # remove and return\\nd.popitem() # remove and return last item\\nd.setdefault(key, v) # insert if missing\\n\\nThese operations may compare keys using __eq__(), which can execute arbitrary Python code. During such comparisons, the dictionary may be modified by another thread. For built-in types like str, int, and float, that implement __eq__() in C, the underlying lock is not released during comparisons and this is not a concern.\\n\\nThe following operations return new objects and hold the per-object lock for the duration of the operation:\\n\\nd.copy() # returns a shallow copy of the dictionary\\nd | other # merges two dicts into a new dict\\nd.keys() # returns a new dict_keys view object\\nd.values() # returns a new dict_values view object\\nd.items() # returns a new dict_items view object\\n\\nThe clear() method holds the lock for its duration. Other threads cannot observe elements being removed.\\n\\nThe following operations lock both dictionaries. For update() and |=, this applies only when the other operand is a dict that uses the standard dict iterator (but not subclasses that override iteration). For equality comparison, this applies to dict and its subclasses:\\n\\nd.update(other_dict) # both locked when other_dict is a dict\\nd |= other_dict # both locked when other_dict is a dict\\nd == other_dict # both locked for dict and subclasses\\n\\nAll comparison operations also compare values using __eq__(), so for non-built-in types the lock may be released during comparison.\\n\\nfromkeys() locks both the new dictionary and the iterable when the iterable is exactly a dict, set, or frozenset (not subclasses):\\n\\ndict.fromkeys(a_dict) # locks both\\ndict.fromkeys(a_set) # locks both\\ndict.fromkeys(a_frozenset) # locks both\\n\\nWhen updating from a non-dict iterable, only the target dictionary is locked. The iterable may be concurrently modified by another thread:\\n\\nd.update(iterable) # iterable is not a dict: only d locked\\nd |= iterable # iterable is not a dict: only d locked\\ndict.fromkeys(iterable) # iterable is not a dict/set/frozenset: only result locked\\n\\nOperations that involve multiple accesses, as well as iteration, are never atomic:\\n\\n# NOT atomic: read-modify-write\\nd[key] = d[key] + 1\\n\\n# NOT atomic: check-then-act (TOCTOU)\\nif key in d:\\n del d[key]\\n\\n# NOT thread-safe: iteration while modifying\\nfor key, value in d.items():\\n process(key) # another thread may modify d\\n\\nTo avoid time-of-check to time-of-use (TOCTOU) issues, use atomic operations or handle exceptions:\\n\\n# Use pop() with default instead of check-then-delete\\nd.pop(key, None)\\n\\n# Or handle the exception\\ntry:\\n del d[key]\\nexcept KeyError:\\n pass\\n\\nTo safely iterate over a dictionary that may be modified by another thread, iterate over a copy:\\n\\n# Make a copy to iterate safely\\nfor key, value in d.copy().items():\\n process(key)\\n\\nConsider external synchronization when sharing dict instances across threads.\\n\\nTable of Contents\\n\\nThread Safety Guarantees\\n\\nThread safety for list objects\\n\\nThread safety for dict objects\\n\\nPrevious topic\\n\\nBuilt-in Exceptions\\n\\nNext topic\\n\\nText Processing Services\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nThread Safety Guarantees\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\time.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nGeneric Operating System Services »\\n\\ntime — Time access and conversions\\n\\n|\\n\\ntime — Time access and conversions¶\\n\\nThis module provides various time-related functions. For related functionality, see also the datetime and calendar modules.\\n\\nAlthough this module is always available, not all functions are available on all platforms. Most of the functions defined in this module call platform C library functions with the same name. It may sometimes be helpful to consult the platform documentation, because the semantics of these functions varies among platforms.\\n\\nAn explanation of some terminology and conventions is in order.\\n\\nThe epoch is the point where the time starts, the return value of time.gmtime(0). It is January 1, 1970, 00:00:00 (UTC) on all platforms.\\n\\nThe term seconds since the epoch refers to the total number of elapsed seconds since the epoch, typically excluding leap seconds. Leap seconds are excluded from this total on all POSIX-compliant platforms.\\n\\nThe functions in this module may not handle dates and times before the epoch or far in the future. The cut-off point in the future is determined by the C library; for 32-bit systems, it is typically in 2038.\\n\\nFunction strptime() can parse 2-digit years when given %y format code. When 2-digit years are parsed, they are converted according to the POSIX and ISO C standards: values 69–99 are mapped to 1969–1999, and values 0–68 are mapped to 2000–2068.\\n\\nUTC is Coordinated Universal Time and superseded 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.\\n\\nDST is Daylight Saving Time, an adjustment of the timezone by (usually) one hour during part of the year. DST rules are magic (determined by local law) and can change from year to year. The C library has a table containing the local rules (often it is read from a system file for flexibility) and is the only source of True Wisdom in this respect.\\n\\nThe precision of the various real-time functions may be less than suggested by the units in which their value or argument is expressed. E.g. on most Unix systems, the clock “ticks” only 50 or 100 times a second.\\n\\nOn the other hand, the precision of time() and sleep() is better than their Unix equivalents: times are expressed as floating-point numbers, time() returns the most accurate time available (using Unix gettimeofday() where available), and sleep() will accept a time with a nonzero fraction (Unix select() is used to implement this, where available).\\n\\nThe time value as returned by gmtime(), localtime(), and strptime(), and accepted by asctime(), mktime() and strftime(), is a sequence of 9 integers. The return values of gmtime(), localtime(), and strptime() also offer attribute names for individual fields.\\n\\nSee struct_time for a description of these objects.\\n\\nChanged in version 3.3: The struct_time type was extended to provide the tm_gmtoff and tm_zone attributes when platform supports corresponding struct tm members.\\n\\nChanged in version 3.6: The struct_time attributes tm_gmtoff and tm_zone are now available on all platforms.\\n\\nUse the following functions to convert between time representations:\\n\\nFrom To Use seconds since the epoch struct_time in\\nUTC gmtime() seconds since the epoch struct_time in\\nlocal time localtime() struct_time in\\nUTC seconds since the epoch calendar.timegm() struct_time in\\nlocal time seconds since the epoch mktime()\\n\\nFunctions¶\\n\\nChanged in version 3.13: On Windows, calls GetSystemTimePreciseAsFileTime() instead of GetSystemTimeAsFileTime().\\n\\nClock ID Constants¶\\n\\nThese constants are used as parameters for clock_getres() and clock_gettime().\\n\\nThe following constant is the only parameter that can be sent to clock_settime().\\n\\nTimezone Constants¶\\n\\nNote\\n\\nFor the above Timezone constants (altzone, daylight, timezone, and tzname), the value is determined by the timezone rules in effect at module load time or the last time tzset() is called and may be incorrect for times in the past. It is recommended to use the tm_gmtoff and tm_zone results from localtime() to obtain timezone information.\\n\\nSee also\\n\\nFootnotes\\n\\n[1] (1,2,3)\\n\\nThe use of %Z is now deprecated, but the %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 RFC 822 standard calls for a two-digit year (%y rather than %Y), but practice moved to 4-digit years long before the year 2000. After that, RFC 822 became obsolete and the 4-digit year has been first recommended by RFC 1123 and then mandated by RFC 2822, with RFC 5322 continuing this requirement.\\n\\nTable of Contents\\n\\ntime — Time access and conversions\\n\\nFunctions\\n\\nClock ID Constants\\n\\nTimezone Constants\\n\\nPrevious topic\\n\\nio — Core tools for working with streams\\n\\nNext topic\\n\\nlogging — Logging facility for Python\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nGeneric Operating System Services »\\n\\ntime — Time access and conversions\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\timeit.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nDebugging and profiling »\\n\\ntimeit — Measure execution time of small code snippets\\n\\n|\\n\\ntimeit — Measure execution time of small code snippets¶\\n\\nSource code: Lib/timeit.py\\n\\nThis module provides a simple way to time small bits of Python code. It has both a Command-Line Interface as well as a callable one. It avoids a number of common traps for measuring execution times. See also Tim Peters’ introduction to the “Algorithms” chapter in the second edition of Python Cookbook, published by O’Reilly.\\n\\nBasic Examples¶\\n\\nThe following example shows how the Command-Line Interface can be used to compare three different expressions:\\n\\n$ python -m timeit \"\\'-\\'.join(str(n) for n in range(100))\"\\n10000 loops, best of 5: 30.2 usec per loop\\n$ python -m timeit \"\\'-\\'.join([str(n) for n in range(100)])\"\\n10000 loops, best of 5: 27.5 usec per loop\\n$ python -m timeit \"\\'-\\'.join(map(str, range(100)))\"\\n10000 loops, best of 5: 23.2 usec per loop\\n\\nThis can be achieved from the Python Interface with:\\n\\n>>> import timeit\\n>>> timeit.timeit(\\'\"-\".join(str(n) for n in range(100))\\', number=10000)\\n0.3018611848820001\\n>>> timeit.timeit(\\'\"-\".join([str(n) for n in range(100)])\\', number=10000)\\n0.2727368790656328\\n>>> timeit.timeit(\\'\"-\".join(map(str, range(100)))\\', number=10000)\\n0.23702679807320237\\n\\nA callable can also be passed from the Python Interface:\\n\\n>>> timeit.timeit(lambda: \"-\".join(map(str, range(100))), number=10000)\\n0.19665591977536678\\n\\nNote however that timeit() will automatically determine the number of repetitions only when the command-line interface is used. In the Examples section you can find more advanced examples.\\n\\nPython Interface¶\\n\\nThe module defines three convenience functions and a public class:\\n\\nCommand-Line Interface¶\\n\\nWhen called as a program from the command line, the following form is used:\\n\\npython -m timeit [-n N] [-r N] [-u U] [-s S] [-p] [-v] [-h] [statement ...]\\n\\nWhere the following options are understood:\\n\\nA multi-line statement may be given by specifying each line as a separate statement argument; indented lines are possible by enclosing an argument in quotes and using leading spaces. Multiple -s options are treated similarly.\\n\\nIf -n is not given, a suitable number of loops is calculated by trying increasing numbers from the sequence 1, 2, 5, 10, 20, 50, … until the total time is at least 0.2 seconds.\\n\\ndefault_timer() measurements can be affected by other programs running on the same machine, so the best thing to do when accurate timing is necessary is to repeat the timing a few times and use the best time. The -r option is good for this; the default of 5 repetitions is probably enough in most cases. You can use time.process_time() to measure CPU time.\\n\\nNote\\n\\nThere is a certain baseline overhead associated with executing a pass statement. The code here doesn’t try to hide it, but you should be aware of it. The baseline overhead can be measured by invoking the program without arguments, and it might differ between Python versions.\\n\\nExamples¶\\n\\nIt is possible to provide a setup statement that is executed only once at the beginning:\\n\\n$ python -m timeit -s \"text = \\'sample string\\'; char = \\'g\\'\" \"char in text\"\\n5000000 loops, best of 5: 0.0877 usec per loop\\n$ python -m timeit -s \"text = \\'sample string\\'; char = \\'g\\'\" \"text.find(char)\"\\n1000000 loops, best of 5: 0.342 usec per loop\\n\\nIn the output, there are three fields. The loop count, which tells you how many times the statement body was run per timing loop repetition. The repetition count (‘best of 5’) which tells you how many times the timing loop was repeated, and finally the time the statement body took on average within the best repetition of the timing loop. That is, the time the fastest repetition took divided by the loop count.\\n\\n>>> import timeit\\n>>> timeit.timeit(\\'char in text\\', setup=\\'text = \"sample string\"; char = \"g\"\\')\\n0.41440500499993504\\n>>> timeit.timeit(\\'text.find(char)\\', setup=\\'text = \"sample string\"; char = \"g\"\\')\\n1.7246671520006203\\n\\nThe same can be done using the Timer class and its methods:\\n\\n>>> import timeit\\n>>> t = timeit.Timer(\\'char in text\\', setup=\\'text = \"sample string\"; char = \"g\"\\')\\n>>> t.timeit()\\n0.3955516149999312\\n>>> t.repeat()\\n[0.40183617287970225, 0.37027556854118704, 0.38344867356679524, 0.3712595970846668, 0.37866875250654886]\\n\\nThe following examples show how to time expressions that contain multiple lines. Here we compare the cost of using hasattr() vs. try/except to test for missing and present object attributes:\\n\\n$ python -m timeit \"try:\" \" str.__bool__\" \"except AttributeError:\" \" pass\"\\n20000 loops, best of 5: 15.7 usec per loop\\n$ python -m timeit \"if hasattr(str, \\'__bool__\\'): pass\"\\n50000 loops, best of 5: 4.26 usec per loop\\n\\n$ python -m timeit \"try:\" \" int.__bool__\" \"except AttributeError:\" \" pass\"\\n200000 loops, best of 5: 1.43 usec per loop\\n$ python -m timeit \"if hasattr(int, \\'__bool__\\'): pass\"\\n100000 loops, best of 5: 2.23 usec per loop\\n\\n>>> import timeit\\n>>> # attribute is missing\\n>>> s = \"\"\"\\\\\\n... try:\\n... str.__bool__\\n... except AttributeError:\\n... pass\\n... \"\"\"\\n>>> timeit.timeit(stmt=s, number=100000)\\n0.9138244460009446\\n>>> s = \"if hasattr(str, \\'__bool__\\'): pass\"\\n>>> timeit.timeit(stmt=s, number=100000)\\n0.5829014980008651\\n>>>\\n>>> # attribute is present\\n>>> s = \"\"\"\\\\\\n... try:\\n... int.__bool__\\n... except AttributeError:\\n... pass\\n... \"\"\"\\n>>> timeit.timeit(stmt=s, number=100000)\\n0.04215312199994514\\n>>> s = \"if hasattr(int, \\'__bool__\\'): pass\"\\n>>> timeit.timeit(stmt=s, number=100000)\\n0.08588060699912603\\n\\nTo give the timeit module access to functions you define, you can pass a setup parameter which contains an import statement:\\n\\ndef test():\\n \"\"\"Stupid test function\"\"\"\\n L = [i for i in range(100)]\\n\\nif __name__ == \\'__main__\\':\\n import timeit\\n print(timeit.timeit(\"test()\", setup=\"from __main__ import test\"))\\n\\nAnother option is to pass globals() to the globals parameter, which will cause the code to be executed within your current global namespace. This can be more convenient than individually specifying imports:\\n\\ndef f(x):\\n return x**2\\ndef g(x):\\n return x**4\\ndef h(x):\\n return x**8\\n\\nimport timeit\\nprint(timeit.timeit(\\'[func(42) for func in (f,g,h)]\\', globals=globals()))\\n\\nTable of Contents\\n\\ntimeit — Measure execution time of small code snippets\\n\\nBasic Examples\\n\\nPython Interface\\n\\nCommand-Line Interface\\n\\nExamples\\n\\nPrevious topic\\n\\npstats — Statistics for profilers\\n\\nNext topic\\n\\ntrace — Trace or track Python statement execution\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nDebugging and profiling »\\n\\ntimeit — Measure execution time of small code snippets\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\tk.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nGraphical user interfaces with Tk\\n\\n|\\n\\nGraphical user interfaces with Tk¶\\n\\nTk/Tcl has long been an integral part of Python. It provides a robust and platform independent windowing toolkit, that is available to Python programmers using the tkinter package, and its extension, the tkinter.ttk module.\\n\\nThe tkinter package is a thin object-oriented layer on top of Tcl/Tk. To use tkinter, you don’t need to write Tcl code, but you will need to consult the Tk documentation, and occasionally the Tcl documentation. tkinter is a set of wrappers that implement the Tk widgets as Python classes.\\n\\ntkinter’s chief virtues are that it is fast, and that it usually comes bundled with Python. Although its standard documentation is weak, good material is available, which includes: references, tutorials, a book and others. tkinter is also famous for having an outdated look and feel, which has been vastly improved in Tk 8.5. Nevertheless, there are many other GUI libraries that you could be interested in. The Python wiki lists several alternative GUI frameworks and tools.\\n\\ntkinter — Python interface to Tcl/Tk\\n\\nArchitecture\\n\\nTkinter Modules\\n\\nTkinter Life Preserver\\n\\nA Hello World Program\\n\\nImportant Tk Concepts\\n\\nUnderstanding How Tkinter Wraps Tcl/Tk\\n\\nHow do I…? What option does…?\\n\\nNavigating the Tcl/Tk Reference Manual\\n\\nThreading model\\n\\nHandy Reference\\n\\nSetting Options\\n\\nThe Packer\\n\\nPacker Options\\n\\nCoupling Widget Variables\\n\\nThe Window Manager\\n\\nTk Option Data Types\\n\\nBindings and Events\\n\\nThe index Parameter\\n\\nImages\\n\\nFile Handlers\\n\\ntkinter.colorchooser — Color choosing dialog\\n\\ntkinter.font — Tkinter font wrapper\\n\\nTkinter Dialogs\\n\\ntkinter.simpledialog — Standard Tkinter input dialogs\\n\\ntkinter.filedialog — File selection dialogs\\n\\nNative Load/Save Dialogs\\n\\ntkinter.commondialog — Dialog window templates\\n\\ntkinter.messagebox — Tkinter message prompts\\n\\ntkinter.scrolledtext — Scrolled Text Widget\\n\\ntkinter.dnd — Drag and drop support\\n\\ntkinter.ttk — Tk themed widgets\\n\\nUsing Ttk\\n\\nTtk Widgets\\n\\nWidget\\n\\nStandard Options\\n\\nScrollable Widget Options\\n\\nLabel Options\\n\\nCompatibility Options\\n\\nWidget States\\n\\nttk.Widget\\n\\nCombobox\\n\\nOptions\\n\\nVirtual events\\n\\nttk.Combobox\\n\\nSpinbox\\n\\nOptions\\n\\nVirtual events\\n\\nttk.Spinbox\\n\\nNotebook\\n\\nOptions\\n\\nTab Options\\n\\nTab Identifiers\\n\\nVirtual Events\\n\\nttk.Notebook\\n\\nProgressbar\\n\\nOptions\\n\\nttk.Progressbar\\n\\nSeparator\\n\\nOptions\\n\\nSizegrip\\n\\nPlatform-specific notes\\n\\nBugs\\n\\nTreeview\\n\\nOptions\\n\\nItem Options\\n\\nTag Options\\n\\nColumn Identifiers\\n\\nVirtual Events\\n\\nttk.Treeview\\n\\nTtk Styling\\n\\nLayouts\\n\\nIDLE — Python editor and shell\\n\\nMenus\\n\\nFile menu (Shell and Editor)\\n\\nEdit menu (Shell and Editor)\\n\\nFormat menu (Editor window only)\\n\\nRun menu (Editor window only)\\n\\nShell menu (Shell window only)\\n\\nDebug menu (Shell window only)\\n\\nOptions menu (Shell and Editor)\\n\\nWindow menu (Shell and Editor)\\n\\nHelp menu (Shell and Editor)\\n\\nContext menus\\n\\nEditing and Navigation\\n\\nEditor windows\\n\\nKey bindings\\n\\nAutomatic indentation\\n\\nSearch and Replace\\n\\nCompletions\\n\\nCalltips\\n\\nFormat block\\n\\nCode Context\\n\\nShell window\\n\\nText colors\\n\\nStartup and Code Execution\\n\\nCommand-line usage\\n\\nStartup failure\\n\\nRunning user code\\n\\nUser output in Shell\\n\\nDeveloping tkinter applications\\n\\nRunning without a subprocess\\n\\nHelp and Preferences\\n\\nHelp sources\\n\\nSetting preferences\\n\\nIDLE on macOS\\n\\nExtensions\\n\\nidlelib — implementation of IDLE application\\n\\nturtle — Turtle graphics\\n\\nIntroduction\\n\\nGet started\\n\\nTutorial\\n\\nStarting a turtle environment\\n\\nBasic drawing\\n\\nPen control\\n\\nThe turtle’s position\\n\\nMaking algorithmic patterns\\n\\nHow to…\\n\\nGet started as quickly as possible\\n\\nAutomatically begin and end filling\\n\\nUse the turtle module namespace\\n\\nUse turtle graphics in a script\\n\\nUse object-oriented turtle graphics\\n\\nTurtle graphics reference\\n\\nTurtle methods\\n\\nMethods of TurtleScreen/Screen\\n\\nMethods of RawTurtle/Turtle and corresponding functions\\n\\nTurtle motion\\n\\nTell Turtle’s state\\n\\nSettings for measurement\\n\\nPen control\\n\\nDrawing state\\n\\nColor control\\n\\nFilling\\n\\nMore drawing control\\n\\nTurtle state\\n\\nVisibility\\n\\nAppearance\\n\\nUsing events\\n\\nSpecial Turtle methods\\n\\nCompound shapes\\n\\nMethods of TurtleScreen/Screen and corresponding functions\\n\\nWindow control\\n\\nAnimation control\\n\\nUsing screen events\\n\\nInput methods\\n\\nSettings and special methods\\n\\nMethods specific to Screen, not inherited from TurtleScreen\\n\\nPublic classes\\n\\nExplanation\\n\\nHelp and configuration\\n\\nHow to use help\\n\\nTranslation of docstrings into different languages\\n\\nHow to configure Screen and Turtles\\n\\nturtledemo — Demo scripts\\n\\nChanges since Python 2.6\\n\\nChanges since Python 3.0\\n\\nPrevious topic\\n\\nlocale — Internationalization services\\n\\nNext topic\\n\\ntkinter — Python interface to Tcl/Tk\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nGraphical user interfaces with Tk\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\tkinter.colorchooser.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nGraphical user interfaces with Tk »\\n\\ntkinter.colorchooser — Color choosing dialog\\n\\n|\\n\\ntkinter.colorchooser — Color choosing dialog¶\\n\\nSource code: Lib/tkinter/colorchooser.py\\n\\nThe tkinter.colorchooser module provides the Chooser class as an interface to the native color picker dialog. Chooser implements a modal color choosing dialog window. The Chooser class inherits from the Dialog class.\\n\\nSee also\\n\\nPrevious topic\\n\\ntkinter — Python interface to Tcl/Tk\\n\\nNext topic\\n\\ntkinter.font — Tkinter font wrapper\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nGraphical user interfaces with Tk »\\n\\ntkinter.colorchooser — Color choosing dialog\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\tkinter.dnd.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nGraphical user interfaces with Tk »\\n\\ntkinter.dnd — Drag and drop support\\n\\n|\\n\\ntkinter.dnd — Drag and drop support¶\\n\\nSource code: Lib/tkinter/dnd.py\\n\\nNote\\n\\nThis is experimental and due to be deprecated when it is replaced with the Tk DND.\\n\\nThe 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 Bindings and Events). The function should call 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).\\n\\nSelection of a target object occurs as follows:\\n\\nTop-down search of area under mouse for target widget\\n\\nTarget widget should have a callable dnd_accept attribute\\n\\nIf dnd_accept is not present or returns None, search moves to parent widget\\n\\nIf no target widget is found, then the target object is None\\n\\nCall to .dnd_leave(source, event)\\n\\nCall to .dnd_enter(source, event)\\n\\nCall to .dnd_commit(source, event) to notify of drop\\n\\nCall to .dnd_end(target, event) to signal end of drag-and-drop\\n\\nSee also\\n\\nBindings and Events\\n\\nPrevious topic\\n\\ntkinter.scrolledtext — Scrolled Text Widget\\n\\nNext topic\\n\\ntkinter.ttk — Tk themed widgets\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nGraphical user interfaces with Tk »\\n\\ntkinter.dnd — Drag and drop support\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\tkinter.font.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nGraphical user interfaces with Tk »\\n\\ntkinter.font — Tkinter font wrapper\\n\\n|\\n\\ntkinter.font — Tkinter font wrapper¶\\n\\nSource code: Lib/tkinter/font.py\\n\\nThe tkinter.font module provides the Font class for creating and using named fonts.\\n\\nThe different font weights and slants are:\\n\\nPrevious topic\\n\\ntkinter.colorchooser — Color choosing dialog\\n\\nNext topic\\n\\nTkinter Dialogs\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nGraphical user interfaces with Tk »\\n\\ntkinter.font — Tkinter font wrapper\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\tkinter.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nGraphical user interfaces with Tk »\\n\\ntkinter — Python interface to Tcl/Tk\\n\\n|\\n\\ntkinter — Python interface to Tcl/Tk¶\\n\\nSource code: Lib/tkinter/__init__.py\\n\\nThe tkinter package (“Tk interface”) is the standard Python interface to the Tcl/Tk GUI toolkit. Both Tk and tkinter are available on most Unix platforms, including macOS, as well as on Windows systems.\\n\\nRunning python -m tkinter from the command line should open a window demonstrating a simple Tk interface, letting you know that 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.\\n\\nTkinter 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 _tkinter module for more information about supported versions.\\n\\nTkinter 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.\\n\\nNote\\n\\nTcl/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.\\n\\nThis is an 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 Requirements for optional modules.\\n\\nSee also\\n\\nTcl/Tk Resources:\\n\\nBooks:\\n\\nArchitecture¶\\n\\nTcl/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.\\n\\nInternally, Tk and Ttk use facilities of the underlying operating system, i.e., Xlib on Unix/X11, Cocoa on macOS, GDI on Windows.\\n\\nWhen your Python application uses a class in Tkinter, e.g., to create a widget, the tkinter module first assembles a Tcl/Tk command string. It passes that Tcl command string to an internal _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.\\n\\nTkinter Modules¶\\n\\nSupport for Tkinter is spread across several modules. Most applications will need the main tkinter module, as well as the tkinter.ttk module, which provides the modern themed widget set and API:\\n\\nfrom tkinter import *\\nfrom tkinter import ttk\\n\\nThe modules that provide Tk support include:\\n\\nAdditional modules:\\n\\nTkinter Life Preserver¶\\n\\nThis 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.\\n\\nThe 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.\\n\\nA Hello World Program¶\\n\\nWe’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.\\n\\nfrom tkinter import *\\nfrom tkinter import ttk\\nroot = Tk()\\nfrm = ttk.Frame(root, padding=10)\\nfrm.grid()\\nttk.Label(frm, text=\"Hello World!\").grid(column=0, row=0)\\nttk.Button(frm, text=\"Quit\", command=root.destroy).grid(column=1, row=0)\\nroot.mainloop()\\n\\nAfter the imports, the next line creates an instance of the 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.\\n\\nThe 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.\\n\\nThe next line creates a label widget holding a static text string. The 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.\\n\\nA button widget is then created, and placed to the right of the label. When pressed, it will call the destroy() method of the root window.\\n\\nFinally, the mainloop() method puts everything on the display, and responds to user input until the program terminates.\\n\\nImportant Tk Concepts¶\\n\\nEven this simple program illustrates the following key Tk concepts:\\n\\nUnderstanding How Tkinter Wraps Tcl/Tk¶\\n\\nWhen 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 Tk instance.\\n\\nWhether 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.\\n\\nTo illustrate, here is the Tcl/Tk equivalent of the main part of the Tkinter script above.\\n\\nttk::frame .frm -padding 10\\ngrid .frm\\ngrid [ttk::label .frm.lbl -text \"Hello World!\"] -column 0 -row 0\\ngrid [ttk::button .frm.btn -text \"Quit\" -command \"destroy .\"] -column 1 -row 0\\n\\nTcl’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:\\n\\nThe commands used to create widgets (like ttk::frame) correspond to widget classes in Tkinter.\\n\\nTcl widget options (like -text) correspond to keyword arguments in Tkinter.\\n\\nWidgets are referred to by a pathname in Tcl (like .frm.btn), whereas Tkinter doesn’t use names but object references.\\n\\nA widget’s place in the widget hierarchy is encoded in its (hierarchical) pathname, which uses a . (dot) as a path separator. The pathname for the root window is just . (dot). In Tkinter, the hierarchy is defined not by pathname but by specifying the parent widget when creating each child widget.\\n\\nOperations which are implemented as separate commands in Tcl (like grid or 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.\\n\\nHow do I…? What option does…?¶\\n\\nIf 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.\\n\\nFirst, 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.\\n\\nWhen 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 print(), can help you identify what you need.\\n\\nTo find out what configuration options are available on any widget, call its configure() method, which returns a dictionary containing a variety of information about each object, including its default and current values. Use keys() to get just the names of each option.\\n\\nbtn = ttk.Button(frm, ...)\\nprint(btn.configure().keys())\\n\\nAs 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.\\n\\nprint(set(btn.configure().keys()) - set(frm.configure().keys()))\\n\\nSimilarly, you can find the available methods for a widget object using the standard 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.\\n\\nprint(dir(btn))\\nprint(set(dir(btn)) - set(dir(frm)))\\n\\nNavigating the Tcl/Tk Reference Manual¶\\n\\nAs noted, the official Tk commands 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.\\n\\nWhile 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.\\n\\ndestroy .\\ngrid .frm.btn -column 0 -row 0\\n\\nOthers, 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).\\n\\n.frm.btn invoke\\n.frm.lbl configure -text \"Goodbye\"\\n\\nIn 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 invoke() method on the ttk::button man page), while functions that take a widget as a parameter often have their own man page (e.g., grid).\\n\\nYou’ll find many common options and methods in the options or ttk::widget man pages, while others are found in the man page for a specific widget class.\\n\\nYou’ll also find that many Tkinter methods have compound names, e.g., winfo_x(), winfo_height(), winfo_viewable(). You’d find documentation for all of these in the winfo man page.\\n\\nNote\\n\\nSomewhat 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 Widget class that all Tkinter widgets inherit from).\\n\\nThreading model¶\\n\\nPython and Tcl/Tk have very different threading models, which tkinter tries to bridge. If you use threads, you may need to be aware of this.\\n\\nA 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.\\n\\nEach Tk object created by tkinter contains a Tcl interpreter. It also keeps track of which thread created that interpreter. Calls to tkinter can be made from any Python thread. Internally, if a call comes from a thread other than the one that created the Tk object, an event is posted to the interpreter’s event queue, and when executed, the result is returned to the calling Python thread.\\n\\nTcl/Tk applications are normally event-driven, meaning that after initialization, the interpreter runs an event loop (i.e. 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.\\n\\nIf the Tcl interpreter is not running the event loop and processing events, any tkinter calls made from threads other than the one running the Tcl interpreter will fail.\\n\\nA number of special cases exist:\\n\\nTcl/Tk libraries can be built so they are not thread-aware. In this case, 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.\\n\\nWhile tkinter allows you to create more than one instance of a 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 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.\\n\\nBlocking 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.\\n\\nThere are a few select tkinter functions that presently work only when called from the thread that created the Tcl interpreter.\\n\\nHandy Reference¶\\n\\nSetting Options¶\\n\\nOptions control things like the color and border width of a widget. Options can be set in three ways:\\n\\nFor a complete explanation of a given option and its behavior, see the Tk man pages for the widget in question.\\n\\nNote that the man pages list “STANDARD OPTIONS” and “WIDGET SPECIFIC OPTIONS” for each widget. The former is a list of options that are common to many widgets, the latter are the options that are idiosyncratic to that particular widget. The Standard Options are documented on the options(3) man page.\\n\\nNo distinction between standard and widget-specific options is made in this document. Some options don’t apply to some kinds of widgets. Whether a given widget responds to a particular option depends on the class of the widget; buttons have a command option, labels do not.\\n\\nThe options supported by a given widget are listed in that widget’s man page, or can be queried at runtime by calling the config() method without arguments, or by calling the keys() method on that widget. The return value of these calls is a dictionary whose key is the name of the option as a string (for example, \\'relief\\') and whose values are 5-tuples.\\n\\nSome options, like bg are synonyms for common options with long names (bg is shorthand for “background”). Passing the config() method the name of a shorthand option will return a 2-tuple, not 5-tuple. The 2-tuple passed back will contain the name of the synonym and the “real” option (such as (\\'bg\\', \\'background\\')).\\n\\nIndex Meaning Example 0 option name \\'relief\\' 1 option name for database lookup \\'relief\\' 2 option class for database\\nlookup \\'Relief\\' 3 default value \\'raised\\' 4 current value \\'groove\\'\\n\\nExample:\\n\\n>>> print(fred.config())\\n{\\'relief\\': (\\'relief\\', \\'relief\\', \\'Relief\\', \\'raised\\', \\'groove\\')}\\n\\nOf course, the dictionary printed will include all the options available and their values. This is meant only as an example.\\n\\nThe Packer¶\\n\\nThe 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.\\n\\nThe 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.\\n\\nNote that widgets do not appear until they have had their geometry specified with a geometry manager. It’s a common early mistake to leave out the geometry specification, and then be surprised when the widget is created but nothing appears. A widget will appear only after it has had, for example, the packer’s pack() method applied to it.\\n\\nThe pack() method can be called with keyword-option/value pairs that control where the widget is to appear within its container, and how it is to behave when the main application window is resized. Here are some examples:\\n\\nfred.pack() # defaults to side = \"top\"\\nfred.pack(side=\"left\")\\nfred.pack(expand=1)\\n\\nPacker Options¶\\n\\nFor more extensive information on the packer and the options that it can take, see the man pages and page 183 of John Ousterhout’s book.\\n\\nCoupling Widget Variables¶\\n\\nThe current-value setting of some widgets (like text entry widgets) can be connected directly to application variables by using special options. These options are variable, textvariable, onvalue, offvalue, and value. This connection works both ways: if the variable changes for any reason, the widget it’s connected to will be updated to reflect the new value.\\n\\nUnfortunately, in the current implementation of tkinter it is not possible to hand over an arbitrary Python variable to a widget through a variable or textvariable option. The only kinds of variables for which this works are variables that are subclassed from a class called Variable, defined in tkinter.\\n\\nThere are many useful subclasses of Variable already defined: StringVar, IntVar, DoubleVar, and BooleanVar. To read the current value of such a variable, call the get() method on it, and to change its value you call the set() method. If you follow this protocol, the widget will always track the value of the variable, with no further intervention on your part.\\n\\nFor example:\\n\\nimport tkinter as tk\\n\\nclass App(tk.Frame):\\n def __init__(self, master):\\n super().__init__(master)\\n self.pack()\\n\\n self.entrythingy = tk.Entry()\\n self.entrythingy.pack()\\n\\n # Create the application variable.\\n self.contents = tk.StringVar()\\n # Set it to some value.\\n self.contents.set(\"this is a variable\")\\n # Tell the entry widget to watch this variable.\\n self.entrythingy[\"textvariable\"] = self.contents\\n\\n # Define a callback for when the user hits return.\\n # It prints the current value of the variable.\\n self.entrythingy.bind(\\'\\',\\n self.print_contents)\\n\\n def print_contents(self, event):\\n print(\"Hi. The current entry content is:\",\\n self.contents.get())\\n\\nroot = tk.Tk()\\nmyapp = App(root)\\nmyapp.mainloop()\\n\\nThe Window Manager¶\\n\\nIn Tk, there is a utility command, wm, for interacting with the window manager. Options to the wm command allow you to control things like titles, placement, icon bitmaps, and the like. In tkinter, these commands have been implemented as methods on the Wm class. Toplevel widgets are subclassed from the Wm class, and so can call the Wm methods directly.\\n\\nTo get at the toplevel window that contains a given widget, you can often just refer to the widget’s master. Of course if the widget has been packed inside of a frame, the master won’t represent a toplevel window. To get at the toplevel window that contains an arbitrary widget, you can call the _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.\\n\\nHere are some examples of typical usage:\\n\\nimport tkinter as tk\\n\\nclass App(tk.Frame):\\n def __init__(self, master=None):\\n super().__init__(master)\\n self.pack()\\n\\n# create the application\\nmyapp = App()\\n\\n#\\n# here are method calls to the window manager class\\n#\\nmyapp.master.title(\"My Do-Nothing Application\")\\nmyapp.master.maxsize(1000, 400)\\n\\n# start the program\\nmyapp.mainloop()\\n\\nTk Option Data Types¶\\n\\nBindings and Events¶\\n\\nThe bind method from the widget command allows you to watch for certain events and to have a callback function trigger when that event type occurs. The form of the bind method is:\\n\\ndef bind(self, sequence, func, add=\\'\\'):\\n\\nwhere:\\n\\nFor example:\\n\\ndef turn_red(self, event):\\n event.widget[\"activeforeground\"] = \"red\"\\n\\nself.button.bind(\"\", self.turn_red)\\n\\nNotice how the widget field of the event is being accessed in the turn_red() callback. This field contains the widget that caught the X event. The following table lists the other event fields you can access, and how they are denoted in Tk, which can be useful when referring to the Tk man pages.\\n\\nTk Tkinter Event Field Tk Tkinter Event Field %f focus %A char %h height %E send_event %k keycode %K keysym %s state %N keysym_num %t time %T type %w width %W widget %x x %X x_root %y y %Y y_root\\n\\nThe index Parameter¶\\n\\nA number of widgets require “index” parameters to be passed. These are used to point at a specific place in a Text widget, or to particular characters in an Entry widget, or to particular menu items in a Menu widget.\\n\\nImages¶\\n\\nImages of different formats can be created through the corresponding subclass of tkinter.Image:\\n\\nBitmapImage for images in XBM format.\\n\\nPhotoImage for images in PGM, PPM, GIF and PNG formats. The latter is supported starting with Tk 8.6.\\n\\nEither type of image is created through either the file or the data option (other options are available as well).\\n\\nChanged in version 3.13: Added the PhotoImage method copy_replace() to copy a region from one image to other image, possibly with pixel zooming and/or subsampling. Add from_coords parameter to PhotoImage methods copy(), zoom() and subsample(). Add zoom and subsample parameters to PhotoImage method copy().\\n\\nThe image object can then be used wherever an image option is supported by some widget (e.g. labels, buttons, menus). In these cases, Tk will not keep a reference to the image. When the last Python reference to the image object is deleted, the image data is deleted as well, and Tk will display an empty box wherever the image was used.\\n\\nSee also\\n\\nThe Pillow package adds support for formats such as BMP, JPEG, TIFF, and WebP, among others.\\n\\nFile Handlers¶\\n\\nTk allows you to register and unregister a callback function which will be called from the Tk mainloop when I/O is possible on a file descriptor. Only one handler may be registered per file descriptor. Example code:\\n\\nimport tkinter\\nwidget = tkinter.Tk()\\nmask = tkinter.READABLE | tkinter.WRITABLE\\nwidget.tk.createfilehandler(file, mask, callback)\\n...\\nwidget.tk.deletefilehandler(file)\\n\\nThis feature is not available on Windows.\\n\\nSince you don’t know how many bytes are available for reading, you may not want to use the BufferedIOBase or TextIOBase read() or readline() methods, since these will insist on reading a predefined number of bytes. For sockets, the recv() or recvfrom() methods will work fine; for other files, use raw reads or os.read(file.fileno(), maxbytecount).\\n\\nTable of Contents\\n\\ntkinter — Python interface to Tcl/Tk\\n\\nArchitecture\\n\\nTkinter Modules\\n\\nTkinter Life Preserver\\n\\nA Hello World Program\\n\\nImportant Tk Concepts\\n\\nUnderstanding How Tkinter Wraps Tcl/Tk\\n\\nHow do I…? What option does…?\\n\\nNavigating the Tcl/Tk Reference Manual\\n\\nThreading model\\n\\nHandy Reference\\n\\nSetting Options\\n\\nThe Packer\\n\\nPacker Options\\n\\nCoupling Widget Variables\\n\\nThe Window Manager\\n\\nTk Option Data Types\\n\\nBindings and Events\\n\\nThe index Parameter\\n\\nImages\\n\\nFile Handlers\\n\\nPrevious topic\\n\\nGraphical user interfaces with Tk\\n\\nNext topic\\n\\ntkinter.colorchooser — Color choosing dialog\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nGraphical user interfaces with Tk »\\n\\ntkinter — Python interface to Tcl/Tk\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\tkinter.messagebox.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nGraphical user interfaces with Tk »\\n\\ntkinter.messagebox — Tkinter message prompts\\n\\n|\\n\\ntkinter.messagebox — Tkinter message prompts¶\\n\\nSource code: Lib/tkinter/messagebox.py\\n\\nThe 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 (True, False, None, OK, CANCEL, YES, NO) based on the user’s selection. Common message box styles and layouts include but are not limited to:\\n\\nInformation message box\\n\\nWarning message boxes\\n\\nQuestion message boxes\\n\\nSymbolic names of buttons:\\n\\nPredefined sets of buttons:\\n\\nIcon images:\\n\\nPrevious topic\\n\\nTkinter Dialogs\\n\\nNext topic\\n\\ntkinter.scrolledtext — Scrolled Text Widget\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nGraphical user interfaces with Tk »\\n\\ntkinter.messagebox — Tkinter message prompts\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\tkinter.scrolledtext.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nGraphical user interfaces with Tk »\\n\\ntkinter.scrolledtext — Scrolled Text Widget\\n\\n|\\n\\ntkinter.scrolledtext — Scrolled Text Widget¶\\n\\nSource code: Lib/tkinter/scrolledtext.py\\n\\nThe 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 ScrolledText class is a lot easier than setting up a text widget and scroll bar directly.\\n\\nThe text widget and scrollbar are packed together in a Frame, and the methods of the Grid and Pack geometry managers are acquired from the Frame object. This allows the ScrolledText widget to be used directly to achieve most normal geometry management behavior.\\n\\nShould more specific control be necessary, the following attributes are available:\\n\\nPrevious topic\\n\\ntkinter.messagebox — Tkinter message prompts\\n\\nNext topic\\n\\ntkinter.dnd — Drag and drop support\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nGraphical user interfaces with Tk »\\n\\ntkinter.scrolledtext — Scrolled Text Widget\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\tkinter.ttk.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nGraphical user interfaces with Tk »\\n\\ntkinter.ttk — Tk themed widgets\\n\\n|\\n\\ntkinter.ttk — Tk themed widgets¶\\n\\nSource code: Lib/tkinter/ttk.py\\n\\nThe 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).\\n\\nThe basic idea for tkinter.ttk is to separate, to the extent possible, the code implementing a widget’s behavior from the code implementing its appearance.\\n\\nSee also\\n\\nUsing Ttk¶\\n\\nTo start using Ttk, import its module:\\n\\nfrom tkinter import ttk\\n\\nTo override the basic Tk widgets, the import should follow the Tk import:\\n\\nfrom tkinter import *\\nfrom tkinter.ttk import *\\n\\nThat code causes several tkinter.ttk widgets (Button, Checkbutton, Entry, Frame, Label, LabelFrame, Menubutton, PanedWindow, Radiobutton, Scale and Scrollbar) to automatically replace the Tk widgets.\\n\\nThis has the direct benefit of using the new widgets which gives a better look and feel across platforms; however, the replacement widgets are not completely compatible. The main difference is that widget options such as “fg”, “bg” and others related to widget styling are no longer present in Ttk widgets. Instead, use the ttk.Style class for improved styling effects.\\n\\nSee also\\n\\nTtk Widgets¶\\n\\nTtk comes with 18 widgets, twelve of which already existed in tkinter: Button, Checkbutton, Entry, Frame, Label, LabelFrame, Menubutton, PanedWindow, Radiobutton, Scale, Scrollbar, and Spinbox. The other six are new: Combobox, Notebook, Progressbar, Separator, Sizegrip and Treeview. And all them are subclasses of Widget.\\n\\nUsing the Ttk widgets gives the application an improved look and feel. As discussed above, there are differences in how the styling is coded.\\n\\nTk code:\\n\\nl1 = tkinter.Label(text=\"Test\", fg=\"black\", bg=\"white\")\\nl2 = tkinter.Label(text=\"Test\", fg=\"black\", bg=\"white\")\\n\\nTtk code:\\n\\nstyle = ttk.Style()\\nstyle.configure(\"BW.TLabel\", foreground=\"black\", background=\"white\")\\n\\nl1 = ttk.Label(text=\"Test\", style=\"BW.TLabel\")\\nl2 = ttk.Label(text=\"Test\", style=\"BW.TLabel\")\\n\\nFor more information about TtkStyling, see the Style class documentation.\\n\\nWidget¶\\n\\nttk.Widget defines standard options and methods supported by Tk themed widgets and is not supposed to be directly instantiated.\\n\\nStandard Options¶\\n\\nAll the ttk Widgets accept the following options:\\n\\nOption Description class Specifies the window class. The class is used when querying\\nthe option database for the window’s other options, to\\ndetermine the default bindtags for the window, and to select\\nthe widget’s default layout and style. This option is\\nread-only, and may only be specified when the window is\\ncreated. cursor Specifies the mouse cursor to be used for the widget. If set\\nto the empty string (the default), the cursor is inherited\\nfor the parent widget. takefocus Determines whether the window accepts the focus during\\nkeyboard traversal. 0, 1 or an empty string is returned.\\nIf 0 is returned, it means that the window should be skipped\\nentirely during keyboard traversal. If 1, it means that the\\nwindow should receive the input focus as long as it is\\nviewable. And an empty string means that the traversal\\nscripts make the decision about whether or not to focus\\non the window. style May be used to specify a custom widget style.\\n\\nScrollable Widget Options¶\\n\\nThe following options are supported by widgets that are controlled by a scrollbar.\\n\\nOption Description xscrollcommand Used to communicate with horizontal scrollbars. When the view in the widget’s window change, the widget\\nwill generate a Tcl command based on the scrollcommand. Usually this option consists of the method Scrollbar.set() of some scrollbar. This will cause\\nthe scrollbar to be updated whenever the view in the\\nwindow changes. yscrollcommand Used to communicate with vertical scrollbars.\\nFor some more information, see above.\\n\\nLabel Options¶\\n\\nThe following options are supported by labels, buttons and other button-like widgets.\\n\\nOption Description text Specifies a text string to be displayed inside the widget. textvariable Specifies a name whose value will be used in place of the\\ntext option resource. underline If set, specifies the index (0-based) of a character to\\nunderline in the text string. The underline character is\\nused for mnemonic activation. image Specifies an image to display. This is a list of 1 or more\\nelements. The first element is the default image name. The\\nrest of the list if a sequence of statespec/value pairs as\\ndefined by Style.map() , specifying different images\\nto use when the widget is in a particular state or a\\ncombination of states. All images in the list should have\\nthe same size. compound Specifies how to display the image relative to the text,\\nin the case both text and images options are present.\\nValid values are: text: display text only image: display image only top, bottom, left, right: display image above, below,\\nleft of, or right of the text, respectively. none: the default. display the image if present,\\notherwise the text. width If greater than zero, specifies how much space, in\\ncharacter widths, to allocate for the text label, if less\\nthan zero, specifies a minimum width. If zero or\\nunspecified, the natural width of the text label is used.\\n\\nCompatibility Options¶\\n\\nOption Description state May be set to “normal” or “disabled” to control the “disabled”\\nstate bit. This is a write-only option: setting it changes the\\nwidget state, but the Widget.state() method does not\\naffect this option.\\n\\nWidget States¶\\n\\nThe widget state is a bitmap of independent state flags.\\n\\nFlag Description active The mouse cursor is over the widget and pressing a mouse\\nbutton will cause some action to occur disabled Widget is disabled under program control focus Widget has keyboard focus pressed Widget is being pressed selected “On”, “true”, or “current” for things like Checkbuttons and\\nradiobuttons background Windows and Mac have a notion of an “active” or foreground\\nwindow. The background state is set for widgets in a\\nbackground window, and cleared for those in the foreground\\nwindow readonly Widget should not allow user modification alternate A widget-specific alternate display format invalid The widget’s value is invalid\\n\\nA state specification is a sequence of state names, optionally prefixed with an exclamation point indicating that the bit is off.\\n\\nttk.Widget¶\\n\\nBesides the methods described below, the ttk.Widget supports the methods tkinter.Widget.cget() and tkinter.Widget.configure().\\n\\nCombobox¶\\n\\nThe ttk.Combobox widget combines a text field with a pop-down list of values. This widget is a subclass of Entry.\\n\\nBesides the methods inherited from Widget: Widget.cget(), Widget.configure(), Widget.identify(), Widget.instate() and Widget.state(), and the following inherited from Entry: Entry.bbox(), Entry.delete(), Entry.icursor(), Entry.index(), Entry.insert(), Entry.selection(), Entry.xview(), it has some other methods, described at ttk.Combobox.\\n\\nOptions¶\\n\\nThis widget accepts the following specific options:\\n\\nOption Description exportselection Boolean value. If set, the widget selection is linked\\nto the Window Manager selection (which can be returned\\nby invoking Misc.selection_get, for example). justify Specifies how the text is aligned within the widget.\\nOne of “left”, “center”, or “right”. height Specifies the height of the pop-down listbox, in rows. postcommand A script (possibly registered with Misc.register) that\\nis called immediately before displaying the values. It\\nmay specify which values to display. state One of “normal”, “readonly”, or “disabled”. In the\\n“readonly” state, the value may not be edited directly,\\nand the user can only selection of the values from the\\ndropdown list. In the “normal” state, the text field is\\ndirectly editable. In the “disabled” state, no\\ninteraction is possible. textvariable Specifies a name whose value is linked to the widget\\nvalue. Whenever the value associated with that name\\nchanges, the widget value is updated, and vice versa.\\nSee tkinter.StringVar . values Specifies the list of values to display in the\\ndrop-down listbox. width Specifies an integer value indicating the desired width\\nof the entry window, in average-size characters of the\\nwidget’s font.\\n\\nVirtual events¶\\n\\nThe combobox widgets generates a <> virtual event when the user selects an element from the list of values.\\n\\nttk.Combobox¶\\n\\nSpinbox¶\\n\\nThe ttk.Spinbox widget is a 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 Entry.\\n\\nBesides the methods inherited from Widget: Widget.cget(), Widget.configure(), Widget.identify(), Widget.instate() and Widget.state(), and the following inherited from Entry: Entry.bbox(), Entry.delete(), Entry.icursor(), Entry.index(), Entry.insert(), Entry.xview(), it has some other methods, described at ttk.Spinbox.\\n\\nOptions¶\\n\\nThis widget accepts the following specific options:\\n\\nOption Description from Float value. If set, this is the minimum value to\\nwhich the decrement button will decrement. Must be\\nspelled as from_ when used as an argument, since from is a Python keyword. to Float value. If set, this is the maximum value to\\nwhich the increment button will increment. increment Float value. Specifies the amount which the\\nincrement/decrement buttons change the\\nvalue. Defaults to 1.0. values Sequence of string or float values. If specified,\\nthe increment/decrement buttons will cycle through\\nthe items in this sequence rather than incrementing\\nor decrementing numbers. wrap Boolean value. If True , increment and decrement\\nbuttons will cycle from the to value to the from value or the from value to the to value, respectively. format String value. This specifies the format of numbers\\nset by the increment/decrement buttons. It must be\\nin the form “%W.Pf”, where W is the padded width of\\nthe value, P is the precision, and ‘%’ and ‘f’ are\\nliteral. command Python callable. Will be called with no arguments\\nwhenever either of the increment or decrement buttons\\nare pressed.\\n\\nVirtual events¶\\n\\nThe spinbox widget generates an <> virtual event when the user presses , and a <> virtual event when the user presses .\\n\\nttk.Spinbox¶\\n\\nNotebook¶\\n\\nTtk Notebook widget manages a collection of windows and displays a single one at a time. Each child window is associated with a tab, which the user may select to change the currently displayed window.\\n\\nOptions¶\\n\\nThis widget accepts the following specific options:\\n\\nOption Description height If present and greater than zero, specifies the desired height\\nof the pane area (not including internal padding or tabs).\\nOtherwise, the maximum height of all panes is used. padding Specifies the amount of extra space to add around the outside\\nof the notebook. The padding is a list up to four length\\nspecifications left top right bottom. If fewer than four\\nelements are specified, bottom defaults to top, right defaults\\nto left, and top defaults to left. width If present and greater than zero, specified the desired width\\nof the pane area (not including internal padding). Otherwise,\\nthe maximum width of all panes is used.\\n\\nTab Options¶\\n\\nThere are also specific options for tabs:\\n\\nOption Description state Either “normal”, “disabled” or “hidden”. If “disabled”, then\\nthe tab is not selectable. If “hidden”, then the tab is not\\nshown. sticky Specifies how the child window is positioned within the pane\\narea. Value is a string containing zero or more of the\\ncharacters “n”, “s”, “e” or “w”. Each letter refers to a\\nside (north, south, east or west) that the child window will\\nstick to, as per the grid() geometry manager. padding Specifies the amount of extra space to add between the\\nnotebook and this pane. Syntax is the same as for the option\\npadding used by this widget. text Specifies a text to be displayed in the tab. image Specifies an image to display in the tab. See the option\\nimage described in Widget . compound Specifies how to display the image relative to the text, in\\nthe case both options text and image are present. See Label Options for legal values. underline Specifies the index (0-based) of a character to underline in\\nthe text string. The underlined character is used for\\nmnemonic activation if Notebook.enable_traversal() is\\ncalled.\\n\\nTab Identifiers¶\\n\\nThe tab_id present in several methods of ttk.Notebook may take any of the following forms:\\n\\nAn integer between zero and the number of tabs\\n\\nThe name of a child window\\n\\nA positional specification of the form “@x,y”, which identifies the tab\\n\\nThe literal string “current”, which identifies the currently selected tab\\n\\nThe literal string “end”, which returns the number of tabs (only valid for Notebook.index())\\n\\nVirtual Events¶\\n\\nThis widget generates a <> virtual event after a new tab is selected.\\n\\nttk.Notebook¶\\n\\nProgressbar¶\\n\\nThe ttk.Progressbar widget shows the status of a long-running operation. It can operate in two modes: 1) the determinate mode which shows the amount completed relative to the total amount of work to be done and 2) the indeterminate mode which provides an animated display to let the user know that work is progressing.\\n\\nOptions¶\\n\\nThis widget accepts the following specific options:\\n\\nOption Description orient One of “horizontal” or “vertical”. Specifies the orientation\\nof the progress bar. length Specifies the length of the long axis of the progress bar\\n(width if horizontal, height if vertical). mode One of “determinate” or “indeterminate”. maximum A number specifying the maximum value. Defaults to 100. value The current value of the progress bar. In “determinate” mode,\\nthis represents the amount of work completed. In\\n“indeterminate” mode, it is interpreted as modulo maximum ;\\nthat is, the progress bar completes one “cycle” when its value\\nincreases by maximum . variable A name which is linked to the option value. If specified, the\\nvalue of the progress bar is automatically set to the value of\\nthis name whenever the latter is modified. phase Read-only option. The widget periodically increments the value\\nof this option whenever its value is greater than 0 and, in\\ndeterminate mode, less than maximum. This option may be used\\nby the current theme to provide additional animation effects.\\n\\nttk.Progressbar¶\\n\\nSeparator¶\\n\\nThe ttk.Separator widget displays a horizontal or vertical separator bar.\\n\\nIt has no other methods besides the ones inherited from ttk.Widget.\\n\\nOptions¶\\n\\nThis widget accepts the following specific option:\\n\\nOption Description orient One of “horizontal” or “vertical”. Specifies the orientation of\\nthe separator.\\n\\nSizegrip¶\\n\\nThe ttk.Sizegrip widget (also known as a grow box) allows the user to resize the containing toplevel window by pressing and dragging the grip.\\n\\nThis widget has neither specific options nor specific methods, besides the ones inherited from ttk.Widget.\\n\\nPlatform-specific notes¶\\n\\nOn macOS, toplevel windows automatically include a built-in size grip by default. Adding a Sizegrip is harmless, since the built-in grip will just mask the widget.\\n\\nBugs¶\\n\\nIf the containing toplevel’s position was specified relative to the right or bottom of the screen (e.g. ….), the Sizegrip widget will not resize the window.\\n\\nThis widget supports only “southeast” resizing.\\n\\nTreeview¶\\n\\nThe ttk.Treeview widget displays a hierarchical collection of items. Each item has a textual label, an optional image, and an optional list of data values. The data values are displayed in successive columns after the tree label.\\n\\nThe order in which data values are displayed may be controlled by setting the widget option displaycolumns. The tree widget can also display column headings. Columns may be accessed by number or symbolic names listed in the widget option columns. See Column Identifiers.\\n\\nEach item is identified by a unique name. The widget will generate item IDs if they are not supplied by the caller. There is a distinguished root item, named {}. The root item itself is not displayed; its children appear at the top level of the hierarchy.\\n\\nEach item also has a list of tags, which can be used to associate event bindings with individual items and control the appearance of the item.\\n\\nThe Treeview widget supports horizontal and vertical scrolling, according to the options described in Scrollable Widget Options and the methods Treeview.xview() and Treeview.yview().\\n\\nOptions¶\\n\\nThis widget accepts the following specific options:\\n\\nOption Description columns A list of column identifiers, specifying the number of\\ncolumns and their names. displaycolumns A list of column identifiers (either symbolic or\\ninteger indices) specifying which data columns are\\ndisplayed and the order in which they appear, or the\\nstring “#all”. height Specifies the number of rows which should be visible.\\nNote: the requested width is determined from the sum\\nof the column widths. padding Specifies the internal padding for the widget. The\\npadding is a list of up to four length specifications. selectmode Controls how the built-in class bindings manage the\\nselection. One of “extended”, “browse” or “none”.\\nIf set to “extended” (the default), multiple items may\\nbe selected. If “browse”, only a single item will be\\nselected at a time. If “none”, the selection will not\\nbe changed. Note that the application code and tag bindings can set\\nthe selection however they wish, regardless of the\\nvalue of this option. show A list containing zero or more of the following values,\\nspecifying which elements of the tree to display. tree: display tree labels in column #0. headings: display the heading row. The default is “tree headings”, i.e., show all\\nelements. Note : Column #0 always refers to the tree column,\\neven if show=”tree” is not specified.\\n\\nItem Options¶\\n\\nThe following item options may be specified for items in the insert and item widget commands.\\n\\nOption Description text The textual label to display for the item. image A Tk Image, displayed to the left of the label. values The list of values associated with the item. Each item should have the same number of values as the widget\\noption columns. If there are fewer values than columns, the\\nremaining values are assumed empty. If there are more values\\nthan columns, the extra values are ignored. open True / False value indicating whether the item’s\\nchildren should be displayed or hidden. tags A list of tags associated with this item.\\n\\nTag Options¶\\n\\nThe following options may be specified on tags:\\n\\nOption Description foreground Specifies the text foreground color. background Specifies the cell or item background color. font Specifies the font to use when drawing text. image Specifies the item image, in case the item’s image option\\nis empty.\\n\\nColumn Identifiers¶\\n\\nColumn identifiers take any of the following forms:\\n\\nA symbolic name from the list of columns option.\\n\\nAn integer n, specifying the nth data column.\\n\\nA string of the form #n, where n is an integer, specifying the nth display column.\\n\\nNotes:\\n\\nItem’s option values may be displayed in a different order than the order in which they are stored.\\n\\nColumn #0 always refers to the tree column, even if show=”tree” is not specified.\\n\\nA data column number is an index into an item’s option values list; a display column number is the column number in the tree where the values are displayed. Tree labels are displayed in column #0. If option displaycolumns is not set, then data column n is displayed in column #n+1. Again, column #0 always refers to the tree column.\\n\\nVirtual Events¶\\n\\nThe Treeview widget generates the following virtual events.\\n\\nEvent Description <> Generated whenever the selection changes. <> Generated just before settings the focus item to\\nopen=True. <> Generated just after setting the focus item to\\nopen=False.\\n\\nThe Treeview.focus() and Treeview.selection() methods can be used to determine the affected item or items.\\n\\nttk.Treeview¶\\n\\nTtk Styling¶\\n\\nEach widget in ttk is assigned a style, which specifies the set of elements making up the widget and how they are arranged, along with dynamic and default settings for element options. By default the style name is the same as the widget’s class name, but it may be overridden by the widget’s style option. If you don’t know the class name of a widget, use the method Misc.winfo_class() (somewidget.winfo_class()).\\n\\nSee also\\n\\nLayouts¶\\n\\nA layout can be just None, if it takes no options, or a dict of options specifying how to arrange the element. The layout mechanism uses a simplified version of the pack geometry manager: given an initial cavity, each element is allocated a parcel.\\n\\nThe valid options/values are:\\n\\nTable of Contents\\n\\ntkinter.ttk — Tk themed widgets\\n\\nUsing Ttk\\n\\nTtk Widgets\\n\\nWidget\\n\\nStandard Options\\n\\nScrollable Widget Options\\n\\nLabel Options\\n\\nCompatibility Options\\n\\nWidget States\\n\\nttk.Widget\\n\\nCombobox\\n\\nOptions\\n\\nVirtual events\\n\\nttk.Combobox\\n\\nSpinbox\\n\\nOptions\\n\\nVirtual events\\n\\nttk.Spinbox\\n\\nNotebook\\n\\nOptions\\n\\nTab Options\\n\\nTab Identifiers\\n\\nVirtual Events\\n\\nttk.Notebook\\n\\nProgressbar\\n\\nOptions\\n\\nttk.Progressbar\\n\\nSeparator\\n\\nOptions\\n\\nSizegrip\\n\\nPlatform-specific notes\\n\\nBugs\\n\\nTreeview\\n\\nOptions\\n\\nItem Options\\n\\nTag Options\\n\\nColumn Identifiers\\n\\nVirtual Events\\n\\nttk.Treeview\\n\\nTtk Styling\\n\\nLayouts\\n\\nPrevious topic\\n\\ntkinter.dnd — Drag and drop support\\n\\nNext topic\\n\\nIDLE — Python editor and shell\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nGraphical user interfaces with Tk »\\n\\ntkinter.ttk — Tk themed widgets\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\token.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Language Services »\\n\\ntoken — Constants used with Python parse trees\\n\\n|\\n\\ntoken — Constants used with Python parse trees¶\\n\\nSource code: Lib/token.py\\n\\nThis module provides constants which represent the numeric values of leaf nodes of the parse tree (terminal tokens). Refer to the file Grammar/Tokens in the Python distribution for the definitions of the names in the context of the language grammar. The specific numeric values which the names map to may change between Python versions.\\n\\nThe module also provides a mapping from numeric codes to names and some functions. The functions mirror definitions in the Python C header files.\\n\\nNote that a token’s value may depend on tokenizer options. For example, a \"+\" token may be reported as either PLUS or OP, or a \"match\" token may be either NAME or SOFT_KEYWORD.\\n\\nThe token constants are:\\n\\nThe following token types are not produced by the tokenize module, and are defined for special uses in the tokenizer or parser:\\n\\nThe remaining tokens represent specific operators and delimiters. (The tokenize module reports these as OP; see exact_type in the tokenize documentation for details.)\\n\\nToken Value token. LPAR ¶ \"(\" token. RPAR ¶ \")\" token. LSQB ¶ \"[\" token. RSQB ¶ \"]\" token. COLON ¶ \":\" token. COMMA ¶ \",\" token. SEMI ¶ \";\" token. PLUS ¶ \"+\" token. MINUS ¶ \"-\" token. STAR ¶ \"*\" token. SLASH ¶ \"/\" token. VBAR ¶ \"|\" token. AMPER ¶ \"&\" token. LESS ¶ \"<\" token. GREATER ¶ \">\" token. EQUAL ¶ \"=\" token. DOT ¶ \".\" token. PERCENT ¶ \"%\" token. LBRACE ¶ \"{\" token. RBRACE ¶ \"}\" token. EQEQUAL ¶ \"==\" token. NOTEQUAL ¶ \"!=\" token. LESSEQUAL ¶ \"<=\" token. GREATEREQUAL ¶ \">=\" token. TILDE ¶ \"~\" token. CIRCUMFLEX ¶ \"^\" token. LEFTSHIFT ¶ \"<<\" token. RIGHTSHIFT ¶ \">>\" token. DOUBLESTAR ¶ \"**\" token. PLUSEQUAL ¶ \"+=\" token. MINEQUAL ¶ \"-=\" token. STAREQUAL ¶ \"*=\" token. SLASHEQUAL ¶ \"/=\" token. PERCENTEQUAL ¶ \"%=\" token. AMPEREQUAL ¶ \"&=\" token. VBAREQUAL ¶ \"|=\" token. CIRCUMFLEXEQUAL ¶ \"^=\" token. LEFTSHIFTEQUAL ¶ \"<<=\" token. RIGHTSHIFTEQUAL ¶ \">>=\" token. DOUBLESTAREQUAL ¶ \"**=\" token. DOUBLESLASH ¶ \"//\" token. DOUBLESLASHEQUAL ¶ \"//=\" token. AT ¶ \"@\" token. ATEQUAL ¶ \"@=\" token. RARROW ¶ \"->\" token. ELLIPSIS ¶ \"...\" token. COLONEQUAL ¶ \":=\" token. EXCLAMATION ¶ \"!\"\\n\\nThe following non-token constants are provided:\\n\\nChanged in version 3.5: Added AWAIT and ASYNC tokens.\\n\\nChanged in version 3.7: Added COMMENT, NL and ENCODING tokens.\\n\\nChanged in version 3.7: Removed AWAIT and ASYNC tokens. “async” and “await” are now tokenized as NAME tokens.\\n\\nChanged in version 3.8: Added TYPE_COMMENT, TYPE_IGNORE, COLONEQUAL. Added AWAIT and ASYNC tokens back (they’re needed to support parsing older Python versions for ast.parse() with feature_version set to 6 or lower).\\n\\nChanged in version 3.12: Added EXCLAMATION.\\n\\nChanged in version 3.13: Removed AWAIT and ASYNC tokens again.\\n\\nPrevious topic\\n\\nsymtable — Access to the compiler’s symbol tables\\n\\nNext topic\\n\\nkeyword — Testing for Python keywords\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Language Services »\\n\\ntoken — Constants used with Python parse trees\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\tokenize.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Language Services »\\n\\ntokenize — Tokenizer for Python source\\n\\n|\\n\\ntokenize — Tokenizer for Python source¶\\n\\nSource code: Lib/tokenize.py\\n\\nThe 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.\\n\\nTo simplify token stream handling, all operator and delimiter tokens and Ellipsis are returned using the generic OP token type. The exact type can be determined by checking the exact_type property on the named tuple returned from tokenize.tokenize().\\n\\nWarning\\n\\nNote that the functions in this module are only designed to parse syntactically valid Python code (code that does not raise when parsed using ast.parse()). The behavior of the functions in this module is undefined when providing invalid Python code and it can change at any point.\\n\\nTokenizing Input¶\\n\\nThe primary entry point is a generator:\\n\\nAll constants from the token module are also exported from tokenize.\\n\\nAnother function is provided to reverse the tokenization process. This is useful for creating tools that tokenize a script, modify the token stream, and write back the modified script.\\n\\ntokenize() needs to detect the encoding of source files it tokenizes. The function it uses to do this is available:\\n\\nCommand-Line Usage¶\\n\\nAdded in version 3.3.\\n\\nThe tokenize module can be executed as a script from the command line. It is as simple as:\\n\\npython -m tokenize [-e] [filename.py]\\n\\nThe following options are accepted:\\n\\nIf filename.py is specified its contents are tokenized to stdout. Otherwise, tokenization is performed on stdin.\\n\\nExamples¶\\n\\nExample of a script rewriter that transforms float literals into Decimal objects:\\n\\nfrom tokenize import tokenize, untokenize, NUMBER, STRING, NAME, OP\\nfrom io import BytesIO\\n\\ndef decistmt(s):\\n \"\"\"Substitute Decimals for floats in a string of statements.\\n\\n >>> from decimal import Decimal\\n >>> s = \\'print(+21.3e-5*-.1234/81.7)\\'\\n >>> decistmt(s)\\n \"print (+Decimal (\\'21.3e-5\\')*-Decimal (\\'.1234\\')/Decimal (\\'81.7\\'))\"\\n\\n The format of the exponent is inherited from the platform C library.\\n Known cases are \"e-007\" (Windows) and \"e-07\" (not Windows). Since\\n we\\'re only showing 12 digits, and the 13th isn\\'t close to 5, the\\n rest of the output should be platform-independent.\\n\\n >>> exec(s) #doctest: +ELLIPSIS\\n -3.21716034272e-0...7\\n\\n Output from calculations with Decimal should be identical across all\\n platforms.\\n\\n >>> exec(decistmt(s))\\n -3.217160342717258261933904529E-7\\n \"\"\"\\n result = []\\n g = tokenize(BytesIO(s.encode(\\'utf-8\\')).readline) # tokenize the string\\n for toknum, tokval, _, _, _ in g:\\n if toknum == NUMBER and \\'.\\' in tokval: # replace NUMBER tokens\\n result.extend([\\n (NAME, \\'Decimal\\'),\\n (OP, \\'(\\'),\\n (STRING, repr(tokval)),\\n (OP, \\')\\')\\n ])\\n else:\\n result.append((toknum, tokval))\\n return untokenize(result).decode(\\'utf-8\\')\\n\\nExample of tokenizing from the command line. The script:\\n\\ndef say_hello():\\n print(\"Hello, World!\")\\n\\nsay_hello()\\n\\nwill be tokenized to the following output where the first column is the range of the line/column coordinates where the token is found, the second column is the name of the token, and the final column is the value of the token (if any)\\n\\n$ python -m tokenize hello.py\\n0,0-0,0: ENCODING \\'utf-8\\'\\n1,0-1,3: NAME \\'def\\'\\n1,4-1,13: NAME \\'say_hello\\'\\n1,13-1,14: OP \\'(\\'\\n1,14-1,15: OP \\')\\'\\n1,15-1,16: OP \\':\\'\\n1,16-1,17: NEWLINE \\'\\\\n\\'\\n2,0-2,4: INDENT \\' \\'\\n2,4-2,9: NAME \\'print\\'\\n2,9-2,10: OP \\'(\\'\\n2,10-2,25: STRING \\'\"Hello, World!\"\\'\\n2,25-2,26: OP \\')\\'\\n2,26-2,27: NEWLINE \\'\\\\n\\'\\n3,0-3,1: NL \\'\\\\n\\'\\n4,0-4,0: DEDENT \\'\\'\\n4,0-4,9: NAME \\'say_hello\\'\\n4,9-4,10: OP \\'(\\'\\n4,10-4,11: OP \\')\\'\\n4,11-4,12: NEWLINE \\'\\\\n\\'\\n5,0-5,0: ENDMARKER \\'\\'\\n\\nThe exact token type names can be displayed using the -e option:\\n\\n$ python -m tokenize -e hello.py\\n0,0-0,0: ENCODING \\'utf-8\\'\\n1,0-1,3: NAME \\'def\\'\\n1,4-1,13: NAME \\'say_hello\\'\\n1,13-1,14: LPAR \\'(\\'\\n1,14-1,15: RPAR \\')\\'\\n1,15-1,16: COLON \\':\\'\\n1,16-1,17: NEWLINE \\'\\\\n\\'\\n2,0-2,4: INDENT \\' \\'\\n2,4-2,9: NAME \\'print\\'\\n2,9-2,10: LPAR \\'(\\'\\n2,10-2,25: STRING \\'\"Hello, World!\"\\'\\n2,25-2,26: RPAR \\')\\'\\n2,26-2,27: NEWLINE \\'\\\\n\\'\\n3,0-3,1: NL \\'\\\\n\\'\\n4,0-4,0: DEDENT \\'\\'\\n4,0-4,9: NAME \\'say_hello\\'\\n4,9-4,10: LPAR \\'(\\'\\n4,10-4,11: RPAR \\')\\'\\n4,11-4,12: NEWLINE \\'\\\\n\\'\\n5,0-5,0: ENDMARKER \\'\\'\\n\\nExample of tokenizing a file programmatically, reading unicode strings instead of bytes with generate_tokens():\\n\\nimport tokenize\\n\\nwith tokenize.open(\\'hello.py\\') as f:\\n tokens = tokenize.generate_tokens(f.readline)\\n for token in tokens:\\n print(token)\\n\\nOr reading bytes directly with tokenize():\\n\\nimport tokenize\\n\\nwith open(\\'hello.py\\', \\'rb\\') as f:\\n tokens = tokenize.tokenize(f.readline)\\n for token in tokens:\\n print(token)\\n\\nTable of Contents\\n\\ntokenize — Tokenizer for Python source\\n\\nTokenizing Input\\n\\nCommand-Line Usage\\n\\nExamples\\n\\nPrevious topic\\n\\nkeyword — Testing for Python keywords\\n\\nNext topic\\n\\ntabnanny — Detection of ambiguous indentation\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Language Services »\\n\\ntokenize — Tokenizer for Python source\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\tomllib.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nFile Formats »\\n\\ntomllib — Parse TOML files\\n\\n|\\n\\ntomllib — Parse TOML files¶\\n\\nSource code: Lib/tomllib\\n\\nThis module provides an interface for parsing TOML 1.1.0 (Tom’s Obvious Minimal Language, https://toml.io). This module does not support writing TOML.\\n\\nAdded in version 3.11: The module was added with support for TOML 1.0.0.\\n\\nChanged in version 3.15: Added TOML 1.1.0 support. See the What’s New for details.\\n\\nSee also\\n\\nThe Tomli-W package is a TOML writer that can be used in conjunction with this module, providing a write API familiar to users of the standard library marshal and pickle modules.\\n\\nSee also\\n\\nThe TOML Kit package is a style-preserving TOML library with both read and write capability. It is a recommended replacement for this module for editing already existing TOML files.\\n\\nThis module defines the following functions:\\n\\nThe following exceptions are available:\\n\\nExamples¶\\n\\nParsing a TOML file:\\n\\nimport tomllib\\n\\nwith open(\"pyproject.toml\", \"rb\") as f:\\n data = tomllib.load(f)\\n\\nParsing a TOML string:\\n\\nimport tomllib\\n\\ntoml_str = \"\"\"\\npython-version = \"3.11.0\"\\npython-implementation = \"CPython\"\\n\"\"\"\\n\\ndata = tomllib.loads(toml_str)\\n\\nConversion Table¶\\n\\nTOML Python TOML document dict string str integer int float float (configurable with parse_float ) boolean bool offset date-time datetime.datetime ( tzinfo attribute set to an instance of datetime.timezone ) local date-time datetime.datetime ( tzinfo attribute set to None ) local date datetime.date local time datetime.time array list table dict inline table dict array of tables list of dicts\\n\\nTable of Contents\\n\\ntomllib — Parse TOML files\\n\\nExamples\\n\\nConversion Table\\n\\nPrevious topic\\n\\nconfigparser — Configuration file parser\\n\\nNext topic\\n\\nnetrc — netrc file processing\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nFile Formats »\\n\\ntomllib — Parse TOML files\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\trace.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nDebugging and profiling »\\n\\ntrace — Trace or track Python statement execution\\n\\n|\\n\\ntrace — Trace or track Python statement execution¶\\n\\nSource code: Lib/trace.py\\n\\nThe 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.\\n\\nSee also\\n\\nCommand-Line Usage¶\\n\\nThe trace module can be invoked from the command line. It can be as simple as\\n\\npython -m trace --count -C . somefile.py ...\\n\\nThe above will execute somefile.py and generate annotated listings of all Python modules imported during the execution into the current directory.\\n\\nAdded in version 3.8: Added --module option that allows running an executable module.\\n\\nMain options¶\\n\\nAt least one of the following options must be specified when invoking trace. The --listfuncs option is mutually exclusive with the --trace and --count options. When --listfuncs is provided, neither --count nor --trace are accepted, and vice versa.\\n\\nModifiers¶\\n\\nFilters¶\\n\\nThese options may be repeated multiple times.\\n\\nProgrammatic Interface¶\\n\\nA simple example demonstrating the use of the programmatic interface:\\n\\nimport sys\\nimport trace\\n\\n# create a Trace object, telling it what to ignore, and whether to\\n# do tracing or line-counting or both.\\ntracer = trace.Trace(\\n ignoredirs=[sys.prefix, sys.exec_prefix],\\n trace=0,\\n count=1)\\n\\n# run the new command using the given tracer\\ntracer.run(\\'main()\\')\\n\\n# make a report, placing output in the current directory\\nr = tracer.results()\\nr.write_results(show_missing=True, coverdir=\".\")\\n\\nTable of Contents\\n\\ntrace — Trace or track Python statement execution\\n\\nCommand-Line Usage\\n\\nMain options\\n\\nModifiers\\n\\nFilters\\n\\nProgrammatic Interface\\n\\nPrevious topic\\n\\ntimeit — Measure execution time of small code snippets\\n\\nNext topic\\n\\ntracemalloc — Trace memory allocations\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nDebugging and profiling »\\n\\ntrace — Trace or track Python statement execution\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\traceback.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Runtime Services »\\n\\ntraceback — Print or retrieve a stack traceback\\n\\n|\\n\\ntraceback — Print or retrieve a stack traceback¶\\n\\nSource code: Lib/traceback.py\\n\\nThis 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.\\n\\nThe module uses traceback objects — these are objects of type types.TracebackType, which are assigned to the __traceback__ field of BaseException instances.\\n\\nSee also\\n\\nThe module’s API can be divided into two parts:\\n\\nModule-level functions offering basic functionality, which are useful for interactive inspection of exceptions and tracebacks.\\n\\nTracebackException class and its helper classes StackSummary and 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.\\n\\nAdded in version 3.13: Output is colorized by default and can be controlled using environment variables.\\n\\nModule-Level Functions¶\\n\\nTracebackException Objects¶\\n\\nAdded in version 3.5.\\n\\nTracebackException 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 traceback and frame objects. In addition, they expose more options to configure the output compared to the module-level functions described above.\\n\\nStackSummary Objects¶\\n\\nAdded in version 3.5.\\n\\nStackSummary objects represent a call stack ready for formatting.\\n\\nFrameSummary Objects¶\\n\\nAdded in version 3.5.\\n\\nA FrameSummary object represents a single frame in a traceback.\\n\\nExamples of Using the Module-Level Functions¶\\n\\nThis simple example implements a basic read-eval-print loop, similar to (but less useful than) the standard Python interactive interpreter loop. For a more complete implementation of the interpreter loop, refer to the code module.\\n\\nimport sys, traceback\\n\\ndef run_user_code(envdir):\\n source = input(\">>> \")\\n try:\\n exec(source, envdir)\\n except Exception:\\n print(\"Exception in user code:\")\\n print(\"-\"*60)\\n traceback.print_exc(file=sys.stdout)\\n print(\"-\"*60)\\n\\nenvdir = {}\\nwhile True:\\n run_user_code(envdir)\\n\\nThe following example demonstrates the different ways to print and format the exception and traceback:\\n\\nimport sys, traceback\\n\\ndef lumberjack():\\n bright_side_of_life()\\n\\ndef bright_side_of_life():\\n return tuple()[0]\\n\\ntry:\\n lumberjack()\\nexcept IndexError as exc:\\n print(\"*** print_tb:\")\\n traceback.print_tb(exc.__traceback__, limit=1, file=sys.stdout)\\n print(\"*** print_exception:\")\\n traceback.print_exception(exc, limit=2, file=sys.stdout)\\n print(\"*** print_exc:\")\\n traceback.print_exc(limit=2, file=sys.stdout)\\n print(\"*** format_exc, first and last line:\")\\n formatted_lines = traceback.format_exc().splitlines()\\n print(formatted_lines[0])\\n print(formatted_lines[-1])\\n print(\"*** format_exception:\")\\n print(repr(traceback.format_exception(exc)))\\n print(\"*** extract_tb:\")\\n print(repr(traceback.extract_tb(exc.__traceback__)))\\n print(\"*** format_tb:\")\\n print(repr(traceback.format_tb(exc.__traceback__)))\\n print(\"*** tb_lineno:\", exc.__traceback__.tb_lineno)\\n\\nThe output for the example would look similar to this:\\n\\n*** print_tb:\\n File \"\", line 10, in \\n lumberjack()\\n ~~~~~~~~~~^^\\n*** print_exception:\\nTraceback (most recent call last):\\n File \"\", line 10, in \\n lumberjack()\\n ~~~~~~~~~~^^\\n File \"\", line 4, in lumberjack\\n bright_side_of_life()\\n ~~~~~~~~~~~~~~~~~~~^^\\nIndexError: tuple index out of range\\n*** print_exc:\\nTraceback (most recent call last):\\n File \"\", line 10, in \\n lumberjack()\\n ~~~~~~~~~~^^\\n File \"\", line 4, in lumberjack\\n bright_side_of_life()\\n ~~~~~~~~~~~~~~~~~~~^^\\nIndexError: tuple index out of range\\n*** format_exc, first and last line:\\nTraceback (most recent call last):\\nIndexError: tuple index out of range\\n*** format_exception:\\n[\\'Traceback (most recent call last):\\\\n\\',\\n \\' File \"\", line 10, in \\\\n lumberjack()\\\\n ~~~~~~~~~~^^\\\\n\\',\\n \\' File \"\", line 4, in lumberjack\\\\n bright_side_of_life()\\\\n ~~~~~~~~~~~~~~~~~~~^^\\\\n\\',\\n \\' File \"\", line 7, in bright_side_of_life\\\\n return tuple()[0]\\\\n ~~~~~~~^^^\\\\n\\',\\n \\'IndexError: tuple index out of range\\\\n\\']\\n*** extract_tb:\\n[, line 10 in >,\\n , line 4 in lumberjack>,\\n , line 7 in bright_side_of_life>]\\n*** format_tb:\\n[\\' File \"\", line 10, in \\\\n lumberjack()\\\\n ~~~~~~~~~~^^\\\\n\\',\\n \\' File \"\", line 4, in lumberjack\\\\n bright_side_of_life()\\\\n ~~~~~~~~~~~~~~~~~~~^^\\\\n\\',\\n \\' File \"\", line 7, in bright_side_of_life\\\\n return tuple()[0]\\\\n ~~~~~~~^^^\\\\n\\']\\n*** tb_lineno: 10\\n\\nThe following example shows the different ways to print and format the stack:\\n\\n>>> import traceback\\n>>> def another_function():\\n... lumberstack()\\n...\\n>>> def lumberstack():\\n... traceback.print_stack()\\n... print(repr(traceback.extract_stack()))\\n... print(repr(traceback.format_stack()))\\n...\\n>>> another_function()\\n File \"\", line 10, in \\n another_function()\\n File \"\", line 3, in another_function\\n lumberstack()\\n File \"\", line 6, in lumberstack\\n traceback.print_stack()\\n[(\\'\\', 10, \\'\\', \\'another_function()\\'),\\n (\\'\\', 3, \\'another_function\\', \\'lumberstack()\\'),\\n (\\'\\', 7, \\'lumberstack\\', \\'print(repr(traceback.extract_stack()))\\')]\\n[\\' File \"\", line 10, in \\\\n another_function()\\\\n\\',\\n \\' File \"\", line 3, in another_function\\\\n lumberstack()\\\\n\\',\\n \\' File \"\", line 8, in lumberstack\\\\n print(repr(traceback.format_stack()))\\\\n\\']\\n\\nThis last example demonstrates the final few formatting functions:\\n\\n>>> import traceback\\n>>> traceback.format_list([(\\'spam.py\\', 3, \\'\\', \\'spam.eggs()\\'),\\n... (\\'eggs.py\\', 42, \\'eggs\\', \\'return \"bacon\"\\')])\\n[\\' File \"spam.py\", line 3, in \\\\n spam.eggs()\\\\n\\',\\n \\' File \"eggs.py\", line 42, in eggs\\\\n return \"bacon\"\\\\n\\']\\n>>> an_error = IndexError(\\'tuple index out of range\\')\\n>>> traceback.format_exception_only(an_error)\\n[\\'IndexError: tuple index out of range\\\\n\\']\\n\\nExamples of Using TracebackException¶\\n\\nWith the helper class, we have more options:\\n\\n>>> import sys\\n>>> from traceback import TracebackException\\n>>>\\n>>> def lumberjack():\\n... bright_side_of_life()\\n...\\n>>> def bright_side_of_life():\\n... t = \"bright\", \"side\", \"of\", \"life\"\\n... return t[5]\\n...\\n>>> try:\\n... lumberjack()\\n... except IndexError as e:\\n... exc = e\\n...\\n>>> try:\\n... try:\\n... lumberjack()\\n... except:\\n... 1/0\\n... except Exception as e:\\n... chained_exc = e\\n...\\n>>> # limit works as with the module-level functions\\n>>> TracebackException.from_exception(exc, limit=-2).print()\\nTraceback (most recent call last):\\n File \"\", line 6, in lumberjack\\n bright_side_of_life()\\n ~~~~~~~~~~~~~~~~~~~^^\\n File \"\", line 10, in bright_side_of_life\\n return t[5]\\n ~^^^\\nIndexError: tuple index out of range\\n\\n>>> # capture_locals adds local variables in frames\\n>>> TracebackException.from_exception(exc, limit=-2, capture_locals=True).print()\\nTraceback (most recent call last):\\n File \"\", line 6, in lumberjack\\n bright_side_of_life()\\n ~~~~~~~~~~~~~~~~~~~^^\\n File \"\", line 10, in bright_side_of_life\\n return t[5]\\n ~^^^\\n t = (\"bright\", \"side\", \"of\", \"life\")\\nIndexError: tuple index out of range\\n\\n>>> # The *chain* kwarg to print() controls whether chained\\n>>> # exceptions are displayed\\n>>> TracebackException.from_exception(chained_exc).print()\\nTraceback (most recent call last):\\n File \"\", line 4, in \\n lumberjack()\\n ~~~~~~~~~~^^\\n File \"\", line 7, in lumberjack\\n bright_side_of_life()\\n ~~~~~~~~~~~~~~~~~~~^^\\n File \"\", line 11, in bright_side_of_life\\n return t[5]\\n ~^^^\\nIndexError: tuple index out of range\\n\\nDuring handling of the above exception, another exception occurred:\\n\\nTraceback (most recent call last):\\n File \"\", line 6, in \\n 1/0\\n ~^~\\nZeroDivisionError: division by zero\\n\\n>>> TracebackException.from_exception(chained_exc).print(chain=False)\\nTraceback (most recent call last):\\n File \"\", line 6, in \\n 1/0\\n ~^~\\nZeroDivisionError: division by zero\\n\\nTable of Contents\\n\\ntraceback — Print or retrieve a stack traceback\\n\\nModule-Level Functions\\n\\nTracebackException Objects\\n\\nStackSummary Objects\\n\\nFrameSummary Objects\\n\\nExamples of Using the Module-Level Functions\\n\\nExamples of Using TracebackException\\n\\nPrevious topic\\n\\natexit — Exit handlers\\n\\nNext topic\\n\\n__future__ — Future statement definitions\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Runtime Services »\\n\\ntraceback — Print or retrieve a stack traceback\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\tracemalloc.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nDebugging and profiling »\\n\\ntracemalloc — Trace memory allocations\\n\\n|\\n\\ntracemalloc — Trace memory allocations¶\\n\\nAdded in version 3.4.\\n\\nSource code: Lib/tracemalloc.py\\n\\nThe tracemalloc module is a debug tool to trace memory blocks allocated by Python. It provides the following information:\\n\\nTraceback where an object was allocated\\n\\nStatistics on allocated memory blocks per filename and per line number: total size, number and average size of allocated memory blocks\\n\\nCompute the differences between two snapshots to detect memory leaks\\n\\nTo trace most memory blocks allocated by Python, the module should be started as early as possible by setting the PYTHONTRACEMALLOC environment variable to 1, or by using -X tracemalloc command line option. The tracemalloc.start() function can be called at runtime to start tracing Python memory allocations.\\n\\nBy default, a trace of an allocated memory block only stores the most recent frame (1 frame). To store 25 frames at startup: set the PYTHONTRACEMALLOC environment variable to 25, or use the -X tracemalloc=25 command line option.\\n\\nExamples¶\\n\\nDisplay the top 10¶\\n\\nDisplay the 10 files allocating the most memory:\\n\\nimport tracemalloc\\n\\ntracemalloc.start()\\n\\n# ... run your application ...\\n\\nsnapshot = tracemalloc.take_snapshot()\\ntop_stats = snapshot.statistics(\\'lineno\\')\\n\\nprint(\"[ Top 10 ]\")\\nfor stat in top_stats[:10]:\\n print(stat)\\n\\nExample of output of the Python test suite:\\n\\n[ Top 10 ]\\n:716: size=4855 KiB, count=39328, average=126 B\\n:284: size=521 KiB, count=3199, average=167 B\\n/usr/lib/python3.4/collections/__init__.py:368: size=244 KiB, count=2315, average=108 B\\n/usr/lib/python3.4/unittest/case.py:381: size=185 KiB, count=779, average=243 B\\n/usr/lib/python3.4/unittest/case.py:402: size=154 KiB, count=378, average=416 B\\n/usr/lib/python3.4/abc.py:133: size=88.7 KiB, count=347, average=262 B\\n:1446: size=70.4 KiB, count=911, average=79 B\\n:1454: size=52.0 KiB, count=25, average=2131 B\\n:5: size=49.7 KiB, count=148, average=344 B\\n/usr/lib/python3.4/sysconfig.py:411: size=48.0 KiB, count=1, average=48.0 KiB\\n\\nWe can see that Python loaded 4855 KiB data (bytecode and constants) from modules and that the collections module allocated 244 KiB to build namedtuple types.\\n\\nSee Snapshot.statistics() for more options.\\n\\nCompute differences¶\\n\\nTake two snapshots and display the differences:\\n\\nimport tracemalloc\\ntracemalloc.start()\\n# ... start your application ...\\n\\nsnapshot1 = tracemalloc.take_snapshot()\\n# ... call the function leaking memory ...\\nsnapshot2 = tracemalloc.take_snapshot()\\n\\ntop_stats = snapshot2.compare_to(snapshot1, \\'lineno\\')\\n\\nprint(\"[ Top 10 differences ]\")\\nfor stat in top_stats[:10]:\\n print(stat)\\n\\nExample of output before/after running some tests of the Python test suite:\\n\\n[ Top 10 differences ]\\n:716: size=8173 KiB (+4428 KiB), count=71332 (+39369), average=117 B\\n/usr/lib/python3.4/linecache.py:127: size=940 KiB (+940 KiB), count=8106 (+8106), average=119 B\\n/usr/lib/python3.4/unittest/case.py:571: size=298 KiB (+298 KiB), count=589 (+589), average=519 B\\n:284: size=1005 KiB (+166 KiB), count=7423 (+1526), average=139 B\\n/usr/lib/python3.4/mimetypes.py:217: size=112 KiB (+112 KiB), count=1334 (+1334), average=86 B\\n/usr/lib/python3.4/http/server.py:848: size=96.0 KiB (+96.0 KiB), count=1 (+1), average=96.0 KiB\\n/usr/lib/python3.4/inspect.py:1465: size=83.5 KiB (+83.5 KiB), count=109 (+109), average=784 B\\n/usr/lib/python3.4/unittest/mock.py:491: size=77.7 KiB (+77.7 KiB), count=143 (+143), average=557 B\\n/usr/lib/python3.4/urllib/parse.py:476: size=71.8 KiB (+71.8 KiB), count=969 (+969), average=76 B\\n/usr/lib/python3.4/contextlib.py:38: size=67.2 KiB (+67.2 KiB), count=126 (+126), average=546 B\\n\\nWe can see that Python has loaded 8173 KiB of module data (bytecode and constants), and that this is 4428 KiB more than had been loaded before the tests, when the previous snapshot was taken. Similarly, the linecache module has cached 940 KiB of Python source code to format tracebacks, all of it since the previous snapshot.\\n\\nIf the system has little free memory, snapshots can be written on disk using the Snapshot.dump() method to analyze the snapshot offline. Then use the Snapshot.load() method reload the snapshot.\\n\\nGet the traceback of a memory block¶\\n\\nCode to display the traceback of the biggest memory block:\\n\\nimport tracemalloc\\n\\n# Store 25 frames\\ntracemalloc.start(25)\\n\\n# ... run your application ...\\n\\nsnapshot = tracemalloc.take_snapshot()\\ntop_stats = snapshot.statistics(\\'traceback\\')\\n\\n# pick the biggest memory block\\nstat = top_stats[0]\\nprint(\"%s memory blocks: %.1f KiB\" % (stat.count, stat.size / 1024))\\nfor line in stat.traceback.format():\\n print(line)\\n\\nExample of output of the Python test suite (traceback limited to 25 frames):\\n\\n903 memory blocks: 870.1 KiB\\n File \"\", line 716\\n File \"\", line 1036\\n File \"\", line 934\\n File \"\", line 1068\\n File \"\", line 619\\n File \"\", line 1581\\n File \"\", line 1614\\n File \"/usr/lib/python3.4/doctest.py\", line 101\\n import pdb\\n File \"\", line 284\\n File \"\", line 938\\n File \"\", line 1068\\n File \"\", line 619\\n File \"\", line 1581\\n File \"\", line 1614\\n File \"/usr/lib/python3.4/test/support/__init__.py\", line 1728\\n import doctest\\n File \"/usr/lib/python3.4/test/test_pickletools.py\", line 21\\n support.run_doctest(pickletools)\\n File \"/usr/lib/python3.4/test/regrtest.py\", line 1276\\n test_runner()\\n File \"/usr/lib/python3.4/test/regrtest.py\", line 976\\n display_failure=not verbose)\\n File \"/usr/lib/python3.4/test/regrtest.py\", line 761\\n match_tests=ns.match_tests)\\n File \"/usr/lib/python3.4/test/regrtest.py\", line 1563\\n main()\\n File \"/usr/lib/python3.4/test/__main__.py\", line 3\\n regrtest.main_in_temp_cwd()\\n File \"/usr/lib/python3.4/runpy.py\", line 73\\n exec(code, run_globals)\\n File \"/usr/lib/python3.4/runpy.py\", line 160\\n \"__main__\", fname, loader, pkg_name)\\n\\nWe can see that the most memory was allocated in the importlib module to load data (bytecode and constants) from modules: 870.1 KiB. The traceback is where the importlib loaded data most recently: on the import pdb line of the doctest module. The traceback may change if a new module is loaded.\\n\\nPretty top¶\\n\\nCode to display the 10 lines allocating the most memory with a pretty output, ignoring and files:\\n\\nimport linecache\\nimport os\\nimport tracemalloc\\n\\ndef display_top(snapshot, key_type=\\'lineno\\', limit=10):\\n snapshot = snapshot.filter_traces((\\n tracemalloc.Filter(False, \"\"),\\n tracemalloc.Filter(False, \"\"),\\n ))\\n top_stats = snapshot.statistics(key_type)\\n\\n print(\"Top %s lines\" % limit)\\n for index, stat in enumerate(top_stats[:limit], 1):\\n frame = stat.traceback[0]\\n print(\"#%s: %s:%s: %.1f KiB\"\\n % (index, frame.filename, frame.lineno, stat.size / 1024))\\n line = linecache.getline(frame.filename, frame.lineno).strip()\\n if line:\\n print(\\' %s\\' % line)\\n\\n other = top_stats[limit:]\\n if other:\\n size = sum(stat.size for stat in other)\\n print(\"%s other: %.1f KiB\" % (len(other), size / 1024))\\n total = sum(stat.size for stat in top_stats)\\n print(\"Total allocated size: %.1f KiB\" % (total / 1024))\\n\\ntracemalloc.start()\\n\\n# ... run your application ...\\n\\nsnapshot = tracemalloc.take_snapshot()\\ndisplay_top(snapshot)\\n\\nExample of output of the Python test suite:\\n\\nTop 10 lines\\n#1: Lib/base64.py:414: 419.8 KiB\\n _b85chars2 = [(a + b) for a in _b85chars for b in _b85chars]\\n#2: Lib/base64.py:306: 419.8 KiB\\n _a85chars2 = [(a + b) for a in _a85chars for b in _a85chars]\\n#3: collections/__init__.py:368: 293.6 KiB\\n exec(class_definition, namespace)\\n#4: Lib/abc.py:133: 115.2 KiB\\n cls = super().__new__(mcls, name, bases, namespace)\\n#5: unittest/case.py:574: 103.1 KiB\\n testMethod()\\n#6: Lib/linecache.py:127: 95.4 KiB\\n lines = fp.readlines()\\n#7: urllib/parse.py:476: 71.8 KiB\\n for a in _hexdig for b in _hexdig}\\n#8: :5: 62.0 KiB\\n#9: Lib/_weakrefset.py:37: 60.0 KiB\\n self.data = set()\\n#10: Lib/base64.py:142: 59.8 KiB\\n _b32tab2 = [a + b for a in _b32tab for b in _b32tab]\\n6220 other: 3602.8 KiB\\nTotal allocated size: 5303.1 KiB\\n\\nSee Snapshot.statistics() for more options.\\n\\nRecord the current and peak size of all traced memory blocks¶\\n\\nThe following code computes two sums like 0 + 1 + 2 + ... inefficiently, by creating a list of those numbers. This list consumes a lot of memory temporarily. We can use get_traced_memory() and reset_peak() to observe the small memory usage after the sum is computed as well as the peak memory usage during the computations:\\n\\nimport tracemalloc\\n\\ntracemalloc.start()\\n\\n# Example code: compute a sum with a large temporary list\\nlarge_sum = sum(list(range(100000)))\\n\\nfirst_size, first_peak = tracemalloc.get_traced_memory()\\n\\ntracemalloc.reset_peak()\\n\\n# Example code: compute a sum with a small temporary list\\nsmall_sum = sum(list(range(1000)))\\n\\nsecond_size, second_peak = tracemalloc.get_traced_memory()\\n\\nprint(f\"{first_size=}, {first_peak=}\")\\nprint(f\"{second_size=}, {second_peak=}\")\\n\\nOutput:\\n\\nfirst_size=664, first_peak=3592984\\nsecond_size=804, second_peak=29704\\n\\nUsing reset_peak() ensured we could accurately record the peak during the computation of small_sum, even though it is much smaller than the overall peak size of memory blocks since the start() call. Without the call to reset_peak(), second_peak would still be the peak from the computation large_sum (that is, equal to first_peak). In this case, both peaks are much higher than the final memory usage, and which suggests we could optimise (by removing the unnecessary call to list, and writing sum(range(...))).\\n\\nAPI¶\\n\\nFunctions¶\\n\\nDomainFilter¶\\n\\nFilter¶\\n\\nFrame¶\\n\\nSnapshot¶\\n\\nStatistic¶\\n\\nStatisticDiff¶\\n\\nTrace¶\\n\\nTraceback¶\\n\\nTable of Contents\\n\\ntracemalloc — Trace memory allocations\\n\\nExamples\\n\\nDisplay the top 10\\n\\nCompute differences\\n\\nGet the traceback of a memory block\\n\\nPretty top\\n\\nRecord the current and peak size of all traced memory blocks\\n\\nAPI\\n\\nFunctions\\n\\nDomainFilter\\n\\nFilter\\n\\nFrame\\n\\nSnapshot\\n\\nStatistic\\n\\nStatisticDiff\\n\\nTrace\\n\\nTraceback\\n\\nPrevious topic\\n\\ntrace — Trace or track Python statement execution\\n\\nNext topic\\n\\nSoftware Packaging and Distribution\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nDebugging and profiling »\\n\\ntracemalloc — Trace memory allocations\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\tty.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nUnix-specific services »\\n\\ntty — Terminal control functions\\n\\n|\\n\\ntty — Terminal control functions¶\\n\\nSource code: Lib/tty.py\\n\\nThe tty module defines functions for putting the tty into cbreak and raw modes.\\n\\nAvailability: Unix.\\n\\nBecause it requires the termios module, it will work only on Unix.\\n\\nThe tty module defines the following functions:\\n\\nSee also\\n\\nPrevious topic\\n\\ntermios — POSIX style tty control\\n\\nNext topic\\n\\npty — Pseudo-terminal utilities\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nUnix-specific services »\\n\\ntty — Terminal control functions\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\turtle.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nGraphical user interfaces with Tk »\\n\\nturtle — Turtle graphics\\n\\n|\\n\\nturtle — Turtle graphics¶\\n\\nSource code: Lib/turtle.py\\n\\nIntroduction¶\\n\\nTurtle graphics is an implementation of the popular geometric drawing tools introduced in Logo, developed by Wally Feurzeig, Seymour Papert and Cynthia Solomon in 1967.\\n\\nThis is an 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 Requirements for optional modules.\\n\\nGet started¶\\n\\nImagine a robotic turtle starting at (0, 0) in the x-y plane. After an import turtle, give it the command turtle.forward(15), and it moves (on-screen!) 15 pixels in the direction it is facing, drawing a line as it moves. Give it the command turtle.right(25), and it rotates in-place 25 degrees clockwise.\\n\\nTurtle star\\n\\nTurtle can draw intricate shapes using programs that repeat simple moves.\\n\\n../_images/turtle-star.png\\n\\nIn 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.\\n\\nIt’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.\\n\\nTurtle 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.\\n\\nTutorial¶\\n\\nNew users should start here. In this tutorial we’ll explore some of the basics of turtle drawing.\\n\\nStarting a turtle environment¶\\n\\nIn a Python shell, import all the objects of the turtle module:\\n\\nfrom turtle import *\\n\\nIf you run into a No module named \\'_tkinter\\' error, you’ll have to install the Tk interface package on your system.\\n\\nBasic drawing¶\\n\\nSend the turtle forward 100 steps:\\n\\nforward(100)\\n\\nYou 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):\\n\\nleft(120)\\n\\nLet’s continue by drawing a triangle:\\n\\nforward(100)\\nleft(120)\\nforward(100)\\n\\nNotice how the turtle, represented by an arrow, points in different directions as you steer it.\\n\\nExperiment with those commands, and also with backward() and right().\\n\\nPen control¶\\n\\nTry changing the color - for example, color(\\'blue\\') - and width of the line - for example, width(3) - and then drawing again.\\n\\nYou can also move the turtle around without drawing, by lifting up the pen: up() before moving. To start drawing again, use down().\\n\\nThe turtle’s position¶\\n\\nSend your turtle back to its starting-point (useful if it has disappeared off-screen):\\n\\nhome()\\n\\nThe 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:\\n\\npos()\\n\\nHome is at (0, 0).\\n\\nAnd after a while, it will probably help to clear the window so we can start anew:\\n\\nclearscreen()\\n\\nMaking algorithmic patterns¶\\n\\nUsing loops, it’s possible to build up geometric patterns:\\n\\nfor steps in range(100):\\n for c in (\\'blue\\', \\'red\\', \\'green\\'):\\n color(c)\\n forward(steps)\\n right(30)\\n\\nwhich of course, are limited only by the imagination!\\n\\nLet’s draw the star shape at the top of this page. We want red lines, filled in with yellow:\\n\\ncolor(\\'red\\')\\nfillcolor(\\'yellow\\')\\n\\nJust as up() and down() determine whether lines will be drawn, filling can be turned on and off:\\n\\nbegin_fill()\\n\\nNext we’ll create a loop:\\n\\nwhile True:\\n forward(200)\\n left(170)\\n if abs(pos()) < 1:\\n break\\n\\nabs(pos()) < 1 is a good way to know when the turtle is back at its home position.\\n\\nFinally, complete the filling:\\n\\nend_fill()\\n\\n(Note that filling only actually takes place when you give the end_fill() command.)\\n\\nHow to…¶\\n\\nThis section covers some typical turtle use-cases and approaches.\\n\\nGet started as quickly as possible¶\\n\\nOne 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).\\n\\nThe turtle module makes this possible by exposing all its basic functionality as functions, available with from turtle import *. The turtle graphics tutorial covers this approach.\\n\\nIt’s worth noting that many of the turtle commands also have even more terse equivalents, such as fd() for forward(). These are especially useful when working with learners for whom typing is not a skill.\\n\\nYou’ll need to have the 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.\\n\\nAutomatically begin and end filling¶\\n\\nStarting with Python 3.14, you can use the fill() context manager instead of begin_fill() and end_fill() to automatically begin and end fill. Here is an example:\\n\\nwith fill():\\n for i in range(4):\\n forward(100)\\n right(90)\\n\\nforward(200)\\n\\nThe code above is equivalent to:\\n\\nbegin_fill()\\nfor i in range(4):\\n forward(100)\\n right(90)\\nend_fill()\\n\\nforward(200)\\n\\nUse the turtle module namespace¶\\n\\nUsing 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).\\n\\nThe solution is to use import turtle - fd() becomes turtle.fd(), width() becomes turtle.width() and so on. (If typing “turtle” over and over again becomes tedious, use for example import turtle as t instead.)\\n\\nUse turtle graphics in a script¶\\n\\nIt’s recommended to use the turtle module namespace as described immediately above, for example:\\n\\nimport turtle as t\\nfrom random import random\\n\\nfor i in range(100):\\n steps = int(random() * 100)\\n angle = int(random() * 360)\\n t.right(angle)\\n t.fd(steps)\\n\\nAnother step is also required though - as soon as the script ends, Python will also close the turtle’s window. Add:\\n\\nt.mainloop()\\n\\nto 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.\\n\\nUse object-oriented turtle graphics¶\\n\\nSee also\\n\\nExplanation of the object-oriented interface\\n\\nOther 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.\\n\\nIn this approach, the various turtle commands are methods of objects (mostly of Turtle objects). You can use the object-oriented approach in the shell, but it would be more typical in a Python script.\\n\\nThe example above then becomes:\\n\\nfrom turtle import Turtle\\nfrom random import random\\n\\nt = Turtle()\\nfor i in range(100):\\n steps = int(random() * 100)\\n angle = int(random() * 360)\\n t.right(angle)\\n t.fd(steps)\\n\\nt.screen.mainloop()\\n\\nNote the last line. t.screen is an instance of the Screen that a Turtle instance exists on; it’s created automatically along with the turtle.\\n\\nThe turtle’s screen can be customised, for example:\\n\\nt.screen.title(\\'Object-oriented turtle demo\\')\\nt.screen.bgcolor(\"orange\")\\n\\nTurtle graphics reference¶\\n\\nNote\\n\\nIn the following documentation the argument list for functions is given. Methods, of course, have the additional first argument self which is omitted here.\\n\\nTurtle methods¶\\n\\nMethods of TurtleScreen/Screen¶\\n\\nMethods of RawTurtle/Turtle and corresponding functions¶\\n\\nMost of the examples in this section refer to a Turtle instance called turtle.\\n\\nTurtle motion¶\\n\\nTell Turtle’s state¶\\n\\nSettings for measurement¶\\n\\nPen control¶\\n\\nDrawing state¶\\n\\nColor control¶\\n\\nSee also: Screen method colormode().\\n\\nFilling¶\\n\\nMore drawing control¶\\n\\nTurtle state¶\\n\\nVisibility¶\\n\\nAppearance¶\\n\\nUsing events¶\\n\\nSpecial Turtle methods¶\\n\\nCompound shapes¶\\n\\nTo use compound turtle shapes, which consist of several polygons of different color, you must use the helper class Shape explicitly as described below:\\n\\nCreate an empty Shape object of type “compound”.\\n\\nAdd as many components to this object as desired, using the addcomponent() method.\\n\\nFor example:\\n\\n>>> s = Shape(\"compound\")\\n>>> poly1 = ((0,0),(10,-5),(0,10),(-10,-5))\\n>>> s.addcomponent(poly1, \"red\", \"blue\")\\n>>> poly2 = ((0,0),(10,-5),(-10,-5))\\n>>> s.addcomponent(poly2, \"blue\", \"red\")\\n\\nNow add the Shape to the Screen’s shapelist and use it:\\n\\n>>> register_shape(\"myshape\", s)\\n>>> shape(\"myshape\")\\n\\nNote\\n\\nThe Shape class is used internally by the register_shape() method in different ways. The application programmer has to deal with the Shape class only when using compound shapes like shown above!\\n\\nMethods of TurtleScreen/Screen and corresponding functions¶\\n\\nMost of the examples in this section refer to a TurtleScreen instance called screen.\\n\\nWindow control¶\\n\\nAnimation control¶\\n\\nSee also the RawTurtle/Turtle method speed().\\n\\nUsing screen events¶\\n\\nInput methods¶\\n\\nSettings and special methods¶\\n\\nMethods specific to Screen, not inherited from TurtleScreen¶\\n\\nPublic classes¶\\n\\nExplanation¶\\n\\nA 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.\\n\\nA Turtle instance will automatically create a Screen instance if one is not already present.\\n\\nTurtle is a subclass of 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 tkinter.Canvas, ScrolledCanvas or TurtleScreen.\\n\\nTurtleScreen is the basic drawing surface for a turtle. Screen is a subclass of TurtleScreen, and includes some additional methods for managing its appearance (including size and title) and behaviour. TurtleScreen’s constructor needs a tkinter.Canvas or a ScrolledCanvas as an argument.\\n\\nThe functional interface for turtle graphics uses the various methods of Turtle and TurtleScreen/Screen. Behind the scenes, a screen object is automatically created whenever a function derived from a Screen method is called. Similarly, a turtle object is automatically created whenever any of the functions derived from a Turtle method is called.\\n\\nTo use multiple turtles on a screen, the object-oriented interface must be used.\\n\\nHelp and configuration¶\\n\\nHow to use help¶\\n\\nThe public methods of the Screen and Turtle classes are documented extensively via docstrings. So these can be used as online-help via the Python help facilities:\\n\\nWhen using IDLE, tooltips show the signatures and first lines of the docstrings of typed in function-/method calls.\\n\\nCalling help() on methods or functions displays the docstrings:\\n\\n>>> help(Screen.bgcolor)\\nHelp on method bgcolor in module turtle:\\n\\nbgcolor(self, *args) unbound turtle.Screen method\\n Set or return backgroundcolor of the TurtleScreen.\\n\\n Arguments (if given): a color string or three numbers\\n in the range 0..colormode or a 3-tuple of such numbers.\\n\\n\\n >>> screen.bgcolor(\"orange\")\\n >>> screen.bgcolor()\\n \"orange\"\\n >>> screen.bgcolor(0.5,0,0.5)\\n >>> screen.bgcolor()\\n \"#800080\"\\n\\n>>> help(Turtle.penup)\\nHelp on method penup in module turtle:\\n\\npenup(self) unbound turtle.Turtle method\\n Pull the pen up -- no drawing when moving.\\n\\n Aliases: penup | pu | up\\n\\n No argument\\n\\n >>> turtle.penup()\\n\\nThe docstrings of the functions which are derived from methods have a modified form:\\n\\n>>> help(bgcolor)\\nHelp on function bgcolor in module turtle:\\n\\nbgcolor(*args)\\n Set or return backgroundcolor of the TurtleScreen.\\n\\n Arguments (if given): a color string or three numbers\\n in the range 0..colormode or a 3-tuple of such numbers.\\n\\n Example::\\n\\n >>> bgcolor(\"orange\")\\n >>> bgcolor()\\n \"orange\"\\n >>> bgcolor(0.5,0,0.5)\\n >>> bgcolor()\\n \"#800080\"\\n\\n>>> help(penup)\\nHelp on function penup in module turtle:\\n\\npenup()\\n Pull the pen up -- no drawing when moving.\\n\\n Aliases: penup | pu | up\\n\\n No argument\\n\\n Example:\\n >>> penup()\\n\\nThese modified docstrings are created automatically together with the function definitions that are derived from the methods at import time.\\n\\nTranslation of docstrings into different languages¶\\n\\nThere is a utility to create a dictionary the keys of which are the method names and the values of which are the docstrings of the public methods of the classes Screen and Turtle.\\n\\nIf you (or your students) want to use turtle with online help in your native language, you have to translate the docstrings and save the resulting file as e.g. turtle_docstringdict_german.py.\\n\\nIf you have an appropriate entry in your turtle.cfg file this dictionary will be read in at import time and will replace the original English docstrings.\\n\\nAt the time of this writing there are docstring dictionaries in German and in Italian. (Requests please to glingl@aon.at.)\\n\\nHow to configure Screen and Turtles¶\\n\\nThe built-in default configuration mimics the appearance and behaviour of the old turtle module in order to retain best possible compatibility with it.\\n\\nIf you want to use a different configuration which better reflects the features of this module or which better fits to your needs, e.g. for use in a classroom, you can prepare a configuration file turtle.cfg which will be read at import time and modify the configuration according to its settings.\\n\\nThe built in configuration would correspond to the following turtle.cfg:\\n\\nwidth = 0.5\\nheight = 0.75\\nleftright = None\\ntopbottom = None\\ncanvwidth = 400\\ncanvheight = 300\\nmode = standard\\ncolormode = 1.0\\ndelay = 10\\nundobuffersize = 1000\\nshape = classic\\npencolor = black\\nfillcolor = black\\nresizemode = noresize\\nvisible = True\\nlanguage = english\\nexampleturtle = turtle\\nexamplescreen = screen\\ntitle = Python Turtle Graphics\\nusing_IDLE = False\\n\\nShort explanation of selected entries:\\n\\nThe first four lines correspond to the arguments of the Screen.setup method.\\n\\nLine 5 and 6 correspond to the arguments of the method Screen.screensize.\\n\\nshape can be any of the built-in shapes, e.g: arrow, turtle, etc. For more info try help(shape).\\n\\nIf you want to use no fill color (i.e. make the turtle transparent), you have to write fillcolor = \"\" (but all nonempty strings must not have quotes in the cfg file).\\n\\nIf you want to reflect the turtle its state, you have to use resizemode = auto.\\n\\nIf you set e.g. language = italian the docstringdict turtle_docstringdict_italian.py will be loaded at import time (if present on the import path, e.g. in the same directory as turtle).\\n\\nThe entries exampleturtle and examplescreen define the names of these objects as they occur in the docstrings. The transformation of method-docstrings to function-docstrings will delete these names from the docstrings.\\n\\nusing_IDLE: Set this to True if you regularly work with IDLE and its -n switch (“no subprocess”). This will prevent exitonclick() to enter the mainloop.\\n\\nThere can be a turtle.cfg file in the directory where turtle is stored and an additional one in the current working directory. The latter will override the settings of the first one.\\n\\nThe Lib/turtledemo directory contains a turtle.cfg file. You can study it as an example and see its effects when running the demos (preferably not from within the demo-viewer).\\n\\nturtledemo — Demo scripts¶\\n\\nThe turtledemo package includes a set of demo scripts. These scripts can be run and viewed using the supplied demo viewer as follows:\\n\\npython -m turtledemo\\n\\nAlternatively, you can run the demo scripts individually. For example,\\n\\npython -m turtledemo.bytedesign\\n\\nThe turtledemo package directory contains:\\n\\nA demo viewer __main__.py which can be used to view the sourcecode of the scripts and run them at the same time.\\n\\nMultiple scripts demonstrating different features of the turtle module. Examples can be accessed via the Examples menu. They can also be run standalone.\\n\\nA turtle.cfg file which serves as an example of how to write and use such files.\\n\\nThe demo scripts are:\\n\\nName Description Features bytedesign complex classical\\nturtle graphics pattern tracer() , delay() , update() chaos graphs Verhulst dynamics,\\nshows that computer’s\\ncomputations can generate\\nresults sometimes against the\\ncommon sense expectations world coordinates clock analog clock showing time\\nof your computer turtles as clock’s\\nhands, ontimer() colormixer experiment with r, g, b ondrag() forest 3 breadth-first trees randomization fractalcurves Hilbert & Koch curves recursion lindenmayer ethnomathematics\\n(indian kolams) L-System minimal_hanoi Towers of Hanoi Rectangular Turtles\\nas Hanoi discs\\n( shape() , shapesize() ) nim play the classical nim game\\nwith three heaps of sticks\\nagainst the computer. turtles as nimsticks,\\nevent driven (mouse,\\nkeyboard) paint super minimalistic\\ndrawing program onclick() peace elementary turtle: appearance\\nand animation penrose aperiodic tiling with\\nkites and darts stamp() planet_and_moon simulation of\\ngravitational system compound shapes, Vec2D rosette a pattern from the wikipedia\\narticle on turtle graphics clone() , undo() round_dance dancing turtles rotating\\npairwise in opposite\\ndirection compound shapes, clone() shapesize() , tilt() , get_shapepoly() , update() sorting_animate visual demonstration of\\ndifferent sorting methods simple alignment,\\nrandomization tree a (graphical) breadth\\nfirst tree (using generators) clone() two_canvases simple design turtles on two\\ncanvases yinyang another elementary example circle()\\n\\nHave fun!\\n\\nChanges since Python 2.6¶\\n\\nThe methods Turtle.tracer, Turtle.window_width and Turtle.window_height have been eliminated. Methods with these names and functionality are now available only as methods of Screen. The functions derived from these remain available. (In fact already in Python 2.6 these methods were merely duplications of the corresponding TurtleScreen/Screen methods.)\\n\\nThe method Turtle.fill() has been eliminated. The behaviour of begin_fill() and end_fill() have changed slightly: now every filling process must be completed with an end_fill() call.\\n\\nA method Turtle.filling has been added. It returns a boolean value: True if a filling process is under way, False otherwise. This behaviour corresponds to a fill() call without arguments in Python 2.6.\\n\\nChanges since Python 3.0¶\\n\\nThe Turtle methods shearfactor(), shapetransform() and get_shapepoly() have been added. Thus the full range of regular linear transforms is now available for transforming turtle shapes. tiltangle() has been enhanced in functionality: it now can be used to get or set the tilt angle.\\n\\nThe Screen method onkeypress() has been added as a complement to onkey(). As the latter binds actions to the key release event, an alias: onkeyrelease() was also added for it.\\n\\nThe method Screen.mainloop has been added, so there is no longer a need to use the standalone mainloop() function when working with Screen and Turtle objects.\\n\\nTwo input methods have been added: Screen.textinput and Screen.numinput. These pop up input dialogs and return strings and numbers respectively.\\n\\nTable of Contents\\n\\nturtle — Turtle graphics\\n\\nIntroduction\\n\\nGet started\\n\\nTutorial\\n\\nStarting a turtle environment\\n\\nBasic drawing\\n\\nPen control\\n\\nThe turtle’s position\\n\\nMaking algorithmic patterns\\n\\nHow to…\\n\\nGet started as quickly as possible\\n\\nAutomatically begin and end filling\\n\\nUse the turtle module namespace\\n\\nUse turtle graphics in a script\\n\\nUse object-oriented turtle graphics\\n\\nTurtle graphics reference\\n\\nTurtle methods\\n\\nMethods of TurtleScreen/Screen\\n\\nMethods of RawTurtle/Turtle and corresponding functions\\n\\nTurtle motion\\n\\nTell Turtle’s state\\n\\nSettings for measurement\\n\\nPen control\\n\\nDrawing state\\n\\nColor control\\n\\nFilling\\n\\nMore drawing control\\n\\nTurtle state\\n\\nVisibility\\n\\nAppearance\\n\\nUsing events\\n\\nSpecial Turtle methods\\n\\nCompound shapes\\n\\nMethods of TurtleScreen/Screen and corresponding functions\\n\\nWindow control\\n\\nAnimation control\\n\\nUsing screen events\\n\\nInput methods\\n\\nSettings and special methods\\n\\nMethods specific to Screen, not inherited from TurtleScreen\\n\\nPublic classes\\n\\nExplanation\\n\\nHelp and configuration\\n\\nHow to use help\\n\\nTranslation of docstrings into different languages\\n\\nHow to configure Screen and Turtles\\n\\nturtledemo — Demo scripts\\n\\nChanges since Python 2.6\\n\\nChanges since Python 3.0\\n\\nPrevious topic\\n\\nIDLE — Python editor and shell\\n\\nNext topic\\n\\nDevelopment Tools\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nGraphical user interfaces with Tk »\\n\\nturtle — Turtle graphics\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\types.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Types »\\n\\ntypes — Dynamic type creation and names for built-in types\\n\\n|\\n\\ntypes — Dynamic type creation and names for built-in types¶\\n\\nSource code: Lib/types.py\\n\\nThis module defines utility functions to assist in dynamic creation of new types.\\n\\nIt also defines names for some object types that are used by the standard Python interpreter, but not exposed as builtins like int or str are.\\n\\nFinally, it provides some additional type-related utility classes and functions that are not fundamental enough to be builtins.\\n\\nDynamic Type Creation¶\\n\\nSee also\\n\\nSee also\\n\\nPEP 560 - Core support for typing module and generic types\\n\\nStandard Interpreter Types¶\\n\\nThis module provides names for many of the types that are required to implement a Python interpreter. It deliberately avoids including some of the types that arise only incidentally during processing such as the listiterator type.\\n\\nTypical use of these names is for isinstance() or issubclass() checks.\\n\\nIf you instantiate any of these types, note that signatures may vary between Python versions.\\n\\nStandard names are defined for the following types:\\n\\nAdditional Utility Classes and Functions¶\\n\\nCoroutine Utility Functions¶\\n\\nTable of Contents\\n\\ntypes — Dynamic type creation and names for built-in types\\n\\nDynamic Type Creation\\n\\nStandard Interpreter Types\\n\\nAdditional Utility Classes and Functions\\n\\nCoroutine Utility Functions\\n\\nPrevious topic\\n\\nweakref — Weak references\\n\\nNext topic\\n\\ncopy — Shallow and deep copy operations\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Types »\\n\\ntypes — Dynamic type creation and names for built-in types\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\typing.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nDevelopment Tools »\\n\\ntyping — Support for type hints\\n\\n|\\n\\ntyping — Support for type hints¶\\n\\nAdded in version 3.5.\\n\\nSource code: Lib/typing.py\\n\\nNote\\n\\nThe Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc.\\n\\nThis module provides runtime support for type hints.\\n\\nConsider the function below:\\n\\ndef surface_area_of_cube(edge_length: float) -> str:\\n return f\"The surface area of the cube is {6 * edge_length ** 2}.\"\\n\\nThe function surface_area_of_cube takes an argument expected to be an instance of float, as indicated by the type hint edge_length: float. The function is expected to return an instance of str, as indicated by the -> str hint.\\n\\nWhile type hints can be simple classes like float or str, they can also be more complex. The typing module provides a vocabulary of more advanced type hints.\\n\\nNew features are frequently added to the typing module. The typing_extensions package provides backports of these new features to older versions of Python.\\n\\nSee also\\n\\nSpecification for the Python Type System¶\\n\\nThe canonical, up-to-date specification of the Python type system can be found at Specification for the Python type system.\\n\\nType aliases¶\\n\\nA type alias is defined using the type statement, which creates an instance of TypeAliasType. In this example, Vector and list[float] will be treated equivalently by static type checkers:\\n\\ntype Vector = list[float]\\n\\ndef scale(scalar: float, vector: Vector) -> Vector:\\n return [scalar * num for num in vector]\\n\\n# passes type checking; a list of floats qualifies as a Vector.\\nnew_vector = scale(2.0, [1.0, -4.2, 5.4])\\n\\nType aliases are useful for simplifying complex type signatures. For example:\\n\\nfrom collections.abc import Sequence\\n\\ntype ConnectionOptions = dict[str, str]\\ntype Address = tuple[str, int]\\ntype Server = tuple[Address, ConnectionOptions]\\n\\ndef broadcast_message(message: str, servers: Sequence[Server]) -> None:\\n ...\\n\\n# The static type checker will treat the previous type signature as\\n# being exactly equivalent to this one.\\ndef broadcast_message(\\n message: str,\\n servers: Sequence[tuple[tuple[str, int], dict[str, str]]]\\n) -> None:\\n ...\\n\\nThe type statement is new in Python 3.12. For backwards compatibility, type aliases can also be created through simple assignment:\\n\\nVector = list[float]\\n\\nOr marked with TypeAlias to make it explicit that this is a type alias, not a normal variable assignment:\\n\\nfrom typing import TypeAlias\\n\\nVector: TypeAlias = list[float]\\n\\nNewType¶\\n\\nUse the NewType helper to create distinct types:\\n\\nfrom typing import NewType\\n\\nUserId = NewType(\\'UserId\\', int)\\nsome_id = UserId(524313)\\n\\nThe static type checker will treat the new type as if it were a subclass of the original type. This is useful in helping catch logical errors:\\n\\ndef get_user_name(user_id: UserId) -> str:\\n ...\\n\\n# passes type checking\\nuser_a = get_user_name(UserId(42351))\\n\\n# fails type checking; an int is not a UserId\\nuser_b = get_user_name(-1)\\n\\nYou may still perform all int operations on a variable of type UserId, but the result will always be of type int. This lets you pass in a UserId wherever an int might be expected, but will prevent you from accidentally creating a UserId in an invalid way:\\n\\n# \\'output\\' is of type \\'int\\', not \\'UserId\\'\\noutput = UserId(23413) + UserId(54341)\\n\\nNote that these checks are enforced only by the static type checker. At runtime, the statement Derived = NewType(\\'Derived\\', Base) will make Derived a callable that immediately returns whatever parameter you pass it. That means the expression Derived(some_value) does not create a new class or introduce much overhead beyond that of a regular function call.\\n\\nMore precisely, the expression some_value is Derived(some_value) is always true at runtime.\\n\\nIt is invalid to create a subtype of Derived:\\n\\nfrom typing import NewType\\n\\nUserId = NewType(\\'UserId\\', int)\\n\\n# Fails at runtime and does not pass type checking\\nclass AdminUserId(UserId): pass\\n\\nHowever, it is possible to create a NewType based on a ‘derived’ NewType:\\n\\nfrom typing import NewType\\n\\nUserId = NewType(\\'UserId\\', int)\\n\\nProUserId = NewType(\\'ProUserId\\', UserId)\\n\\nand typechecking for ProUserId will work as expected.\\n\\nSee PEP 484 for more details.\\n\\nNote\\n\\nRecall that the use of a type alias declares two types to be equivalent to one another. Doing type Alias = Original will make the static type checker treat Alias as being exactly equivalent to Original in all cases. This is useful when you want to simplify complex type signatures.\\n\\nIn contrast, NewType declares one type to be a subtype of another. Doing Derived = NewType(\\'Derived\\', Original) will make the static type checker treat Derived as a subclass of Original, which means a value of type Original cannot be used in places where a value of type Derived is expected. This is useful when you want to prevent logic errors with minimal runtime cost.\\n\\nAdded in version 3.5.2.\\n\\nChanged in version 3.10: NewType is now a class rather than a function. As a result, there is some additional runtime cost when calling NewType over a regular function.\\n\\nChanged in version 3.11: The performance of calling NewType has been restored to its level in Python 3.9.\\n\\nAnnotating callable objects¶\\n\\nFunctions – or other callable objects – can be annotated using collections.abc.Callable or deprecated typing.Callable. Callable[[int], str] signifies a function that takes a single parameter of type int and returns a str.\\n\\nFor example:\\n\\nfrom collections.abc import Callable, Awaitable\\n\\ndef feeder(get_next_item: Callable[[], str]) -> None:\\n ... # Body\\n\\ndef async_query(on_success: Callable[[int], None],\\n on_error: Callable[[int, Exception], None]) -> None:\\n ... # Body\\n\\nasync def on_update(value: str) -> None:\\n ... # Body\\n\\ncallback: Callable[[str], Awaitable[None]] = on_update\\n\\nThe 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 ParamSpec, Concatenate, or an ellipsis (...). The return type must be a single type.\\n\\nIf a literal ellipsis ... is given as the argument list, it indicates that a callable with any arbitrary parameter list would be acceptable:\\n\\ndef concat(x: str, y: str) -> str:\\n return x + y\\n\\nx: Callable[..., str]\\nx = str # OK\\nx = concat # Also OK\\n\\nCallable cannot express complex signatures such as functions that take a variadic number of arguments, overloaded functions, or functions that have keyword-only parameters. However, these signatures can be expressed by defining a Protocol class with a __call__() method:\\n\\nfrom collections.abc import Iterable\\nfrom typing import Protocol\\n\\nclass Combiner(Protocol):\\n def __call__(self, *vals: bytes, maxlen: int | None = None) -> list[bytes]: ...\\n\\ndef batch_proc(data: Iterable[bytes], cb_results: Combiner) -> bytes:\\n for item in data:\\n ...\\n\\ndef good_cb(*vals: bytes, maxlen: int | None = None) -> list[bytes]:\\n ...\\ndef bad_cb(*vals: bytes, maxitems: int | None) -> list[bytes]:\\n ...\\n\\nbatch_proc([], good_cb) # OK\\nbatch_proc([], bad_cb) # Error! Argument 2 has incompatible type because of\\n # different name and kind in the callback\\n\\nCallables which take other callables as arguments may indicate that their parameter types are dependent on each other using ParamSpec. Additionally, if that callable adds or removes arguments from other callables, the Concatenate operator may be used. They take the form Callable[ParamSpecVariable, ReturnType] and Callable[Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable], ReturnType] respectively.\\n\\nChanged in version 3.10: Callable now supports ParamSpec and Concatenate. See PEP 612 for more details.\\n\\nSee also\\n\\nThe documentation for ParamSpec and Concatenate provides examples of usage in Callable.\\n\\nGenerics¶\\n\\nSince type information about objects kept in containers cannot be statically inferred in a generic way, many container classes in the standard library support subscription to denote the expected types of container elements.\\n\\nfrom collections.abc import Mapping, Sequence\\n\\nclass Employee: ...\\n\\n# Sequence[Employee] indicates that all elements in the sequence\\n# must be instances of \"Employee\".\\n# Mapping[str, str] indicates that all keys and all values in the mapping\\n# must be strings.\\ndef notify_by_email(employees: Sequence[Employee],\\n overrides: Mapping[str, str]) -> None: ...\\n\\nGeneric functions and classes can be parameterized by using type parameter syntax:\\n\\nfrom collections.abc import Sequence\\n\\ndef first[T](l: Sequence[T]) -> T: # Function is generic over the TypeVar \"T\"\\n return l[0]\\n\\nOr by using the TypeVar factory directly:\\n\\nfrom collections.abc import Sequence\\nfrom typing import TypeVar\\n\\nU = TypeVar(\\'U\\') # Declare type variable \"U\"\\n\\ndef second(l: Sequence[U]) -> U: # Function is generic over the TypeVar \"U\"\\n return l[1]\\n\\nChanged in version 3.12: Syntactic support for generics is new in Python 3.12.\\n\\nAnnotating tuples¶\\n\\nFor most containers in Python, the typing system assumes that all elements in the container will be of the same type. For example:\\n\\nfrom collections.abc import Mapping\\n\\n# Type checker will infer that all elements in ``x`` are meant to be ints\\nx: list[int] = []\\n\\n# Type checker error: ``list`` only accepts a single type argument:\\ny: list[int, str] = [1, \\'foo\\']\\n\\n# Type checker will infer that all keys in ``z`` are meant to be strings,\\n# and that all values in ``z`` are meant to be either strings or ints\\nz: Mapping[str, str | int] = {}\\n\\nlist only accepts one type argument, so a type checker would emit an error on the y assignment above. Similarly, Mapping only accepts two type arguments: the first indicates the type of the keys, and the second indicates the type of the values.\\n\\nUnlike most other Python containers, however, it is common in idiomatic Python code for tuples to have elements which are not all of the same type. For this reason, tuples are special-cased in Python’s typing system. tuple accepts any number of type arguments:\\n\\n# OK: ``x`` is assigned to a tuple of length 1 where the sole element is an int\\nx: tuple[int] = (5,)\\n\\n# OK: ``y`` is assigned to a tuple of length 2;\\n# element 1 is an int, element 2 is a str\\ny: tuple[int, str] = (5, \"foo\")\\n\\n# Error: the type annotation indicates a tuple of length 1,\\n# but ``z`` has been assigned to a tuple of length 3\\nz: tuple[int] = (1, 2, 3)\\n\\nTo denote a tuple which could be of any length, and in which all elements are of the same type T, use the literal ellipsis ...: tuple[T, ...]. To denote an empty tuple, use tuple[()]. Using plain tuple as an annotation is equivalent to using tuple[Any, ...]:\\n\\nx: tuple[int, ...] = (1, 2)\\n# These reassignments are OK: ``tuple[int, ...]`` indicates x can be of any length\\nx = (1, 2, 3)\\nx = ()\\n# This reassignment is an error: all elements in ``x`` must be ints\\nx = (\"foo\", \"bar\")\\n\\n# ``y`` can only ever be assigned to an empty tuple\\ny: tuple[()] = ()\\n\\nz: tuple = (\"foo\", \"bar\")\\n# These reassignments are OK: plain ``tuple`` is equivalent to ``tuple[Any, ...]``\\nz = (1, 2, 3)\\nz = ()\\n\\nThe type of class objects¶\\n\\nA variable annotated with C may accept a value of type C. In contrast, a variable annotated with type[C] (or deprecated typing.Type[C]) may accept values that are classes themselves – specifically, it will accept the class object of C. For example:\\n\\na = 3 # Has type ``int``\\nb = int # Has type ``type[int]``\\nc = type(a) # Also has type ``type[int]``\\n\\nNote that type[C] is covariant:\\n\\nclass User: ...\\nclass ProUser(User): ...\\nclass TeamUser(User): ...\\n\\ndef make_new_user(user_class: type[User]) -> User:\\n # ...\\n return user_class()\\n\\nmake_new_user(User) # OK\\nmake_new_user(ProUser) # Also OK: ``type[ProUser]`` is a subtype of ``type[User]``\\nmake_new_user(TeamUser) # Still fine\\nmake_new_user(User()) # Error: expected ``type[User]`` but got ``User``\\nmake_new_user(int) # Error: ``type[int]`` is not a subtype of ``type[User]``\\n\\nThe only legal parameters for type are classes, Any, type variables, and unions of any of these types. For example:\\n\\ndef new_non_team_user(user_class: type[BasicUser | ProUser]): ...\\n\\nnew_non_team_user(BasicUser) # OK\\nnew_non_team_user(ProUser) # OK\\nnew_non_team_user(TeamUser) # Error: ``type[TeamUser]`` is not a subtype\\n # of ``type[BasicUser | ProUser]``\\nnew_non_team_user(User) # Also an error\\n\\ntype[Any] is equivalent to type, which is the root of Python’s metaclass hierarchy.\\n\\nAnnotating generators and coroutines¶\\n\\nA generator can be annotated using the generic type Generator[YieldType, SendType, ReturnType]. For example:\\n\\ndef echo_round() -> Generator[int, float, str]:\\n sent = yield 0\\n while sent >= 0:\\n sent = yield round(sent)\\n return \\'Done\\'\\n\\nNote that unlike many other generic classes in the standard library, the SendType of Generator behaves contravariantly, not covariantly or invariantly.\\n\\nThe SendType and ReturnType parameters default to None:\\n\\ndef infinite_stream(start: int) -> Generator[int]:\\n while True:\\n yield start\\n start += 1\\n\\nIt is also possible to set these types explicitly:\\n\\ndef infinite_stream(start: int) -> Generator[int, None, None]:\\n while True:\\n yield start\\n start += 1\\n\\nSimple generators that only ever yield values can also be annotated as having a return type of either Iterable[YieldType] or Iterator[YieldType]:\\n\\ndef infinite_stream(start: int) -> Iterator[int]:\\n while True:\\n yield start\\n start += 1\\n\\nAsync generators are handled in a similar fashion, but don’t expect a ReturnType type argument (AsyncGenerator[YieldType, SendType]). The SendType argument defaults to None, so the following definitions are equivalent:\\n\\nasync def infinite_stream(start: int) -> AsyncGenerator[int]:\\n while True:\\n yield start\\n start = await increment(start)\\n\\nasync def infinite_stream(start: int) -> AsyncGenerator[int, None]:\\n while True:\\n yield start\\n start = await increment(start)\\n\\nAs in the synchronous case, AsyncIterable[YieldType] and AsyncIterator[YieldType] are available as well:\\n\\nasync def infinite_stream(start: int) -> AsyncIterator[int]:\\n while True:\\n yield start\\n start = await increment(start)\\n\\nCoroutines can be annotated using Coroutine[YieldType, SendType, ReturnType]. Generic arguments correspond to those of Generator, for example:\\n\\nfrom collections.abc import Coroutine\\nc: Coroutine[list[str], str, int] # Some coroutine defined elsewhere\\nx = c.send(\\'hi\\') # Inferred type of \\'x\\' is list[str]\\nasync def bar() -> None:\\n y = await c # Inferred type of \\'y\\' is int\\n\\nUser-defined generic types¶\\n\\nA user-defined class can be defined as a generic class.\\n\\nfrom logging import Logger\\n\\nclass LoggedVar[T]:\\n def __init__(self, value: T, name: str, logger: Logger) -> None:\\n self.name = name\\n self.logger = logger\\n self.value = value\\n\\n def set(self, new: T) -> None:\\n self.log(\\'Set \\' + repr(self.value))\\n self.value = new\\n\\n def get(self) -> T:\\n self.log(\\'Get \\' + repr(self.value))\\n return self.value\\n\\n def log(self, message: str) -> None:\\n self.logger.info(\\'%s: %s\\', self.name, message)\\n\\nThis syntax indicates that the class LoggedVar is parameterised around a single type variable T . This also makes T valid as a type within the class body.\\n\\nGeneric classes implicitly inherit from Generic. For compatibility with Python 3.11 and lower, it is also possible to inherit explicitly from Generic to indicate a generic class:\\n\\nfrom typing import TypeVar, Generic\\n\\nT = TypeVar(\\'T\\')\\n\\nclass LoggedVar(Generic[T]):\\n ...\\n\\nGeneric classes have __class_getitem__() methods, meaning they can be parameterised at runtime (e.g. LoggedVar[int] below):\\n\\nfrom collections.abc import Iterable\\n\\ndef zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None:\\n for var in vars:\\n var.set(0)\\n\\nA generic type can have any number of type variables. All varieties of TypeVar are permissible as parameters for a generic type:\\n\\nfrom typing import TypeVar, Generic, Sequence\\n\\nclass WeirdTrio[T, B: Sequence[bytes], S: (int, str)]:\\n ...\\n\\nOldT = TypeVar(\\'OldT\\', contravariant=True)\\nOldB = TypeVar(\\'OldB\\', bound=Sequence[bytes], covariant=True)\\nOldS = TypeVar(\\'OldS\\', int, str)\\n\\nclass OldWeirdTrio(Generic[OldT, OldB, OldS]):\\n ...\\n\\nEach type variable argument to Generic must be distinct. This is thus invalid:\\n\\nfrom typing import TypeVar, Generic\\n...\\n\\nclass Pair[M, M]: # SyntaxError\\n ...\\n\\nT = TypeVar(\\'T\\')\\n\\nclass Pair(Generic[T, T]): # INVALID\\n ...\\n\\nGeneric classes can also inherit from other classes:\\n\\nfrom collections.abc import Sized\\n\\nclass LinkedList[T](Sized):\\n ...\\n\\nWhen inheriting from generic classes, some type parameters could be fixed:\\n\\nfrom collections.abc import Mapping\\n\\nclass MyDict[T](Mapping[str, T]):\\n ...\\n\\nIn this case MyDict has a single parameter, T.\\n\\nUsing a generic class without specifying type parameters assumes Any for each position. In the following example, MyIterable is not generic but implicitly inherits from Iterable[Any]:\\n\\nfrom collections.abc import Iterable\\n\\nclass MyIterable(Iterable): # Same as Iterable[Any]\\n ...\\n\\nUser-defined generic type aliases are also supported. Examples:\\n\\nfrom collections.abc import Iterable\\n\\ntype Response[S] = Iterable[S] | int\\n\\n# Return type here is same as Iterable[str] | int\\ndef response(query: str) -> Response[str]:\\n ...\\n\\ntype Vec[T] = Iterable[tuple[T, T]]\\n\\ndef inproduct[T: (int, float, complex)](v: Vec[T]) -> T: # Same as Iterable[tuple[T, T]]\\n return sum(x*y for x, y in v)\\n\\nFor backward compatibility, generic type aliases can also be created through a simple assignment:\\n\\nfrom collections.abc import Iterable\\nfrom typing import TypeVar\\n\\nS = TypeVar(\"S\")\\nResponse = Iterable[S] | int\\n\\nChanged in version 3.7: Generic no longer has a custom metaclass.\\n\\nChanged in version 3.12: Syntactic support for generics and type aliases is new in version 3.12. Previously, generic classes had to explicitly inherit from Generic or contain a type variable in one of their bases.\\n\\nUser-defined generics for parameter expressions are also supported via parameter specification variables in the form [**P]. The behavior is consistent with type variables’ described above as parameter specification variables are treated by the typing module as a specialized type variable. The one exception to this is that a list of types can be used to substitute a ParamSpec:\\n\\n>>> class Z[T, **P]: ... # T is a TypeVar; P is a ParamSpec\\n...\\n>>> Z[int, [dict, float]]\\n__main__.Z[int, [dict, float]]\\n\\nClasses generic over a ParamSpec can also be created using explicit inheritance from Generic. In this case, ** is not used:\\n\\nfrom typing import ParamSpec, Generic\\n\\nP = ParamSpec(\\'P\\')\\n\\nclass Z(Generic[P]):\\n ...\\n\\nAnother difference between TypeVar and ParamSpec is that a generic with only one parameter specification variable will accept parameter lists in the forms X[[Type1, Type2, ...]] and also X[Type1, Type2, ...] for aesthetic reasons. Internally, the latter is converted to the former, so the following are equivalent:\\n\\n>>> class X[**P]: ...\\n...\\n>>> X[int, str]\\n__main__.X[[int, str]]\\n>>> X[[int, str]]\\n__main__.X[[int, str]]\\n\\nNote that generics with ParamSpec may not have correct __parameters__ after substitution in some cases because they are intended primarily for static type checking.\\n\\nChanged in version 3.10: Generic can now be parameterized over parameter expressions. See ParamSpec and PEP 612 for more details.\\n\\nA 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 typing module are hashable and comparable for equality.\\n\\nThe Any type¶\\n\\nA special kind of type is Any. A static type checker will treat every type as being compatible with Any and Any as being compatible with every type.\\n\\nThis means that it is possible to perform any operation or method call on a value of type Any and assign it to any variable:\\n\\nfrom typing import Any\\n\\na: Any = None\\na = [] # OK\\na = 2 # OK\\n\\ns: str = \\'\\'\\ns = a # OK\\n\\ndef foo(item: Any) -> int:\\n # Passes type checking; \\'item\\' could be any type,\\n # and that type might have a \\'bar\\' method\\n item.bar()\\n ...\\n\\nNotice that no type checking is performed when assigning a value of type Any to a more precise type. For example, the static type checker did not report an error when assigning a to s even though s was declared to be of type str and receives an int value at runtime!\\n\\nFurthermore, all functions without a return type or parameter types will implicitly default to using Any:\\n\\ndef legacy_parser(text):\\n ...\\n return data\\n\\n# A static type checker will treat the above\\n# as having the same signature as:\\ndef legacy_parser(text: Any) -> Any:\\n ...\\n return data\\n\\nThis behavior allows Any to be used as an escape hatch when you need to mix dynamically and statically typed code.\\n\\nContrast the behavior of Any with the behavior of object. Similar to Any, every type is a subtype of object. However, unlike Any, the reverse is not true: object is not a subtype of every other type.\\n\\nThat means when the type of a value is object, a type checker will reject almost all operations on it, and assigning it to a variable (or using it as a return value) of a more specialized type is a type error. For example:\\n\\ndef hash_a(item: object) -> int:\\n # Fails type checking; an object does not have a \\'magic\\' method.\\n item.magic()\\n ...\\n\\ndef hash_b(item: Any) -> int:\\n # Passes type checking\\n item.magic()\\n ...\\n\\n# Passes type checking, since ints and strs are subclasses of object\\nhash_a(42)\\nhash_a(\"foo\")\\n\\n# Passes type checking, since Any is compatible with all types\\nhash_b(42)\\nhash_b(\"foo\")\\n\\nUse object to indicate that a value could be any type in a typesafe manner. Use Any to indicate that a value is dynamically typed.\\n\\nNominal vs structural subtyping¶\\n\\nInitially PEP 484 defined the Python static type system as using nominal subtyping. This means that a class A is allowed where a class B is expected if and only if A is a subclass of B.\\n\\nThis requirement previously also applied to abstract base classes, such as Iterable. The problem with this approach is that a class had to be explicitly marked to support them, which is unpythonic and unlike what one would normally do in idiomatic dynamically typed Python code. For example, this conforms to PEP 484:\\n\\nfrom collections.abc import Sized, Iterable, Iterator\\n\\nclass Bucket(Sized, Iterable[int]):\\n ...\\n def __len__(self) -> int: ...\\n def __iter__(self) -> Iterator[int]: ...\\n\\nPEP 544 solves this problem by allowing users to write the above code without explicit base classes in the class definition, allowing Bucket to be implicitly considered a subtype of both Sized and Iterable[int] by static type checkers. This is known as structural subtyping (or static duck-typing):\\n\\nfrom collections.abc import Iterator, Iterable\\n\\nclass Bucket: # Note: no base classes\\n ...\\n def __len__(self) -> int: ...\\n def __iter__(self) -> Iterator[int]: ...\\n\\ndef collect(items: Iterable[int]) -> int: ...\\nresult = collect(Bucket()) # Passes type check\\n\\nMoreover, by subclassing a special class Protocol, a user can define new custom protocols to fully enjoy structural subtyping (see examples below).\\n\\nModule contents¶\\n\\nThe typing module defines the following classes, functions and decorators.\\n\\nSpecial typing primitives¶\\n\\nSpecial types¶\\n\\nThese can be used as types in annotations. They do not support subscription using [].\\n\\nSpecial forms¶\\n\\nThese can be used as types in annotations. They all support subscription using [], but each has a unique syntax.\\n\\nBuilding generic types and type aliases¶\\n\\nThe following classes should not be used directly as annotations. Their intended purpose is to be building blocks for creating generic types and type aliases.\\n\\nThese objects can be created through special syntax (type parameter lists and the type statement). For compatibility with Python 3.11 and earlier, they can also be created without the dedicated syntax, as documented below.\\n\\nOther special directives¶\\n\\nThese functions and classes should not be used directly as annotations. Their intended purpose is to be building blocks for creating and declaring types.\\n\\nProtocols¶\\n\\nThe following protocols are provided by the typing module. All are decorated with @runtime_checkable.\\n\\nABCs and Protocols for working with I/O¶\\n\\nThe protocols io.Reader and io.Writer offer a simpler alternative for argument types, when only the read() or write() methods are accessed, respectively:\\n\\ndef read_and_write(reader: Reader[str], writer: Writer[bytes]):\\n data = reader.read()\\n writer.write(data.encode())\\n\\nAlso consider using collections.abc.Iterable for iterating over the lines of an input stream:\\n\\ndef read_config(stream: Iterable[str]):\\n for line in stream:\\n ...\\n\\nFunctions and decorators¶\\n\\nIntrospection helpers¶\\n\\nConstant¶\\n\\nDeprecated aliases¶\\n\\nThis module defines several deprecated aliases to pre-existing standard library classes. These were originally included in the typing module in order to support parameterizing these generic classes using []. However, the aliases became redundant in Python 3.9 when the corresponding pre-existing classes were enhanced to support [] (see PEP 585).\\n\\nThe 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.\\n\\nIf 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 typing module without deprecation warnings until at least Python 3.14.\\n\\nType 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.\\n\\nAliases to built-in types¶\\n\\nAliases to types in collections¶\\n\\nAliases to other concrete types¶\\n\\nAliases to container ABCs in collections.abc¶\\n\\nAliases to asynchronous ABCs in collections.abc¶\\n\\nAliases to other ABCs in collections.abc¶\\n\\nAliases to contextlib ABCs¶\\n\\nDeprecation Timeline of Major Features¶\\n\\nCertain features in typing are deprecated and may be removed in a future version of Python. The following table summarizes major deprecations for your convenience. This is subject to change, and not all deprecations are listed.\\n\\nFeature Deprecated in Projected removal PEP/issue typing versions of standard collections 3.9 Undecided (see Deprecated aliases for more information) PEP 585 typing.ByteString 3.9 3.17 gh-91896 typing.Text 3.11 Undecided gh-92332 typing.Hashable and typing.Sized 3.12 Undecided gh-94309 typing.TypeAlias 3.12 Undecided PEP 695 typing.AnyStr 3.13 3.18 gh-105578\\n\\nTable of Contents\\n\\ntyping — Support for type hints\\n\\nSpecification for the Python Type System\\n\\nType aliases\\n\\nNewType\\n\\nAnnotating callable objects\\n\\nGenerics\\n\\nAnnotating tuples\\n\\nThe type of class objects\\n\\nAnnotating generators and coroutines\\n\\nUser-defined generic types\\n\\nThe Any type\\n\\nNominal vs structural subtyping\\n\\nModule contents\\n\\nSpecial typing primitives\\n\\nSpecial types\\n\\nSpecial forms\\n\\nBuilding generic types and type aliases\\n\\nOther special directives\\n\\nProtocols\\n\\nABCs and Protocols for working with I/O\\n\\nFunctions and decorators\\n\\nIntrospection helpers\\n\\nConstant\\n\\nDeprecated aliases\\n\\nAliases to built-in types\\n\\nAliases to types in collections\\n\\nAliases to other concrete types\\n\\nAliases to container ABCs in collections.abc\\n\\nAliases to asynchronous ABCs in collections.abc\\n\\nAliases to other ABCs in collections.abc\\n\\nAliases to contextlib ABCs\\n\\nDeprecation Timeline of Major Features\\n\\nPrevious topic\\n\\nDevelopment Tools\\n\\nNext topic\\n\\npydoc — Documentation generator and online help system\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nDevelopment Tools »\\n\\ntyping — Support for type hints\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\unicodedata.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nText Processing Services »\\n\\nunicodedata — Unicode Database\\n\\n|\\n\\nunicodedata — Unicode Database¶\\n\\nThis 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 17.0.0.\\n\\nThe module uses the same names and symbols as defined by Unicode Standard Annex #44, “Unicode Character Database”. It defines the following functions:\\n\\nSee also\\n\\nThe Unicode HOWTO for more information about Unicode and how to use this module.\\n\\nIn addition, the module exposes the following constant:\\n\\nFootnotes\\n\\n[1]\\n\\nhttps://www.unicode.org/Public/17.0.0/ucd/NameAliases.txt\\n\\n[2]\\n\\nhttps://www.unicode.org/Public/17.0.0/ucd/NamedSequences.txt\\n\\nPrevious topic\\n\\ntextwrap — Text wrapping and filling\\n\\nNext topic\\n\\nstringprep — Internet String Preparation\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nText Processing Services »\\n\\nunicodedata — Unicode Database\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\unittest.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nDevelopment Tools »\\n\\nunittest — Unit testing framework\\n\\n|\\n\\nunittest — Unit testing framework¶\\n\\nSource code: Lib/unittest/__init__.py\\n\\n(If you are already familiar with the basic concepts of testing, you might want to skip to the list of assert methods.)\\n\\nThe 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.\\n\\nTo achieve this, unittest supports some important concepts in an object-oriented way:\\n\\nSee also\\n\\nThe script Tools/unittestgui/unittestgui.py in the Python source distribution is a GUI tool for test discovery and execution. This is intended largely for ease of use for those new to unit testing. For production environments it is recommended that tests be driven by a continuous integration system such as Buildbot, Jenkins, GitHub Actions, or AppVeyor.\\n\\nBasic example¶\\n\\nThe 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.\\n\\nHere is a short script to test three string methods:\\n\\nimport unittest\\n\\nclass TestStringMethods(unittest.TestCase):\\n\\n def test_upper(self):\\n self.assertEqual(\\'foo\\'.upper(), \\'FOO\\')\\n\\n def test_isupper(self):\\n self.assertTrue(\\'FOO\\'.isupper())\\n self.assertFalse(\\'Foo\\'.isupper())\\n\\n def test_split(self):\\n s = \\'hello world\\'\\n self.assertEqual(s.split(), [\\'hello\\', \\'world\\'])\\n # check that s.split fails when the separator is not a string\\n with self.assertRaises(TypeError):\\n s.split(2)\\n\\nif __name__ == \\'__main__\\':\\n unittest.main()\\n\\nA test case is created by subclassing unittest.TestCase. The three individual tests are defined with methods whose names start with the letters test. This naming convention informs the test runner about which methods represent tests.\\n\\nThe crux of each test is a call to assertEqual() to check for an expected result; assertTrue() or assertFalse() to verify a condition; or assertRaises() to verify that a specific exception gets raised. These methods are used instead of the assert statement so the test runner can accumulate all test results and produce a report.\\n\\nThe setUp() and tearDown() methods allow you to define instructions that will be executed before and after each test method. They are covered in more detail in the section Organizing test code.\\n\\nThe final block shows a simple way to run the tests. unittest.main() provides a command-line interface to the test script. When run from the command line, the above script produces an output that looks like this:\\n\\n...\\n----------------------------------------------------------------------\\nRan 3 tests in 0.000s\\n\\nOK\\n\\nPassing the -v option to your test script will instruct unittest.main() to enable a higher level of verbosity, and produce the following output:\\n\\ntest_isupper (__main__.TestStringMethods.test_isupper) ... ok\\ntest_split (__main__.TestStringMethods.test_split) ... ok\\ntest_upper (__main__.TestStringMethods.test_upper) ... ok\\n\\n----------------------------------------------------------------------\\nRan 3 tests in 0.001s\\n\\nOK\\n\\nThe above examples show the most commonly used unittest features which are sufficient to meet many everyday testing needs. The remainder of the documentation explores the full feature set from first principles.\\n\\nChanged in version 3.11: The behavior of returning a value from a test method (other than the default None value), is now deprecated.\\n\\nCommand-Line Interface¶\\n\\nThe unittest module can be used from the command line to run tests from modules, classes or even individual test methods:\\n\\npython -m unittest test_module1 test_module2\\npython -m unittest test_module.TestClass\\npython -m unittest test_module.TestClass.test_method\\n\\nYou can pass in a list with any combination of module names, and fully qualified class or method names.\\n\\nTest modules can be specified by file path as well:\\n\\npython -m unittest tests/test_something.py\\n\\nThis allows you to use the shell filename completion to specify the test module. The file specified must still be importable as a module. The path is converted to a module name by removing the ‘.py’ and converting path separators into ‘.’. If you want to execute a test file that isn’t importable as a module you should execute the file directly instead.\\n\\nYou can run tests with more detail (higher verbosity) by passing in the -v flag:\\n\\npython -m unittest -v test_module\\n\\nWhen executed without arguments Test Discovery is started:\\n\\npython -m unittest\\n\\nFor a list of all the command-line options:\\n\\npython -m unittest -h\\n\\nChanged in version 3.2: In earlier versions it was only possible to run individual test methods and not modules or classes.\\n\\nAdded in version 3.14: Output is colorized by default and can be controlled using environment variables.\\n\\nCommand-line options¶\\n\\nunittest supports these command-line options:\\n\\nAdded in version 3.2: The command-line options -b, -c and -f were added.\\n\\nAdded in version 3.5: The command-line option --locals.\\n\\nAdded in version 3.7: The command-line option -k.\\n\\nAdded in version 3.12: The command-line option --durations.\\n\\nThe command line can also be used for test discovery, for running all of the tests in a project or just a subset.\\n\\nTest Discovery¶\\n\\nAdded in version 3.2.\\n\\nUnittest supports simple test discovery. In order to be compatible with test discovery, all of the test files must be modules or packages importable from the top-level directory of the project (this means that their filenames must be valid identifiers).\\n\\nTest discovery is implemented in TestLoader.discover(), but can also be used from the command line. The basic command-line usage is:\\n\\ncd project_directory\\npython -m unittest discover\\n\\nNote\\n\\nAs a shortcut, python -m unittest is the equivalent of python -m unittest discover. If you want to pass arguments to test discovery the discover sub-command must be used explicitly.\\n\\nThe discover sub-command has the following options:\\n\\nThe -s, -p, and -t options can be passed in as positional arguments in that order. The following two command lines are equivalent:\\n\\npython -m unittest discover -s project_directory -p \"*_test.py\"\\npython -m unittest discover project_directory \"*_test.py\"\\n\\nAs well as being a path it is possible to pass a package name, for example myproject.subpackage.test, as the start directory. The package name you supply will then be imported and its location on the filesystem will be used as the start directory.\\n\\nCaution\\n\\nTest discovery loads tests by importing them. Once test discovery has found all the test files from the start directory you specify it turns the paths into package names to import. For example foo/bar/baz.py will be imported as foo.bar.baz.\\n\\nIf you have a package installed globally and attempt test discovery on a different copy of the package then the import could happen from the wrong place. If this happens test discovery will warn you and exit.\\n\\nIf you supply the start directory as a package name rather than a path to a directory then discover assumes that whichever location it imports from is the location you intended, so you will not get the warning.\\n\\nTest modules and packages can customize test loading and discovery by through the load_tests protocol.\\n\\nChanged in version 3.4: Test discovery supports namespace packages.\\n\\nChanged in version 3.11: Test discovery dropped the namespace packages support. It has been broken since Python 3.7. Start directory and its subdirectories containing tests must be regular package that have __init__.py file.\\n\\nIf the start directory is the dotted name of the package, the ancestor packages can be namespace packages.\\n\\nChanged in version 3.14: Test discovery supports namespace package as start directory again. To avoid scanning directories unrelated to Python, tests are not searched in subdirectories that do not contain __init__.py.\\n\\nOrganizing test code¶\\n\\nThe basic building blocks of unit testing are test cases — single scenarios that must be set up and checked for correctness. In unittest, test cases are represented by unittest.TestCase instances. To make your own test cases you must write subclasses of TestCase or use FunctionTestCase.\\n\\nThe testing code of a TestCase instance should be entirely self contained, such that it can be run either in isolation or in arbitrary combination with any number of other test cases.\\n\\nThe simplest TestCase subclass will simply implement a test method (i.e. a method whose name starts with test) in order to perform specific testing code:\\n\\nimport unittest\\n\\nclass DefaultWidgetSizeTestCase(unittest.TestCase):\\n def test_default_widget_size(self):\\n widget = Widget(\\'The widget\\')\\n self.assertEqual(widget.size(), (50, 50))\\n\\nNote that in order to test something, we use one of the assert* methods provided by the TestCase base class. If the test fails, an exception will be raised with an explanatory message, and unittest will identify the test case as a failure. Any other exceptions will be treated as errors.\\n\\nTests can be numerous, and their set-up can be repetitive. Luckily, we can factor out set-up code by implementing a method called setUp(), which the testing framework will automatically call for every single test we run:\\n\\nimport unittest\\n\\nclass WidgetTestCase(unittest.TestCase):\\n def setUp(self):\\n self.widget = Widget(\\'The widget\\')\\n\\n def test_default_widget_size(self):\\n self.assertEqual(self.widget.size(), (50,50),\\n \\'incorrect default size\\')\\n\\n def test_widget_resize(self):\\n self.widget.resize(100,150)\\n self.assertEqual(self.widget.size(), (100,150),\\n \\'wrong size after resize\\')\\n\\nNote\\n\\nThe order in which the various tests will be run is determined by sorting the test method names with respect to the built-in ordering for strings.\\n\\nIf the setUp() method raises an exception while the test is running, the framework will consider the test to have suffered an error, and the test method will not be executed.\\n\\nSimilarly, we can provide a tearDown() method that tidies up after the test method has been run:\\n\\nimport unittest\\n\\nclass WidgetTestCase(unittest.TestCase):\\n def setUp(self):\\n self.widget = Widget(\\'The widget\\')\\n\\n def tearDown(self):\\n self.widget.dispose()\\n\\nIf setUp() succeeded, tearDown() will be run whether the test method succeeded or not.\\n\\nSuch a working environment for the testing code is called a test fixture. A new TestCase instance is created as a unique test fixture used to execute each individual test method. Thus setUp(), tearDown(), and TestCase.__init__() will be called once per test.\\n\\nIt is recommended that you use TestCase implementations to group tests together according to the features they test. unittest provides a mechanism for this: the test suite, represented by unittest’s TestSuite class. In most cases, calling unittest.main() will do the right thing and collect all the module’s test cases for you and execute them.\\n\\nHowever, should you want to customize the building of your test suite, you can do it yourself:\\n\\ndef suite():\\n suite = unittest.TestSuite()\\n suite.addTest(WidgetTestCase(\\'test_default_widget_size\\'))\\n suite.addTest(WidgetTestCase(\\'test_widget_resize\\'))\\n return suite\\n\\nif __name__ == \\'__main__\\':\\n runner = unittest.TextTestRunner()\\n runner.run(suite())\\n\\nYou can place the definitions of test cases and test suites in the same modules as the code they are to test (such as widget.py), but there are several advantages to placing the test code in a separate module, such as test_widget.py:\\n\\nThe test module can be run standalone from the command line.\\n\\nThe test code can more easily be separated from shipped code.\\n\\nThere is less temptation to change test code to fit the code it tests without a good reason.\\n\\nTest code should be modified much less frequently than the code it tests.\\n\\nTested code can be refactored more easily.\\n\\nTests for modules written in C must be in separate modules anyway, so why not be consistent?\\n\\nIf the testing strategy changes, there is no need to change the source code.\\n\\nRe-using old test code¶\\n\\nSome users will find that they have existing test code that they would like to run from unittest, without converting every old test function to a TestCase subclass.\\n\\nFor this reason, unittest provides a FunctionTestCase class. This subclass of TestCase can be used to wrap an existing test function. Set-up and tear-down functions can also be provided.\\n\\nGiven the following test function:\\n\\ndef testSomething():\\n something = makeSomething()\\n assert something.name is not None\\n # ...\\n\\none can create an equivalent test case instance as follows, with optional set-up and tear-down methods:\\n\\ntestcase = unittest.FunctionTestCase(testSomething,\\n setUp=makeSomethingDB,\\n tearDown=deleteSomethingDB)\\n\\nNote\\n\\nEven though FunctionTestCase can be used to quickly convert an existing test base over to a unittest-based system, this approach is not recommended. Taking the time to set up proper TestCase subclasses will make future test refactorings infinitely easier.\\n\\nIn some cases, the existing tests may have been written using the doctest module. If so, doctest provides a DocTestSuite class that can automatically build unittest.TestSuite instances from the existing doctest-based tests.\\n\\nSkipping tests and expected failures¶\\n\\nAdded in version 3.1.\\n\\nUnittest supports skipping individual test methods and even whole classes of tests. In addition, it supports marking a test as an “expected failure,” a test that is broken and will fail, but shouldn’t be counted as a failure on a TestResult.\\n\\nSkipping a test is simply a matter of using the skip() decorator or one of its conditional variants, calling TestCase.skipTest() within a setUp() or test method, or raising SkipTest directly.\\n\\nBasic skipping looks like this:\\n\\nclass MyTestCase(unittest.TestCase):\\n\\n @unittest.skip(\"demonstrating skipping\")\\n def test_nothing(self):\\n self.fail(\"shouldn\\'t happen\")\\n\\n @unittest.skipIf(mylib.__version__ < (1, 3),\\n \"not supported in this library version\")\\n def test_format(self):\\n # Tests that work for only a certain version of the library.\\n pass\\n\\n @unittest.skipUnless(sys.platform.startswith(\"win\"), \"requires Windows\")\\n def test_windows_support(self):\\n # windows specific testing code\\n pass\\n\\n def test_maybe_skipped(self):\\n if not external_resource_available():\\n self.skipTest(\"external resource not available\")\\n # test code that depends on the external resource\\n pass\\n\\nThis is the output of running the example above in verbose mode:\\n\\ntest_format (__main__.MyTestCase.test_format) ... skipped \\'not supported in this library version\\'\\ntest_nothing (__main__.MyTestCase.test_nothing) ... skipped \\'demonstrating skipping\\'\\ntest_maybe_skipped (__main__.MyTestCase.test_maybe_skipped) ... skipped \\'external resource not available\\'\\ntest_windows_support (__main__.MyTestCase.test_windows_support) ... skipped \\'requires Windows\\'\\n\\n----------------------------------------------------------------------\\nRan 4 tests in 0.005s\\n\\nOK (skipped=4)\\n\\nClasses can be skipped just like methods:\\n\\n@unittest.skip(\"showing class skipping\")\\nclass MySkippedTestCase(unittest.TestCase):\\n def test_not_run(self):\\n pass\\n\\nTestCase.setUp() can also skip the test. This is useful when a resource that needs to be set up is not available.\\n\\nExpected failures use the expectedFailure() decorator.\\n\\nclass ExpectedFailureTestCase(unittest.TestCase):\\n @unittest.expectedFailure\\n def test_fail(self):\\n self.assertEqual(1, 0, \"broken\")\\n\\nIt’s easy to roll your own skipping decorators by making a decorator that calls skip() on the test when it wants it to be skipped. This decorator skips the test unless the passed object has a certain attribute:\\n\\ndef skipUnlessHasattr(obj, attr):\\n if hasattr(obj, attr):\\n return lambda func: func\\n return unittest.skip(\"{!r} doesn\\'t have {!r}\".format(obj, attr))\\n\\nThe following decorators and exception implement test skipping and expected failures:\\n\\nSkipped tests will not have setUp() or tearDown() run around them. Skipped classes will not have setUpClass() or tearDownClass() run. Skipped modules will not have setUpModule() or tearDownModule() run.\\n\\nDistinguishing test iterations using subtests¶\\n\\nAdded in version 3.4.\\n\\nWhen there are very small differences among your tests, for instance some parameters, unittest allows you to distinguish them inside the body of a test method using the subTest() context manager.\\n\\nFor example, the following test:\\n\\nclass NumbersTest(unittest.TestCase):\\n\\n def test_even(self):\\n \"\"\"\\n Test that numbers between 0 and 5 are all even.\\n \"\"\"\\n for i in range(0, 6):\\n with self.subTest(i=i):\\n self.assertEqual(i % 2, 0)\\n\\nwill produce the following output:\\n\\n======================================================================\\nFAIL: test_even (__main__.NumbersTest.test_even) (i=1)\\nTest that numbers between 0 and 5 are all even.\\n----------------------------------------------------------------------\\nTraceback (most recent call last):\\n File \"subtests.py\", line 11, in test_even\\n self.assertEqual(i % 2, 0)\\n ^^^^^^^^^^^^^^^^^^^^^^^^^^\\nAssertionError: 1 != 0\\n\\n======================================================================\\nFAIL: test_even (__main__.NumbersTest.test_even) (i=3)\\nTest that numbers between 0 and 5 are all even.\\n----------------------------------------------------------------------\\nTraceback (most recent call last):\\n File \"subtests.py\", line 11, in test_even\\n self.assertEqual(i % 2, 0)\\n ^^^^^^^^^^^^^^^^^^^^^^^^^^\\nAssertionError: 1 != 0\\n\\n======================================================================\\nFAIL: test_even (__main__.NumbersTest.test_even) (i=5)\\nTest that numbers between 0 and 5 are all even.\\n----------------------------------------------------------------------\\nTraceback (most recent call last):\\n File \"subtests.py\", line 11, in test_even\\n self.assertEqual(i % 2, 0)\\n ^^^^^^^^^^^^^^^^^^^^^^^^^^\\nAssertionError: 1 != 0\\n\\nWithout using a subtest, execution would stop after the first failure, and the error would be less easy to diagnose because the value of i wouldn’t be displayed:\\n\\n======================================================================\\nFAIL: test_even (__main__.NumbersTest.test_even)\\n----------------------------------------------------------------------\\nTraceback (most recent call last):\\n File \"subtests.py\", line 32, in test_even\\n self.assertEqual(i % 2, 0)\\nAssertionError: 1 != 0\\n\\nClasses and functions¶\\n\\nThis section describes in depth the API of unittest.\\n\\nTest cases¶\\n\\nGrouping tests¶\\n\\nLoading and running tests¶\\n\\nload_tests Protocol¶\\n\\nAdded in version 3.2.\\n\\nModules or packages can customize how tests are loaded from them during normal test runs or test discovery by implementing a function called load_tests.\\n\\nIf a test module defines load_tests it will be called by TestLoader.loadTestsFromModule() with the following arguments:\\n\\nload_tests(loader, standard_tests, pattern)\\n\\nwhere pattern is passed straight through from loadTestsFromModule. It defaults to None.\\n\\nIt should return a TestSuite.\\n\\nloader is the instance of TestLoader doing the loading. standard_tests are the tests that would be loaded by default from the module. It is common for test modules to only want to add or remove tests from the standard set of tests. The third argument is used when loading packages as part of test discovery.\\n\\nA typical load_tests function that loads tests from a specific set of TestCase classes may look like:\\n\\ntest_cases = (TestCase1, TestCase2, TestCase3)\\n\\ndef load_tests(loader, tests, pattern):\\n suite = TestSuite()\\n for test_class in test_cases:\\n tests = loader.loadTestsFromTestCase(test_class)\\n suite.addTests(tests)\\n return suite\\n\\nIf discovery is started in a directory containing a package, either from the command line or by calling TestLoader.discover(), then the package __init__.py will be checked for load_tests. If that function does not exist, discovery will recurse into the package as though it were just another directory. Otherwise, discovery of the package’s tests will be left up to load_tests which is called with the following arguments:\\n\\nload_tests(loader, standard_tests, pattern)\\n\\nThis should return a TestSuite representing all the tests from the package. (standard_tests will only contain tests collected from __init__.py.)\\n\\nBecause the pattern is passed into load_tests the package is free to continue (and potentially modify) test discovery. A ‘do nothing’ load_tests function for a test package would look like:\\n\\ndef load_tests(loader, standard_tests, pattern):\\n # top level directory cached on loader instance\\n this_dir = os.path.dirname(__file__)\\n package_tests = loader.discover(start_dir=this_dir, pattern=pattern)\\n standard_tests.addTests(package_tests)\\n return standard_tests\\n\\nChanged in version 3.5: Discovery no longer checks package names for matching pattern due to the impossibility of package names matching the default pattern.\\n\\nClass and Module Fixtures¶\\n\\nClass and module level fixtures are implemented in TestSuite. When the test suite encounters a test from a new class then tearDownClass() from the previous class (if there is one) is called, followed by setUpClass() from the new class.\\n\\nSimilarly if a test is from a different module from the previous test then tearDownModule from the previous module is run, followed by setUpModule from the new module.\\n\\nAfter all the tests have run the final tearDownClass and tearDownModule are run.\\n\\nNote that shared fixtures do not play well with [potential] features like test parallelization and they break test isolation. They should be used with care.\\n\\nThe default ordering of tests created by the unittest test loaders is to group all tests from the same modules and classes together. This will lead to setUpClass / setUpModule (etc) being called exactly once per class and module. If you randomize the order, so that tests from different modules and classes are adjacent to each other, then these shared fixture functions may be called multiple times in a single test run.\\n\\nShared fixtures are not intended to work with suites with non-standard ordering. A BaseTestSuite still exists for frameworks that don’t want to support shared fixtures.\\n\\nIf there are any exceptions raised during one of the shared fixture functions the test is reported as an error. Because there is no corresponding test instance an _ErrorHolder object (that has the same interface as a TestCase) is created to represent the error. If you are just using the standard unittest test runner then this detail doesn’t matter, but if you are a framework author it may be relevant.\\n\\nsetUpClass and tearDownClass¶\\n\\nThese must be implemented as class methods:\\n\\nimport unittest\\n\\nclass Test(unittest.TestCase):\\n @classmethod\\n def setUpClass(cls):\\n cls._connection = createExpensiveConnectionObject()\\n\\n @classmethod\\n def tearDownClass(cls):\\n cls._connection.destroy()\\n\\nIf you want the setUpClass and tearDownClass on base classes called then you must call up to them yourself. The implementations in TestCase are empty.\\n\\nIf an exception is raised during a setUpClass then the tests in the class are not run and the tearDownClass is not run. Skipped classes will not have setUpClass or tearDownClass run. If the exception is a SkipTest exception then the class will be reported as having been skipped instead of as an error.\\n\\nsetUpModule and tearDownModule¶\\n\\nThese should be implemented as functions:\\n\\ndef setUpModule():\\n createConnection()\\n\\ndef tearDownModule():\\n closeConnection()\\n\\nIf an exception is raised in a setUpModule then none of the tests in the module will be run and the tearDownModule will not be run. If the exception is a SkipTest exception then the module will be reported as having been skipped instead of as an error.\\n\\nTo add cleanup code that must be run even in the case of an exception, use addModuleCleanup:\\n\\nSignal Handling¶\\n\\nAdded in version 3.2.\\n\\nThe -c/--catch command-line option to unittest, along with the catchbreak parameter to unittest.main(), provide more friendly handling of control-C during a test run. With catch break behavior enabled control-C will allow the currently running test to complete, and the test run will then end and report all the results so far. A second control-c will raise a KeyboardInterrupt in the usual way.\\n\\nThe control-c handling signal handler attempts to remain compatible with code or tests that install their own signal.SIGINT handler. If the unittest handler is called but isn’t the installed signal.SIGINT handler, i.e. it has been replaced by the system under test and delegated to, then it calls the default handler. This will normally be the expected behavior by code that replaces an installed handler and delegates to it. For individual tests that need unittest control-c handling disabled the removeHandler() decorator can be used.\\n\\nThere are a few utility functions for framework authors to enable control-c handling functionality within test frameworks.\\n\\nTable of Contents\\n\\nunittest — Unit testing framework\\n\\nBasic example\\n\\nCommand-Line Interface\\n\\nCommand-line options\\n\\nTest Discovery\\n\\nOrganizing test code\\n\\nRe-using old test code\\n\\nSkipping tests and expected failures\\n\\nDistinguishing test iterations using subtests\\n\\nClasses and functions\\n\\nTest cases\\n\\nGrouping tests\\n\\nLoading and running tests\\n\\nload_tests Protocol\\n\\nClass and Module Fixtures\\n\\nsetUpClass and tearDownClass\\n\\nsetUpModule and tearDownModule\\n\\nSignal Handling\\n\\nPrevious topic\\n\\ndoctest — Test interactive Python examples\\n\\nNext topic\\n\\nunittest.mock — mock object library\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nDevelopment Tools »\\n\\nunittest — Unit testing framework\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\unittest.mock-examples.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nDevelopment Tools »\\n\\nunittest.mock — getting started\\n\\n|\\n\\nunittest.mock — getting started¶\\n\\nAdded in version 3.3.\\n\\nUsing Mock¶\\n\\nMock Patching Methods¶\\n\\nCommon uses for Mock objects include:\\n\\nPatching methods\\n\\nRecording method calls on objects\\n\\nYou might want to replace a method on an object to check that it is called with the correct arguments by another part of the system:\\n\\n>>> real = SomeClass()\\n>>> real.method = MagicMock(name=\\'method\\')\\n>>> real.method(3, 4, 5, key=\\'value\\')\\n\\n\\nOnce our mock has been used (real.method in this example) it has methods and attributes that allow you to make assertions about how it has been used.\\n\\nNote\\n\\nIn most of these examples the Mock and MagicMock classes are interchangeable. As the MagicMock is the more capable class it makes a sensible one to use by default.\\n\\nOnce the mock has been called its called attribute is set to True. More importantly we can use the assert_called_with() or assert_called_once_with() method to check that it was called with the correct arguments.\\n\\nThis example tests that calling ProductionClass().method results in a call to the something method:\\n\\n>>> class ProductionClass:\\n... def method(self):\\n... self.something(1, 2, 3)\\n... def something(self, a, b, c):\\n... pass\\n...\\n>>> real = ProductionClass()\\n>>> real.something = MagicMock()\\n>>> real.method()\\n>>> real.something.assert_called_once_with(1, 2, 3)\\n\\nMock for Method Calls on an Object¶\\n\\nIn the last example we patched a method directly on an object to check that it was called correctly. Another common use case is to pass an object into a method (or some part of the system under test) and then check that it is used in the correct way.\\n\\nThe simple ProductionClass below has a closer method. If it is called with an object then it calls close on it.\\n\\n>>> class ProductionClass:\\n... def closer(self, something):\\n... something.close()\\n...\\n\\nSo to test it we need to pass in an object with a close method and check that it was called correctly.\\n\\n>>> real = ProductionClass()\\n>>> mock = Mock()\\n>>> real.closer(mock)\\n>>> mock.close.assert_called_with()\\n\\nWe don’t have to do any work to provide the ‘close’ method on our mock. Accessing close creates it. So, if ‘close’ hasn’t already been called then accessing it in the test will create it, but assert_called_with() will raise a failure exception.\\n\\nMocking Classes¶\\n\\nA common use case is to mock out classes instantiated by your code under test. When you patch a class, then that class is replaced with a mock. Instances are created by calling the class. This means you access the “mock instance” by looking at the return value of the mocked class.\\n\\nIn the example below we have a function some_function that instantiates Foo and calls a method on it. The call to patch() replaces the class Foo with a mock. The Foo instance is the result of calling the mock, so it is configured by modifying the mock return_value.\\n\\n>>> def some_function():\\n... instance = module.Foo()\\n... return instance.method()\\n...\\n>>> with patch(\\'module.Foo\\') as mock:\\n... instance = mock.return_value\\n... instance.method.return_value = \\'the result\\'\\n... result = some_function()\\n... assert result == \\'the result\\'\\n\\nNaming your mocks¶\\n\\nIt can be useful to give your mocks a name. The name is shown in the repr of the mock and can be helpful when the mock appears in test failure messages. The name is also propagated to attributes or methods of the mock:\\n\\n>>> mock = MagicMock(name=\\'foo\\')\\n>>> mock\\n\\n>>> mock.method\\n\\n\\nTracking all Calls¶\\n\\nOften you want to track more than a single call to a method. The mock_calls attribute records all calls to child attributes of the mock - and also to their children.\\n\\n>>> mock = MagicMock()\\n>>> mock.method()\\n\\n>>> mock.attribute.method(10, x=53)\\n\\n>>> mock.mock_calls\\n[call.method(), call.attribute.method(10, x=53)]\\n\\nIf you make an assertion about mock_calls and any unexpected methods have been called, then the assertion will fail. This is useful because as well as asserting that the calls you expected have been made, you are also checking that they were made in the right order and with no additional calls:\\n\\nYou use the call object to construct lists for comparing with mock_calls:\\n\\n>>> expected = [call.method(), call.attribute.method(10, x=53)]\\n>>> mock.mock_calls == expected\\nTrue\\n\\nHowever, 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:\\n\\n>>> m = Mock()\\n>>> m.factory(important=True).deliver()\\n\\n>>> m.mock_calls[-1] == call.factory(important=False).deliver()\\nTrue\\n\\nSetting Return Values and Attributes¶\\n\\nSetting the return values on a mock object is trivially easy:\\n\\n>>> mock = Mock()\\n>>> mock.return_value = 3\\n>>> mock()\\n3\\n\\nOf course you can do the same for methods on the mock:\\n\\n>>> mock = Mock()\\n>>> mock.method.return_value = 3\\n>>> mock.method()\\n3\\n\\nThe return value can also be set in the constructor:\\n\\n>>> mock = Mock(return_value=3)\\n>>> mock()\\n3\\n\\nIf you need an attribute setting on your mock, just do it:\\n\\n>>> mock = Mock()\\n>>> mock.x = 3\\n>>> mock.x\\n3\\n\\nSometimes you want to mock up a more complex situation, like for example mock.connection.cursor().execute(\"SELECT 1\"). If we wanted this call to return a list, then we have to configure the result of the nested call.\\n\\nWe can use call to construct the set of calls in a “chained call” like this for easy assertion afterwards:\\n\\n>>> mock = Mock()\\n>>> cursor = mock.connection.cursor.return_value\\n>>> cursor.execute.return_value = [\\'foo\\']\\n>>> mock.connection.cursor().execute(\"SELECT 1\")\\n[\\'foo\\']\\n>>> expected = call.connection.cursor().execute(\"SELECT 1\").call_list()\\n>>> mock.mock_calls\\n[call.connection.cursor(), call.connection.cursor().execute(\\'SELECT 1\\')]\\n>>> mock.mock_calls == expected\\nTrue\\n\\nIt is the call to .call_list() that turns our call object into a list of calls representing the chained calls.\\n\\nRaising exceptions with mocks¶\\n\\nA useful attribute is side_effect. If you set this to an exception class or instance then the exception will be raised when the mock is called.\\n\\n>>> mock = Mock(side_effect=Exception(\\'Boom!\\'))\\n>>> mock()\\nTraceback (most recent call last):\\n ...\\nException: Boom!\\n\\nSide effect functions and iterables¶\\n\\nside_effect can also be set to a function or an iterable. The use case for side_effect as an iterable is where your mock is going to be called several times, and you want each call to return a different value. When you set side_effect to an iterable every call to the mock returns the next value from the iterable:\\n\\n>>> mock = MagicMock(side_effect=[4, 5, 6])\\n>>> mock()\\n4\\n>>> mock()\\n5\\n>>> mock()\\n6\\n\\nFor more advanced use cases, like dynamically varying the return values depending on what the mock is called with, side_effect can be a function. The function will be called with the same arguments as the mock. Whatever the function returns is what the call returns:\\n\\n>>> vals = {(1, 2): 1, (2, 3): 2}\\n>>> def side_effect(*args):\\n... return vals[args]\\n...\\n>>> mock = MagicMock(side_effect=side_effect)\\n>>> mock(1, 2)\\n1\\n>>> mock(2, 3)\\n2\\n\\nMocking asynchronous iterators¶\\n\\nSince Python 3.8, AsyncMock and MagicMock have support to mock Asynchronous Iterators through __aiter__. The return_value attribute of __aiter__ can be used to set the return values to be used for iteration.\\n\\n>>> mock = MagicMock() # AsyncMock also works here\\n>>> mock.__aiter__.return_value = [1, 2, 3]\\n>>> async def main():\\n... return [i async for i in mock]\\n...\\n>>> asyncio.run(main())\\n[1, 2, 3]\\n\\nMocking asynchronous context manager¶\\n\\nSince Python 3.8, AsyncMock and MagicMock have support to mock Asynchronous Context Managers through __aenter__ and __aexit__. By default, __aenter__ and __aexit__ are AsyncMock instances that return an async function.\\n\\n>>> class AsyncContextManager:\\n... async def __aenter__(self):\\n... return self\\n... async def __aexit__(self, exc_type, exc, tb):\\n... pass\\n...\\n>>> mock_instance = MagicMock(AsyncContextManager()) # AsyncMock also works here\\n>>> async def main():\\n... async with mock_instance as result:\\n... pass\\n...\\n>>> asyncio.run(main())\\n>>> mock_instance.__aenter__.assert_awaited_once()\\n>>> mock_instance.__aexit__.assert_awaited_once()\\n\\nCreating a Mock from an Existing Object¶\\n\\nOne problem with over use of mocking is that it couples your tests to the implementation of your mocks rather than your real code. Suppose you have a class that implements some_method. In a test for another class, you provide a mock of this object that also provides some_method. If later you refactor the first class, so that it no longer has some_method - then your tests will continue to pass even though your code is now broken!\\n\\nMock allows you to provide an object as a specification for the mock, using the spec keyword argument. Accessing methods / attributes on the mock that don’t exist on your specification object will immediately raise an attribute error. If you change the implementation of your specification, then tests that use that class will start failing immediately without you having to instantiate the class in those tests.\\n\\n>>> mock = Mock(spec=SomeClass)\\n>>> mock.old_method()\\nTraceback (most recent call last):\\n ...\\nAttributeError: Mock object has no attribute \\'old_method\\'. Did you mean: \\'class_method\\'?\\n\\nUsing a specification also enables a smarter matching of calls made to the mock, regardless of whether some parameters were passed as positional or named arguments:\\n\\n>>> def f(a, b, c): pass\\n...\\n>>> mock = Mock(spec=f)\\n>>> mock(1, 2, 3)\\n\\n>>> mock.assert_called_with(a=1, b=2, c=3)\\n\\nIf you want this smarter matching to also work with method calls on the mock, you can use auto-speccing.\\n\\nIf you want a stronger form of specification that prevents the setting of arbitrary attributes as well as the getting of them then you can use spec_set instead of spec.\\n\\nUsing side_effect to return per file content¶\\n\\nmock_open() is used to patch open() method. 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:\\n\\nDEFAULT = \"default\"\\ndata_dict = {\"file1\": \"data1\",\\n \"file2\": \"data2\"}\\n\\ndef open_side_effect(name):\\n return mock_open(read_data=data_dict.get(name, DEFAULT))()\\n\\nwith patch(\"builtins.open\", side_effect=open_side_effect):\\n with open(\"file1\") as file1:\\n assert file1.read() == \"data1\"\\n\\n with open(\"file2\") as file2:\\n assert file2.read() == \"data2\"\\n\\n with open(\"file3\") as file2:\\n assert file2.read() == \"default\"\\n\\nPatch Decorators¶\\n\\nNote\\n\\nWith patch() it matters that you patch objects in the namespace where they are looked up. This is normally straightforward, but for a quick guide read where to patch.\\n\\nA common need in tests is to patch a class attribute or a module attribute, for example patching a builtin or patching a class in a module to test that it is instantiated. Modules and classes are effectively global, so patching on them has to be undone after the test or the patch will persist into other tests and cause hard to diagnose problems.\\n\\nmock provides three convenient decorators for this: patch(), patch.object() and patch.dict(). patch takes a single string, of the form package.module.Class.attribute to specify the attribute you are patching. It also optionally takes a value that you want the attribute (or class or whatever) to be replaced with. ‘patch.object’ takes an object and the name of the attribute you would like patched, plus optionally the value to patch it with.\\n\\npatch.object:\\n\\n>>> original = SomeClass.attribute\\n>>> @patch.object(SomeClass, \\'attribute\\', sentinel.attribute)\\n... def test():\\n... assert SomeClass.attribute == sentinel.attribute\\n...\\n>>> test()\\n>>> assert SomeClass.attribute == original\\n\\n>>> @patch(\\'package.module.attribute\\', sentinel.attribute)\\n... def test():\\n... from package.module import attribute\\n... assert attribute is sentinel.attribute\\n...\\n>>> test()\\n\\nIf you are patching a module (including builtins) then use patch() instead of patch.object():\\n\\n>>> mock = MagicMock(return_value=sentinel.file_handle)\\n>>> with patch(\\'builtins.open\\', mock):\\n... handle = open(\\'filename\\', \\'r\\')\\n...\\n>>> mock.assert_called_with(\\'filename\\', \\'r\\')\\n>>> assert handle == sentinel.file_handle, \"incorrect file handle returned\"\\n\\nThe module name can be ‘dotted’, in the form package.module if needed:\\n\\n>>> @patch(\\'package.module.ClassName.attribute\\', sentinel.attribute)\\n... def test():\\n... from package.module import ClassName\\n... assert ClassName.attribute == sentinel.attribute\\n...\\n>>> test()\\n\\nA nice pattern is to actually decorate test methods themselves:\\n\\n>>> class MyTest(unittest.TestCase):\\n... @patch.object(SomeClass, \\'attribute\\', sentinel.attribute)\\n... def test_something(self):\\n... self.assertEqual(SomeClass.attribute, sentinel.attribute)\\n...\\n>>> original = SomeClass.attribute\\n>>> MyTest(\\'test_something\\').test_something()\\n>>> assert SomeClass.attribute == original\\n\\nIf you want to patch with a Mock, you can use patch() with only one argument (or patch.object() with two arguments). The mock will be created for you and passed into the test function / method:\\n\\n>>> class MyTest(unittest.TestCase):\\n... @patch.object(SomeClass, \\'static_method\\')\\n... def test_something(self, mock_method):\\n... SomeClass.static_method()\\n... mock_method.assert_called_with()\\n...\\n>>> MyTest(\\'test_something\\').test_something()\\n\\nYou can stack up multiple patch decorators using this pattern:\\n\\n>>> class MyTest(unittest.TestCase):\\n... @patch(\\'package.module.ClassName1\\')\\n... @patch(\\'package.module.ClassName2\\')\\n... def test_something(self, MockClass2, MockClass1):\\n... self.assertIs(package.module.ClassName1, MockClass1)\\n... self.assertIs(package.module.ClassName2, MockClass2)\\n...\\n>>> MyTest(\\'test_something\\').test_something()\\n\\nWhen you nest patch decorators the mocks are passed in to the decorated function in the same order they applied (the normal Python order that decorators are applied). This means from the bottom up, so in the example above the mock for test_module.ClassName2 is passed in first.\\n\\nThere is also patch.dict() for setting values in a dictionary just during a scope and restoring the dictionary to its original state when the test ends:\\n\\n>>> foo = {\\'key\\': \\'value\\'}\\n>>> original = foo.copy()\\n>>> with patch.dict(foo, {\\'newkey\\': \\'newvalue\\'}, clear=True):\\n... assert foo == {\\'newkey\\': \\'newvalue\\'}\\n...\\n>>> assert foo == original\\n\\npatch, patch.object and patch.dict can all be used as context managers.\\n\\nWhere you use patch() to create a mock for you, you can get a reference to the mock using the “as” form of the with statement:\\n\\n>>> class ProductionClass:\\n... def method(self):\\n... pass\\n...\\n>>> with patch.object(ProductionClass, \\'method\\') as mock_method:\\n... mock_method.return_value = None\\n... real = ProductionClass()\\n... real.method(1, 2, 3)\\n...\\n>>> mock_method.assert_called_with(1, 2, 3)\\n\\nAs an alternative patch, patch.object and patch.dict can be used as class decorators. When used in this way it is the same as applying the decorator individually to every method whose name starts with “test”.\\n\\nFurther Examples¶\\n\\nHere are some more examples for some slightly more advanced scenarios.\\n\\nMocking chained calls¶\\n\\nMocking chained calls is actually straightforward with mock once you understand the return_value attribute. When a mock is called for the first time, or you fetch its return_value before it has been called, a new Mock is created.\\n\\nThis means that you can see how the object returned from a call to a mocked object has been used by interrogating the return_value mock:\\n\\n>>> mock = Mock()\\n>>> mock().foo(a=2, b=3)\\n\\n>>> mock.return_value.foo.assert_called_with(a=2, b=3)\\n\\nFrom here it is a simple step to configure and then make assertions about chained calls. Of course another alternative is writing your code in a more testable way in the first place…\\n\\nSo, suppose we have some code that looks a little bit like this:\\n\\n>>> class Something:\\n... def __init__(self):\\n... self.backend = BackendProvider()\\n... def method(self):\\n... response = self.backend.get_endpoint(\\'foobar\\').create_call(\\'spam\\', \\'eggs\\').start_call()\\n... # more code\\n\\nAssuming that BackendProvider is already well tested, how do we test method()? Specifically, we want to test that the code section # more code uses the response object in the correct way.\\n\\nAs this chain of calls is made from an instance attribute we can monkey patch the backend attribute on a Something instance. In this particular case we are only interested in the return value from the final call to start_call so we don’t have much configuration to do. Let’s assume the object it returns is ‘file-like’, so we’ll ensure that our response object uses the builtin open() as its spec.\\n\\nTo do this we create a mock instance as our mock backend and create a mock response object for it. To set the response as the return value for that final start_call we could do this:\\n\\nmock_backend.get_endpoint.return_value.create_call.return_value.start_call.return_value = mock_response\\n\\nWe can do that in a slightly nicer way using the configure_mock() method to directly set the return value for us:\\n\\n>>> something = Something()\\n>>> mock_response = Mock(spec=open)\\n>>> mock_backend = Mock()\\n>>> config = {\\'get_endpoint.return_value.create_call.return_value.start_call.return_value\\': mock_response}\\n>>> mock_backend.configure_mock(**config)\\n\\nWith these we monkey patch the “mock backend” in place and can make the real call:\\n\\n>>> something.backend = mock_backend\\n>>> something.method()\\n\\nUsing mock_calls we can check the chained call with a single assert. A chained call is several calls in one line of code, so there will be several entries in mock_calls. We can use call.call_list() to create this list of calls for us:\\n\\n>>> chained = call.get_endpoint(\\'foobar\\').create_call(\\'spam\\', \\'eggs\\').start_call()\\n>>> call_list = chained.call_list()\\n>>> assert mock_backend.mock_calls == call_list\\n\\nPartial mocking¶\\n\\nFor some tests, you may want to mock out a call to datetime.date.today() to return a known date, but don’t want to prevent the code under test from creating new date objects. Unfortunately datetime.date is written in C, so you cannot just monkey-patch out the static datetime.date.today() method.\\n\\nInstead, 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).\\n\\nThe patch decorator is used here to mock out the date class in the module under test. The side_effect attribute on the mock date class is then set to a lambda function that returns a real date. When the mock date class is called a real date will be constructed and returned by side_effect.\\n\\n>>> from datetime import date\\n>>> with patch(\\'mymodule.date\\') as mock_date:\\n... mock_date.today.return_value = date(2010, 10, 8)\\n... mock_date.side_effect = lambda *args, **kw: date(*args, **kw)\\n...\\n... assert mymodule.date.today() == date(2010, 10, 8)\\n... assert mymodule.date(2009, 6, 8) == date(2009, 6, 8)\\n\\nNote that we don’t patch datetime.date globally, we patch date in the module that uses it. See where to patch.\\n\\nWhen date.today() is called a known date is returned, but calls to the date(...) constructor still return normal dates. Without this you can find yourself having to calculate an expected result using exactly the same algorithm as the code under test, which is a classic testing anti-pattern.\\n\\nCalls to the date constructor are recorded in the mock_date attributes (call_count and friends) which may also be useful for your tests.\\n\\nAn alternative way of dealing with mocking dates, or other builtin classes, is discussed in this blog entry.\\n\\nMocking a Generator Method¶\\n\\nA Python generator is a function or method that uses the yield statement to return a series of values when iterated over [1].\\n\\nA generator method / function is called to return the generator object. It is the generator object that is then iterated over. The protocol method for iteration is __iter__(), so we can mock this using a MagicMock.\\n\\nHere’s an example class with an “iter” method implemented as a generator:\\n\\n>>> class Foo:\\n... def iter(self):\\n... for i in [1, 2, 3]:\\n... yield i\\n...\\n>>> foo = Foo()\\n>>> list(foo.iter())\\n[1, 2, 3]\\n\\nHow would we mock this class, and in particular its “iter” method?\\n\\nTo configure the values returned from the iteration (implicit in the call to list), we need to configure the object returned by the call to foo.iter().\\n\\n>>> mock_foo = MagicMock()\\n>>> mock_foo.iter.return_value = iter([1, 2, 3])\\n>>> list(mock_foo.iter())\\n[1, 2, 3]\\n\\n[1]\\n\\nThere are also generator expressions and more advanced uses of generators, but we aren’t concerned about them here. A very good introduction to generators and how powerful they are is: Generator Tricks for Systems Programmers.\\n\\nApplying the same patch to every test method¶\\n\\nIf you want several patches in place for multiple test methods the obvious way is to apply the patch decorators to every method. This can feel like unnecessary repetition. Instead, you can use patch() (in all its various forms) as a class decorator. This applies the patches to all test methods on the class. A test method is identified by methods whose names start with test:\\n\\n>>> @patch(\\'mymodule.SomeClass\\')\\n... class MyTest(unittest.TestCase):\\n...\\n... def test_one(self, MockSomeClass):\\n... self.assertIs(mymodule.SomeClass, MockSomeClass)\\n...\\n... def test_two(self, MockSomeClass):\\n... self.assertIs(mymodule.SomeClass, MockSomeClass)\\n...\\n... def not_a_test(self):\\n... return \\'something\\'\\n...\\n>>> MyTest(\\'test_one\\').test_one()\\n>>> MyTest(\\'test_two\\').test_two()\\n>>> MyTest(\\'test_two\\').not_a_test()\\n\\'something\\'\\n\\nAn alternative way of managing patches is to use the patch methods: start and stop. These allow you to move the patching into your setUp and tearDown methods.\\n\\n>>> class MyTest(unittest.TestCase):\\n... def setUp(self):\\n... self.patcher = patch(\\'mymodule.foo\\')\\n... self.mock_foo = self.patcher.start()\\n...\\n... def test_foo(self):\\n... self.assertIs(mymodule.foo, self.mock_foo)\\n...\\n... def tearDown(self):\\n... self.patcher.stop()\\n...\\n>>> MyTest(\\'test_foo\\').run()\\n\\nIf you use this technique you must ensure that the patching is “undone” by calling stop. This can be fiddlier than you might think, because if an exception is raised in the setUp then tearDown is not called. unittest.TestCase.addCleanup() makes this easier:\\n\\n>>> class MyTest(unittest.TestCase):\\n... def setUp(self):\\n... patcher = patch(\\'mymodule.foo\\')\\n... self.addCleanup(patcher.stop)\\n... self.mock_foo = patcher.start()\\n...\\n... def test_foo(self):\\n... self.assertIs(mymodule.foo, self.mock_foo)\\n...\\n>>> MyTest(\\'test_foo\\').run()\\n\\nMocking Unbound Methods¶\\n\\nSometimes 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 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 self passed in. The workaround is to patch the unbound method with a real function instead. The patch() decorator makes it so simple to patch out methods with a mock that having to create a real function becomes a nuisance.\\n\\nIf you pass autospec=True to patch then it does the patching with a real function object. This function object has the same signature as the one it is replacing, but delegates to a mock under the hood. You still get your mock auto-created in exactly the same way as before. What it means though, is that if you use it to patch out an unbound method on a class the mocked function will be turned into a bound method if it is fetched from an instance. It will have self passed in as the first argument, which is exactly what was needed:\\n\\n>>> class Foo:\\n... def foo(self):\\n... pass\\n...\\n>>> with patch.object(Foo, \\'foo\\', autospec=True) as mock_foo:\\n... mock_foo.return_value = \\'foo\\'\\n... foo = Foo()\\n... foo.foo()\\n...\\n\\'foo\\'\\n>>> mock_foo.assert_called_once_with(foo)\\n\\nIf we don’t use autospec=True then the unbound method is patched out with a Mock instance instead, and isn’t called with self.\\n\\nChecking multiple calls with mock¶\\n\\nmock has a nice API for making assertions about how your mock objects are used.\\n\\n>>> mock = Mock()\\n>>> mock.foo_bar.return_value = None\\n>>> mock.foo_bar(\\'baz\\', spam=\\'eggs\\')\\n>>> mock.foo_bar.assert_called_with(\\'baz\\', spam=\\'eggs\\')\\n\\nIf your mock is only being called once you can use the assert_called_once_with() method that also asserts that the call_count is one.\\n\\n>>> mock.foo_bar.assert_called_once_with(\\'baz\\', spam=\\'eggs\\')\\n>>> mock.foo_bar()\\n>>> mock.foo_bar.assert_called_once_with(\\'baz\\', spam=\\'eggs\\')\\nTraceback (most recent call last):\\n ...\\nAssertionError: Expected \\'foo_bar\\' to be called once. Called 2 times.\\nCalls: [call(\\'baz\\', spam=\\'eggs\\'), call()].\\n\\nBoth assert_called_with and assert_called_once_with make assertions about the most recent call. If your mock is going to be called several times, and you want to make assertions about all those calls you can use call_args_list:\\n\\n>>> mock = Mock(return_value=None)\\n>>> mock(1, 2, 3)\\n>>> mock(4, 5, 6)\\n>>> mock()\\n>>> mock.call_args_list\\n[call(1, 2, 3), call(4, 5, 6), call()]\\n\\nThe call helper makes it easy to make assertions about these calls. You can build up a list of expected calls and compare it to call_args_list. This looks remarkably similar to the repr of the call_args_list:\\n\\n>>> expected = [call(1, 2, 3), call(4, 5, 6), call()]\\n>>> mock.call_args_list == expected\\nTrue\\n\\nCoping with mutable arguments¶\\n\\nAnother situation is rare, but can bite you, is when your mock is called with mutable arguments. call_args and call_args_list store references to the arguments. If the arguments are mutated by the code under test then you can no longer make assertions about what the values were when the mock was called.\\n\\nHere’s some example code that shows the problem. Imagine the following functions defined in ‘mymodule’:\\n\\ndef frob(val):\\n pass\\n\\ndef grob(val):\\n \"First frob and then clear val\"\\n frob(val)\\n val.clear()\\n\\nWhen we try to test that grob calls frob with the correct argument look what happens:\\n\\n>>> with patch(\\'mymodule.frob\\') as mock_frob:\\n... val = {6}\\n... mymodule.grob(val)\\n...\\n>>> val\\nset()\\n>>> mock_frob.assert_called_with({6})\\nTraceback (most recent call last):\\n ...\\nAssertionError: Expected: (({6},), {})\\nCalled with: ((set(),), {})\\n\\nOne possibility would be for mock to copy the arguments you pass in. This could then cause problems if you do assertions that rely on object identity for equality.\\n\\nHere’s one solution that uses the side_effect functionality. If you provide a side_effect function for a mock then side_effect will be called with the same args as the mock. This gives us an opportunity to copy the arguments and store them for later assertions. In this example we’re using another mock to store the arguments so that we can use the mock methods for doing the assertion. Again a helper function sets this up for us.\\n\\n>>> from copy import deepcopy\\n>>> from unittest.mock import Mock, patch, DEFAULT\\n>>> def copy_call_args(mock):\\n... new_mock = Mock()\\n... def side_effect(*args, **kwargs):\\n... args = deepcopy(args)\\n... kwargs = deepcopy(kwargs)\\n... new_mock(*args, **kwargs)\\n... return DEFAULT\\n... mock.side_effect = side_effect\\n... return new_mock\\n...\\n>>> with patch(\\'mymodule.frob\\') as mock_frob:\\n... new_mock = copy_call_args(mock_frob)\\n... val = {6}\\n... mymodule.grob(val)\\n...\\n>>> new_mock.assert_called_with({6})\\n>>> new_mock.call_args\\ncall({6})\\n\\ncopy_call_args is called with the mock that will be called. It returns a new mock that we do the assertion on. The side_effect function makes a copy of the args and calls our new_mock with the copy.\\n\\nNote\\n\\nIf your mock is only going to be used once there is an easier way of checking arguments at the point they are called. You can simply do the checking inside a side_effect function.\\n\\n>>> def side_effect(arg):\\n... assert arg == {6}\\n...\\n>>> mock = Mock(side_effect=side_effect)\\n>>> mock({6})\\n>>> mock(set())\\nTraceback (most recent call last):\\n ...\\nAssertionError\\n\\nAn alternative approach is to create a subclass of Mock or MagicMock that copies (using copy.deepcopy()) the arguments. Here’s an example implementation:\\n\\n>>> from copy import deepcopy\\n>>> class CopyingMock(MagicMock):\\n... def __call__(self, /, *args, **kwargs):\\n... args = deepcopy(args)\\n... kwargs = deepcopy(kwargs)\\n... return super().__call__(*args, **kwargs)\\n...\\n>>> c = CopyingMock(return_value=None)\\n>>> arg = set()\\n>>> c(arg)\\n>>> arg.add(1)\\n>>> c.assert_called_with(set())\\n>>> c.assert_called_with(arg)\\nTraceback (most recent call last):\\n ...\\nAssertionError: expected call not found.\\nExpected: mock({1})\\nActual: mock(set())\\n>>> c.foo\\n\\n\\nWhen you subclass Mock or MagicMock all dynamically created attributes, and the return_value will use your subclass automatically. That means all children of a CopyingMock will also have the type CopyingMock.\\n\\nNesting Patches¶\\n\\nUsing 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:\\n\\n>>> class MyTest(unittest.TestCase):\\n...\\n... def test_foo(self):\\n... with patch(\\'mymodule.Foo\\') as mock_foo:\\n... with patch(\\'mymodule.Bar\\') as mock_bar:\\n... with patch(\\'mymodule.Spam\\') as mock_spam:\\n... assert mymodule.Foo is mock_foo\\n... assert mymodule.Bar is mock_bar\\n... assert mymodule.Spam is mock_spam\\n...\\n>>> original = mymodule.Foo\\n>>> MyTest(\\'test_foo\\').test_foo()\\n>>> assert mymodule.Foo is original\\n\\nWith unittest cleanup functions and the patch methods: start and stop we can achieve the same effect without the nested indentation. A simple helper method, create_patch, puts the patch in place and returns the created mock for us:\\n\\n>>> class MyTest(unittest.TestCase):\\n...\\n... def create_patch(self, name):\\n... patcher = patch(name)\\n... thing = patcher.start()\\n... self.addCleanup(patcher.stop)\\n... return thing\\n...\\n... def test_foo(self):\\n... mock_foo = self.create_patch(\\'mymodule.Foo\\')\\n... mock_bar = self.create_patch(\\'mymodule.Bar\\')\\n... mock_spam = self.create_patch(\\'mymodule.Spam\\')\\n...\\n... assert mymodule.Foo is mock_foo\\n... assert mymodule.Bar is mock_bar\\n... assert mymodule.Spam is mock_spam\\n...\\n>>> original = mymodule.Foo\\n>>> MyTest(\\'test_foo\\').run()\\n>>> assert mymodule.Foo is original\\n\\nMocking a dictionary with MagicMock¶\\n\\nYou may want to mock a dictionary, or other container object, recording all access to it whilst having it still behave like a dictionary.\\n\\nWe can do this with MagicMock, which will behave like a dictionary, and using side_effect to delegate dictionary access to a real underlying dictionary that is under our control.\\n\\nWhen the __getitem__() and __setitem__() methods of our MagicMock are called (normal dictionary access) then side_effect is called with the key (and in the case of __setitem__ the value too). We can also control what is returned.\\n\\nAfter the MagicMock has been used we can use attributes like call_args_list to assert about how the dictionary was used:\\n\\n>>> my_dict = {\\'a\\': 1, \\'b\\': 2, \\'c\\': 3}\\n>>> def getitem(name):\\n... return my_dict[name]\\n...\\n>>> def setitem(name, val):\\n... my_dict[name] = val\\n...\\n>>> mock = MagicMock()\\n>>> mock.__getitem__.side_effect = getitem\\n>>> mock.__setitem__.side_effect = setitem\\n\\nNote\\n\\nAn alternative to using MagicMock is to use Mock and only provide the magic methods you specifically want:\\n\\n>>> mock = Mock()\\n>>> mock.__getitem__ = Mock(side_effect=getitem)\\n>>> mock.__setitem__ = Mock(side_effect=setitem)\\n\\nA third option is to use MagicMock but passing in dict as the spec (or spec_set) argument so that the MagicMock created only has dictionary magic methods available:\\n\\n>>> mock = MagicMock(spec_set=dict)\\n>>> mock.__getitem__.side_effect = getitem\\n>>> mock.__setitem__.side_effect = setitem\\n\\nWith these side effect functions in place, the mock will behave like a normal dictionary but recording the access. It even raises a KeyError if you try to access a key that doesn’t exist.\\n\\n>>> mock[\\'a\\']\\n1\\n>>> mock[\\'c\\']\\n3\\n>>> mock[\\'d\\']\\nTraceback (most recent call last):\\n ...\\nKeyError: \\'d\\'\\n>>> mock[\\'b\\'] = \\'fish\\'\\n>>> mock[\\'d\\'] = \\'eggs\\'\\n>>> mock[\\'b\\']\\n\\'fish\\'\\n>>> mock[\\'d\\']\\n\\'eggs\\'\\n\\nAfter it has been used you can make assertions about the access using the normal mock methods and attributes:\\n\\n>>> mock.__getitem__.call_args_list\\n[call(\\'a\\'), call(\\'c\\'), call(\\'d\\'), call(\\'b\\'), call(\\'d\\')]\\n>>> mock.__setitem__.call_args_list\\n[call(\\'b\\', \\'fish\\'), call(\\'d\\', \\'eggs\\')]\\n>>> my_dict\\n{\\'a\\': 1, \\'b\\': \\'fish\\', \\'c\\': 3, \\'d\\': \\'eggs\\'}\\n\\nMock subclasses and their attributes¶\\n\\nThere are various reasons why you might want to subclass Mock. One reason might be to add helper methods. Here’s a silly example:\\n\\n>>> class MyMock(MagicMock):\\n... def has_been_called(self):\\n... return self.called\\n...\\n>>> mymock = MyMock(return_value=None)\\n>>> mymock\\n\\n>>> mymock.has_been_called()\\nFalse\\n>>> mymock()\\n>>> mymock.has_been_called()\\nTrue\\n\\nThe standard behaviour for Mock instances is that attributes and the return value mocks are of the same type as the mock they are accessed on. This ensures that Mock attributes are Mocks and MagicMock attributes are MagicMocks [2]. 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.\\n\\n>>> mymock.foo\\n\\n>>> mymock.foo.has_been_called()\\nFalse\\n>>> mymock.foo()\\n\\n>>> mymock.foo.has_been_called()\\nTrue\\n\\nSometimes this is inconvenient. For example, one user is subclassing mock to created a Twisted adaptor. Having this applied to attributes too actually causes errors.\\n\\nMock (in all its flavours) uses a method called _get_child_mock to create these “sub-mocks” for attributes and return values. You can prevent your subclass being used for attributes by overriding this method. The signature is that it takes arbitrary keyword arguments (**kwargs) which are then passed onto the mock constructor:\\n\\n>>> class Subclass(MagicMock):\\n... def _get_child_mock(self, /, **kwargs):\\n... return MagicMock(**kwargs)\\n...\\n>>> mymock = Subclass()\\n>>> mymock.foo\\n\\n>>> assert isinstance(mymock, Subclass)\\n>>> assert not isinstance(mymock.foo, Subclass)\\n>>> assert not isinstance(mymock(), Subclass)\\n\\n[2]\\n\\nAn exception to this rule are the non-callable mocks. Attributes use the callable variant because otherwise non-callable mocks couldn’t have callable methods.\\n\\nMocking imports with patch.dict¶\\n\\nOne 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.\\n\\nGenerally 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).\\n\\nThat aside there is a way to use mock to affect the results of an import. Importing fetches an object from the 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 sys.modules, so usually when you import something you get a module back. This need not be the case however.\\n\\nThis means you can use patch.dict() to temporarily put a mock in place in 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 patcher.stop() is called) then whatever was there previously will be restored safely.\\n\\nHere’s an example that mocks out the ‘fooble’ module.\\n\\n>>> import sys\\n>>> mock = Mock()\\n>>> with patch.dict(\\'sys.modules\\', {\\'fooble\\': mock}):\\n... import fooble\\n... fooble.blob()\\n...\\n\\n>>> assert \\'fooble\\' not in sys.modules\\n>>> mock.blob.assert_called_once_with()\\n\\nAs you can see the import fooble succeeds, but on exit there is no ‘fooble’ left in sys.modules.\\n\\nThis also works for the from module import name form:\\n\\n>>> mock = Mock()\\n>>> with patch.dict(\\'sys.modules\\', {\\'fooble\\': mock}):\\n... from fooble import blob\\n... blob.blip()\\n...\\n\\n>>> mock.blob.blip.assert_called_once_with()\\n\\nWith slightly more work you can also mock package imports:\\n\\n>>> mock = Mock()\\n>>> modules = {\\'package\\': mock, \\'package.module\\': mock.module}\\n>>> with patch.dict(\\'sys.modules\\', modules):\\n... from package.module import fooble\\n... fooble()\\n...\\n\\n>>> mock.module.fooble.assert_called_once_with()\\n\\nTracking order of calls and less verbose call assertions¶\\n\\nThe Mock class allows you to track the order of method calls on your mock objects through the method_calls attribute. This doesn’t allow you to track the order of calls between separate mock objects, however we can use mock_calls to achieve the same effect.\\n\\nBecause mocks track calls to child mocks in mock_calls, and accessing an arbitrary attribute of a mock creates a child mock, we can create our separate mocks from a parent one. Calls to those child mock will then all be recorded, in order, in the mock_calls of the parent:\\n\\n>>> manager = Mock()\\n>>> mock_foo = manager.foo\\n>>> mock_bar = manager.bar\\n\\n>>> mock_foo.something()\\n\\n>>> mock_bar.other.thing()\\n\\n\\n>>> manager.mock_calls\\n[call.foo.something(), call.bar.other.thing()]\\n\\nWe can then assert about the calls, including the order, by comparing with the mock_calls attribute on the manager mock:\\n\\n>>> expected_calls = [call.foo.something(), call.bar.other.thing()]\\n>>> manager.mock_calls == expected_calls\\nTrue\\n\\nIf patch is creating, and putting in place, your mocks then you can attach them to a manager mock using the attach_mock() method. After attaching calls will be recorded in mock_calls of the manager.\\n\\n>>> manager = MagicMock()\\n>>> with patch(\\'mymodule.Class1\\') as MockClass1:\\n... with patch(\\'mymodule.Class2\\') as MockClass2:\\n... manager.attach_mock(MockClass1, \\'MockClass1\\')\\n... manager.attach_mock(MockClass2, \\'MockClass2\\')\\n... MockClass1().foo()\\n... MockClass2().bar()\\n\\n\\n>>> manager.mock_calls\\n[call.MockClass1(),\\ncall.MockClass1().foo(),\\ncall.MockClass2(),\\ncall.MockClass2().bar()]\\n\\nIf many calls have been made, but you’re only interested in a particular sequence of them then an alternative is to use the assert_has_calls() method. This takes a list of calls (constructed with the call object). If that sequence of calls are in mock_calls then the assert succeeds.\\n\\n>>> m = MagicMock()\\n>>> m().foo().bar().baz()\\n\\n>>> m.one().two().three()\\n\\n>>> calls = call.one().two().three().call_list()\\n>>> m.assert_has_calls(calls)\\n\\nEven though the chained call m.one().two().three() aren’t the only calls that have been made to the mock, the assert still succeeds.\\n\\nSometimes a mock may have several calls made to it, and you are only interested in asserting about some of those calls. You may not even care about the order. In this case you can pass any_order=True to assert_has_calls:\\n\\n>>> m = MagicMock()\\n>>> m(1), m.two(2, 3), m.seven(7), m.fifty(\\'50\\')\\n(...)\\n>>> calls = [call.fifty(\\'50\\'), call(1), call.seven(7)]\\n>>> m.assert_has_calls(calls, any_order=True)\\n\\nMore complex argument matching¶\\n\\nUsing the same basic concept as ANY we can implement matchers to do more complex assertions on objects used as arguments to mocks.\\n\\nSuppose 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 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.\\n\\nYou can see in this example how a ‘standard’ call to assert_called_with isn’t sufficient:\\n\\n>>> class Foo:\\n... def __init__(self, a, b):\\n... self.a, self.b = a, b\\n...\\n>>> mock = Mock(return_value=None)\\n>>> mock(Foo(1, 2))\\n>>> mock.assert_called_with(Foo(1, 2))\\nTraceback (most recent call last):\\n ...\\nAssertionError: expected call not found.\\nExpected: mock(<__main__.Foo object at 0x...>)\\nActual: mock(<__main__.Foo object at 0x...>)\\n\\nA comparison function for our Foo class might look something like this:\\n\\n>>> def compare(self, other):\\n... if not type(self) == type(other):\\n... return False\\n... if self.a != other.a:\\n... return False\\n... if self.b != other.b:\\n... return False\\n... return True\\n...\\n\\nAnd a matcher object that can use comparison functions like this for its equality operation would look something like this:\\n\\n>>> class Matcher:\\n... def __init__(self, compare, some_obj):\\n... self.compare = compare\\n... self.some_obj = some_obj\\n... def __eq__(self, other):\\n... return self.compare(self.some_obj, other)\\n...\\n\\nPutting all this together:\\n\\n>>> match_foo = Matcher(compare, Foo(1, 2))\\n>>> mock.assert_called_with(match_foo)\\n\\nThe Matcher is instantiated with our compare function and the Foo object we want to compare against. In assert_called_with the Matcher equality method will be called, which compares the object the mock was called with against the one we created our matcher with. If they match then assert_called_with passes, and if they don’t an AssertionError is raised:\\n\\n>>> match_wrong = Matcher(compare, Foo(3, 4))\\n>>> mock.assert_called_with(match_wrong)\\nTraceback (most recent call last):\\n ...\\nAssertionError: Expected: ((,), {})\\nCalled with: ((,), {})\\n\\nWith a bit of tweaking you could have the comparison function raise the AssertionError directly and provide a more useful failure message.\\n\\nAs of version 1.5, the Python testing library PyHamcrest provides similar functionality, that may be useful here, in the form of its equality matcher (hamcrest.library.integration.match_equality).\\n\\nTable of Contents\\n\\nunittest.mock — getting started\\n\\nUsing Mock\\n\\nMock Patching Methods\\n\\nMock for Method Calls on an Object\\n\\nMocking Classes\\n\\nNaming your mocks\\n\\nTracking all Calls\\n\\nSetting Return Values and Attributes\\n\\nRaising exceptions with mocks\\n\\nSide effect functions and iterables\\n\\nMocking asynchronous iterators\\n\\nMocking asynchronous context manager\\n\\nCreating a Mock from an Existing Object\\n\\nUsing side_effect to return per file content\\n\\nPatch Decorators\\n\\nFurther Examples\\n\\nMocking chained calls\\n\\nPartial mocking\\n\\nMocking a Generator Method\\n\\nApplying the same patch to every test method\\n\\nMocking Unbound Methods\\n\\nChecking multiple calls with mock\\n\\nCoping with mutable arguments\\n\\nNesting Patches\\n\\nMocking a dictionary with MagicMock\\n\\nMock subclasses and their attributes\\n\\nMocking imports with patch.dict\\n\\nTracking order of calls and less verbose call assertions\\n\\nMore complex argument matching\\n\\nPrevious topic\\n\\nunittest.mock — mock object library\\n\\nNext topic\\n\\ntest — Regression tests package for Python\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nDevelopment Tools »\\n\\nunittest.mock — getting started\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\unittest.mock.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nDevelopment Tools »\\n\\nunittest.mock — mock object library\\n\\n|\\n\\nunittest.mock — mock object library¶\\n\\nAdded in version 3.3.\\n\\nSource code: Lib/unittest/mock.py\\n\\nunittest.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.\\n\\nunittest.mock provides a core 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.\\n\\nAdditionally, mock provides a patch() decorator that handles patching module and class level attributes within the scope of a test, along with sentinel for creating unique objects. See the quick guide for some examples of how to use Mock, MagicMock and patch().\\n\\nMock is designed for use with unittest and is based on the ‘action -> assertion’ pattern instead of ‘record -> replay’ used by many mocking frameworks.\\n\\nThere is a backport of unittest.mock for earlier versions of Python, available as mock on PyPI.\\n\\nQuick Guide¶\\n\\nMock and MagicMock objects create all attributes and methods as you access them and store details of how they have been used. You can configure them, to specify return values or limit what attributes are available, and then make assertions about how they have been used:\\n\\n>>> from unittest.mock import MagicMock\\n>>> thing = ProductionClass()\\n>>> thing.method = MagicMock(return_value=3)\\n>>> thing.method(3, 4, 5, key=\\'value\\')\\n3\\n>>> thing.method.assert_called_with(3, 4, 5, key=\\'value\\')\\n\\nside_effect allows you to perform side effects, including raising an exception when a mock is called:\\n\\n>>> from unittest.mock import Mock\\n>>> mock = Mock(side_effect=KeyError(\\'foo\\'))\\n>>> mock()\\nTraceback (most recent call last):\\n ...\\nKeyError: \\'foo\\'\\n\\n>>> values = {\\'a\\': 1, \\'b\\': 2, \\'c\\': 3}\\n>>> def side_effect(arg):\\n... return values[arg]\\n...\\n>>> mock.side_effect = side_effect\\n>>> mock(\\'a\\'), mock(\\'b\\'), mock(\\'c\\')\\n(1, 2, 3)\\n>>> mock.side_effect = [5, 4, 3, 2, 1]\\n>>> mock(), mock(), mock()\\n(5, 4, 3)\\n\\nMock has many other ways you can configure it and control its behaviour. For example the spec argument configures the mock to take its specification from another object. Attempting to access attributes or methods on the mock that don’t exist on the spec will fail with an AttributeError.\\n\\nThe patch() decorator / context manager makes it easy to mock classes or objects in a module under test. The object you specify will be replaced with a mock (or other object) during the test and restored when the test ends:\\n\\n>>> from unittest.mock import patch\\n>>> @patch(\\'module.ClassName2\\')\\n... @patch(\\'module.ClassName1\\')\\n... def test(MockClass1, MockClass2):\\n... module.ClassName1()\\n... module.ClassName2()\\n... assert MockClass1 is module.ClassName1\\n... assert MockClass2 is module.ClassName2\\n... assert MockClass1.called\\n... assert MockClass2.called\\n...\\n>>> test()\\n\\nNote\\n\\nWhen you nest patch decorators the mocks are passed in to the decorated function in the same order they applied (the normal Python order that decorators are applied). This means from the bottom up, so in the example above the mock for module.ClassName1 is passed in first.\\n\\nWith patch() it matters that you patch objects in the namespace where they are looked up. This is normally straightforward, but for a quick guide read where to patch.\\n\\nAs well as a decorator patch() can be used as a context manager in a with statement:\\n\\n>>> with patch.object(ProductionClass, \\'method\\', return_value=None) as mock_method:\\n... thing = ProductionClass()\\n... thing.method(1, 2, 3)\\n...\\n>>> mock_method.assert_called_once_with(1, 2, 3)\\n\\nThere is also patch.dict() for setting values in a dictionary just during a scope and restoring the dictionary to its original state when the test ends:\\n\\n>>> foo = {\\'key\\': \\'value\\'}\\n>>> original = foo.copy()\\n>>> with patch.dict(foo, {\\'newkey\\': \\'newvalue\\'}, clear=True):\\n... assert foo == {\\'newkey\\': \\'newvalue\\'}\\n...\\n>>> assert foo == original\\n\\nMock supports the mocking of Python magic methods. The easiest way of using magic methods is with the MagicMock class. It allows you to do things like:\\n\\n>>> mock = MagicMock()\\n>>> mock.__str__.return_value = \\'foobarbaz\\'\\n>>> str(mock)\\n\\'foobarbaz\\'\\n>>> mock.__str__.assert_called_with()\\n\\nMock allows you to assign functions (or other Mock instances) to magic methods and they will be called appropriately. The MagicMock class is just a Mock variant that has all of the magic methods pre-created for you (well, all the useful ones anyway).\\n\\nThe following is an example of using magic methods with the ordinary Mock class:\\n\\n>>> mock = Mock()\\n>>> mock.__str__ = Mock(return_value=\\'wheeeeee\\')\\n>>> str(mock)\\n\\'wheeeeee\\'\\n\\nFor ensuring that the mock objects in your tests have the same api as the objects they are replacing, you can use auto-speccing. Auto-speccing can be done through the autospec argument to patch, or the create_autospec() function. Auto-speccing creates mock objects that have the same attributes and methods as the objects they are replacing, and any functions and methods (including constructors) have the same call signature as the real object.\\n\\nThis ensures that your mocks will fail in the same way as your production code if they are used incorrectly:\\n\\n>>> from unittest.mock import create_autospec\\n>>> def function(a, b, c):\\n... pass\\n...\\n>>> mock_function = create_autospec(function, return_value=\\'fishy\\')\\n>>> mock_function(1, 2, 3)\\n\\'fishy\\'\\n>>> mock_function.assert_called_once_with(1, 2, 3)\\n>>> mock_function(\\'wrong arguments\\')\\nTraceback (most recent call last):\\n ...\\nTypeError: missing a required argument: \\'b\\'\\n\\ncreate_autospec() can also be used on classes, where it copies the signature of the __init__ method, and on callable objects where it copies the signature of the __call__ method.\\n\\nThe Mock Class¶\\n\\nMock is a flexible mock object intended to replace the use of stubs and test doubles throughout your code. Mocks are callable and create attributes as new mocks when you access them [1]. Accessing the same attribute will always return the same mock. Mocks record how you use them, allowing you to make assertions about what your code has done to them.\\n\\nMagicMock is a subclass of Mock with all the magic methods pre-created and ready to use. There are also non-callable variants, useful when you are mocking out objects that aren’t callable: NonCallableMock and NonCallableMagicMock\\n\\nThe patch() decorators makes it easy to temporarily replace classes in a particular module with a Mock object. By default patch() will create a MagicMock for you. You can specify an alternative class of Mock using the new_callable argument to patch().\\n\\nMock objects that use a class or an instance as a spec or spec_set are able to pass isinstance() tests:\\n\\n>>> mock = Mock(spec=SomeClass)\\n>>> isinstance(mock, SomeClass)\\nTrue\\n>>> mock = Mock(spec_set=SomeClass())\\n>>> isinstance(mock, SomeClass)\\nTrue\\n\\nThe Mock classes have support for mocking magic methods. See magic methods for the full details.\\n\\nThe mock classes and the patch() decorators all take arbitrary keyword arguments for configuration. For the patch() decorators the keywords are passed to the constructor of the mock being created. The keyword arguments are for configuring attributes of the mock:\\n\\n>>> m = MagicMock(attribute=3, other=\\'fish\\')\\n>>> m.attribute\\n3\\n>>> m.other\\n\\'fish\\'\\n\\nThe return value and side effect of child mocks can be set in the same way, using dotted notation. As you can’t use dotted names directly in a call you have to create a dictionary and unpack it using **:\\n\\n>>> attrs = {\\'method.return_value\\': 3, \\'other.side_effect\\': KeyError}\\n>>> mock = Mock(some_attribute=\\'eggs\\', **attrs)\\n>>> mock.some_attribute\\n\\'eggs\\'\\n>>> mock.method()\\n3\\n>>> mock.other()\\nTraceback (most recent call last):\\n ...\\nKeyError\\n\\nA callable mock which was created with a spec (or a spec_set) will introspect the specification object’s signature when matching calls to the mock. Therefore, it can match the actual call’s arguments regardless of whether they were passed positionally or by name:\\n\\n>>> def f(a, b, c): pass\\n...\\n>>> mock = Mock(spec=f)\\n>>> mock(1, 2, c=3)\\n\\n>>> mock.assert_called_with(1, 2, 3)\\n>>> mock.assert_called_with(a=1, b=2, c=3)\\n\\nThis applies to assert_called_with(), assert_called_once_with(), assert_has_calls() and assert_any_call(). When Autospeccing, it will also apply to method calls on the mock object.\\n\\nChanged in version 3.4: Added signature introspection on specced and autospecced mock objects.\\n\\nBecause of the way mock attributes are stored you can’t directly attach a PropertyMock to a mock object. Instead you can attach it to the mock type object:\\n\\n>>> m = MagicMock()\\n>>> p = PropertyMock(return_value=3)\\n>>> type(m).foo = p\\n>>> m.foo\\n3\\n>>> p.assert_called_once_with()\\n\\nCaution\\n\\nIf an AttributeError is raised by PropertyMock, it will be interpreted as a missing descriptor and __getattr__() will be called on the parent mock:\\n\\n>>> m = MagicMock()\\n>>> no_attribute = PropertyMock(side_effect=AttributeError)\\n>>> type(m).my_property = no_attribute\\n>>> m.my_property\\n\\n\\nSee __getattr__() for details.\\n\\nCalling¶\\n\\nMock objects are callable. The call will return the value set as the return_value attribute. The default return value is a new Mock object; it is created the first time the return value is accessed (either explicitly or by calling the Mock) - but it is stored and the same one returned each time.\\n\\nCalls made to the object will be recorded in the attributes like call_args and call_args_list.\\n\\nIf side_effect is set then it will be called after the call has been recorded, so if side_effect raises an exception the call is still recorded.\\n\\nThe simplest way to make a mock raise an exception when called is to make side_effect an exception class or instance:\\n\\n>>> m = MagicMock(side_effect=IndexError)\\n>>> m(1, 2, 3)\\nTraceback (most recent call last):\\n ...\\nIndexError\\n>>> m.mock_calls\\n[call(1, 2, 3)]\\n>>> m.side_effect = KeyError(\\'Bang!\\')\\n>>> m(\\'two\\', \\'three\\', \\'four\\')\\nTraceback (most recent call last):\\n ...\\nKeyError: \\'Bang!\\'\\n>>> m.mock_calls\\n[call(1, 2, 3), call(\\'two\\', \\'three\\', \\'four\\')]\\n\\nIf side_effect is a function then whatever that function returns is what calls to the mock return. The side_effect function is called with the same arguments as the mock. This allows you to vary the return value of the call dynamically, based on the input:\\n\\n>>> def side_effect(value):\\n... return value + 1\\n...\\n>>> m = MagicMock(side_effect=side_effect)\\n>>> m(1)\\n2\\n>>> m(2)\\n3\\n>>> m.mock_calls\\n[call(1), call(2)]\\n\\nIf 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 return_value from inside side_effect, or return DEFAULT:\\n\\n>>> m = MagicMock()\\n>>> def side_effect(*args, **kwargs):\\n... return m.return_value\\n...\\n>>> m.side_effect = side_effect\\n>>> m.return_value = 3\\n>>> m()\\n3\\n>>> def side_effect(*args, **kwargs):\\n... return DEFAULT\\n...\\n>>> m.side_effect = side_effect\\n>>> m()\\n3\\n\\nTo remove a side_effect, and return to the default behaviour, set the side_effect to None:\\n\\n>>> m = MagicMock(return_value=6)\\n>>> def side_effect(*args, **kwargs):\\n... return 3\\n...\\n>>> m.side_effect = side_effect\\n>>> m()\\n3\\n>>> m.side_effect = None\\n>>> m()\\n6\\n\\nThe 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 StopIteration is raised):\\n\\n>>> m = MagicMock(side_effect=[1, 2, 3])\\n>>> m()\\n1\\n>>> m()\\n2\\n>>> m()\\n3\\n>>> m()\\nTraceback (most recent call last):\\n ...\\nStopIteration\\n\\nIf any members of the iterable are exceptions they will be raised instead of returned:\\n\\n>>> iterable = (33, ValueError, 66)\\n>>> m = MagicMock(side_effect=iterable)\\n>>> m()\\n33\\n>>> m()\\nTraceback (most recent call last):\\n ...\\nValueError\\n>>> m()\\n66\\n\\nDeleting Attributes¶\\n\\nMock objects create attributes on demand. This allows them to pretend to be objects of any type.\\n\\nYou may want a mock object to return False to a hasattr() call, or raise an AttributeError when an attribute is fetched. You can do this by providing an object as a spec for a mock, but that isn’t always convenient.\\n\\nYou “block” attributes by deleting them. Once deleted, accessing an attribute will raise an AttributeError.\\n\\n>>> mock = MagicMock()\\n>>> hasattr(mock, \\'m\\')\\nTrue\\n>>> del mock.m\\n>>> hasattr(mock, \\'m\\')\\nFalse\\n>>> del mock.f\\n>>> mock.f\\nTraceback (most recent call last):\\n ...\\nAttributeError: f\\n\\nMock names and the name attribute¶\\n\\nSince “name” is an argument to the Mock constructor, if you want your mock object to have a “name” attribute you can’t just pass it in at creation time. There are two alternatives. One option is to use configure_mock():\\n\\n>>> mock = MagicMock()\\n>>> mock.configure_mock(name=\\'my_name\\')\\n>>> mock.name\\n\\'my_name\\'\\n\\nA simpler option is to simply set the “name” attribute after mock creation:\\n\\n>>> mock = MagicMock()\\n>>> mock.name = \"foo\"\\n\\nAttaching Mocks as Attributes¶\\n\\nWhen you attach a mock as an attribute of another mock (or as the return value) it becomes a “child” of that mock. Calls to the child are recorded in the method_calls and mock_calls attributes of the parent. This is useful for configuring child mocks and then attaching them to the parent, or for attaching mocks to a parent that records all calls to the children and allows you to make assertions about the order of calls between mocks:\\n\\n>>> parent = MagicMock()\\n>>> child1 = MagicMock(return_value=None)\\n>>> child2 = MagicMock(return_value=None)\\n>>> parent.child1 = child1\\n>>> parent.child2 = child2\\n>>> child1(1)\\n>>> child2(2)\\n>>> parent.mock_calls\\n[call.child1(1), call.child2(2)]\\n\\nThe exception to this is if the mock has a name. This allows you to prevent the “parenting” if for some reason you don’t want it to happen.\\n\\n>>> mock = MagicMock()\\n>>> not_a_child = MagicMock(name=\\'not-a-child\\')\\n>>> mock.attribute = not_a_child\\n>>> mock.attribute()\\n\\n>>> mock.mock_calls\\n[]\\n\\nMocks created for you by patch() are automatically given names. To attach mocks that have names to a parent you use the attach_mock() method:\\n\\n>>> thing1 = object()\\n>>> thing2 = object()\\n>>> parent = MagicMock()\\n>>> with patch(\\'__main__.thing1\\', return_value=None) as child1:\\n... with patch(\\'__main__.thing2\\', return_value=None) as child2:\\n... parent.attach_mock(child1, \\'child1\\')\\n... parent.attach_mock(child2, \\'child2\\')\\n... child1(\\'one\\')\\n... child2(\\'two\\')\\n...\\n>>> parent.mock_calls\\n[call.child1(\\'one\\'), call.child2(\\'two\\')]\\n\\n[1]\\n\\nThe only exceptions are magic methods and attributes (those that have leading and trailing double underscores). Mock doesn’t create these but instead raises an AttributeError. This is because the interpreter will often implicitly request these methods, and gets very confused to get a new Mock object when it expects a magic method. If you need magic method support see magic methods.\\n\\nThe patchers¶\\n\\nThe patch decorators are used for patching objects only within the scope of the function they decorate. They automatically handle the unpatching for you, even if exceptions are raised. All of these functions can also be used in with statements or as class decorators.\\n\\npatch¶\\n\\nNote\\n\\nThe key is to do the patching in the right namespace. See the section where to patch.\\n\\npatch() as function decorator, creating the mock for you and passing it into the decorated function:\\n\\n>>> @patch(\\'__main__.SomeClass\\')\\n... def function(normal_argument, mock_class):\\n... print(mock_class is SomeClass)\\n...\\n>>> function(None)\\nTrue\\n\\nPatching a class replaces the class with a MagicMock instance. If the class is instantiated in the code under test then it will be the return_value of the mock that will be used.\\n\\nIf the class is instantiated multiple times you could use side_effect to return a new mock each time. Alternatively you can set the return_value to be anything you want.\\n\\nTo configure return values on methods of instances on the patched class you must do this on the return_value. For example:\\n\\n>>> class Class:\\n... def method(self):\\n... pass\\n...\\n>>> with patch(\\'__main__.Class\\') as MockClass:\\n... instance = MockClass.return_value\\n... instance.method.return_value = \\'foo\\'\\n... assert Class() is instance\\n... assert Class().method() == \\'foo\\'\\n...\\n\\nIf you use spec or spec_set and patch() is replacing a class, then the return value of the created mock will have the same spec.\\n\\n>>> Original = Class\\n>>> patcher = patch(\\'__main__.Class\\', spec=True)\\n>>> MockClass = patcher.start()\\n>>> instance = MockClass()\\n>>> assert isinstance(instance, Original)\\n>>> patcher.stop()\\n\\nThe new_callable argument is useful where you want to use an alternative class to the default MagicMock for the created mock. For example, if you wanted a NonCallableMock to be used:\\n\\n>>> thing = object()\\n>>> with patch(\\'__main__.thing\\', new_callable=NonCallableMock) as mock_thing:\\n... assert thing is mock_thing\\n... thing()\\n...\\nTraceback (most recent call last):\\n ...\\nTypeError: \\'NonCallableMock\\' object is not callable\\n\\nAnother use case might be to replace an object with an io.StringIO instance:\\n\\n>>> from io import StringIO\\n>>> def foo():\\n... print(\\'Something\\')\\n...\\n>>> @patch(\\'sys.stdout\\', new_callable=StringIO)\\n... def test(mock_stdout):\\n... foo()\\n... assert mock_stdout.getvalue() == \\'Something\\\\n\\'\\n...\\n>>> test()\\n\\nWhen patch() is creating a mock for you, it is common that the first thing you need to do is to configure the mock. Some of that configuration can be done in the call to patch. Any arbitrary keywords you pass into the call will be used to set attributes on the created mock:\\n\\n>>> patcher = patch(\\'__main__.thing\\', first=\\'one\\', second=\\'two\\')\\n>>> mock_thing = patcher.start()\\n>>> mock_thing.first\\n\\'one\\'\\n>>> mock_thing.second\\n\\'two\\'\\n\\nAs well as attributes on the created mock attributes, like the return_value and side_effect, of child mocks can also be configured. These aren’t syntactically valid to pass in directly as keyword arguments, but a dictionary with these as keys can still be expanded into a patch() call using **:\\n\\n>>> config = {\\'method.return_value\\': 3, \\'other.side_effect\\': KeyError}\\n>>> patcher = patch(\\'__main__.thing\\', **config)\\n>>> mock_thing = patcher.start()\\n>>> mock_thing.method()\\n3\\n>>> mock_thing.other()\\nTraceback (most recent call last):\\n ...\\nKeyError\\n\\nBy 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 AttributeError:\\n\\n>>> @patch(\\'sys.non_existing_attribute\\', 42)\\n... def test():\\n... assert sys.non_existing_attribute == 42\\n...\\n>>> test()\\nTraceback (most recent call last):\\n ...\\nAttributeError: does not have the attribute \\'non_existing_attribute\\'\\n\\nbut adding create=True in the call to patch() will make the previous example work as expected:\\n\\n>>> @patch(\\'sys.non_existing_attribute\\', 42, create=True)\\n... def test(mock_stdout):\\n... assert sys.non_existing_attribute == 42\\n...\\n>>> test()\\n\\nChanged in version 3.8: patch() now returns an AsyncMock if the target is an async function.\\n\\npatch.object¶\\n\\nYou can either call patch.object() with three arguments or two arguments. The three argument form takes the object to be patched, the attribute name and the object to replace the attribute with.\\n\\nWhen calling with the two argument form you omit the replacement object, and a mock is created for you and passed in as an extra argument to the decorated function:\\n\\n>>> @patch.object(SomeClass, \\'class_method\\')\\n... def test(mock_method):\\n... SomeClass.class_method(3)\\n... mock_method.assert_called_with(3)\\n...\\n>>> test()\\n\\nspec, create and the other arguments to patch.object() have the same meaning as they do for patch().\\n\\npatch.dict¶\\n\\npatch.dict() can be used as a context manager, decorator or class decorator:\\n\\n>>> foo = {}\\n>>> @patch.dict(foo, {\\'newkey\\': \\'newvalue\\'})\\n... def test():\\n... assert foo == {\\'newkey\\': \\'newvalue\\'}\\n...\\n>>> test()\\n>>> assert foo == {}\\n\\nWhen used as a class decorator patch.dict() honours patch.TEST_PREFIX (default to \\'test\\') for choosing which methods to wrap:\\n\\n>>> import os\\n>>> import unittest\\n>>> from unittest.mock import patch\\n>>> @patch.dict(\\'os.environ\\', {\\'newkey\\': \\'newvalue\\'})\\n... class TestSample(unittest.TestCase):\\n... def test_sample(self):\\n... self.assertEqual(os.environ[\\'newkey\\'], \\'newvalue\\')\\n\\nIf you want to use a different prefix for your test, you can inform the patchers of the different prefix by setting patch.TEST_PREFIX. For more details about how to change the value of see TEST_PREFIX.\\n\\npatch.dict() can be used to add members to a dictionary, or simply let a test change a dictionary, and ensure the dictionary is restored when the test ends.\\n\\n>>> foo = {}\\n>>> with patch.dict(foo, {\\'newkey\\': \\'newvalue\\'}) as patched_foo:\\n... assert foo == {\\'newkey\\': \\'newvalue\\'}\\n... assert patched_foo == {\\'newkey\\': \\'newvalue\\'}\\n... # You can add, update or delete keys of foo (or patched_foo, it\\'s the same dict)\\n... patched_foo[\\'spam\\'] = \\'eggs\\'\\n...\\n>>> assert foo == {}\\n>>> assert patched_foo == {}\\n\\n>>> import os\\n>>> with patch.dict(\\'os.environ\\', {\\'newkey\\': \\'newvalue\\'}):\\n... print(os.environ[\\'newkey\\'])\\n...\\nnewvalue\\n>>> assert \\'newkey\\' not in os.environ\\n\\nKeywords can be used in the patch.dict() call to set values in the dictionary:\\n\\n>>> mymodule = MagicMock()\\n>>> mymodule.function.return_value = \\'fish\\'\\n>>> with patch.dict(\\'sys.modules\\', mymodule=mymodule):\\n... import mymodule\\n... mymodule.function(\\'some\\', \\'args\\')\\n...\\n\\'fish\\'\\n\\npatch.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 __getitem__(), __setitem__(), __delitem__() and either __iter__() or __contains__().\\n\\n>>> class Container:\\n... def __init__(self):\\n... self.values = {}\\n... def __getitem__(self, name):\\n... return self.values[name]\\n... def __setitem__(self, name, value):\\n... self.values[name] = value\\n... def __delitem__(self, name):\\n... del self.values[name]\\n... def __iter__(self):\\n... return iter(self.values)\\n...\\n>>> thing = Container()\\n>>> thing[\\'one\\'] = 1\\n>>> with patch.dict(thing, one=2, two=3):\\n... assert thing[\\'one\\'] == 2\\n... assert thing[\\'two\\'] == 3\\n...\\n>>> assert thing[\\'one\\'] == 1\\n>>> assert list(thing) == [\\'one\\']\\n\\npatch.multiple¶\\n\\nIf you want patch.multiple() to create mocks for you, then you can use DEFAULT as the value. If you use patch.multiple() as a decorator then the created mocks are passed into the decorated function by keyword.\\n\\n>>> thing = object()\\n>>> other = object()\\n\\n>>> @patch.multiple(\\'__main__\\', thing=DEFAULT, other=DEFAULT)\\n... def test_function(thing, other):\\n... assert isinstance(thing, MagicMock)\\n... assert isinstance(other, MagicMock)\\n...\\n>>> test_function()\\n\\npatch.multiple() can be nested with other patch decorators, but put arguments passed by keyword after any of the standard arguments created by patch():\\n\\n>>> @patch(\\'sys.exit\\')\\n... @patch.multiple(\\'__main__\\', thing=DEFAULT, other=DEFAULT)\\n... def test_function(mock_exit, other, thing):\\n... assert \\'other\\' in repr(other)\\n... assert \\'thing\\' in repr(thing)\\n... assert \\'exit\\' in repr(mock_exit)\\n...\\n>>> test_function()\\n\\nIf patch.multiple() is used as a context manager, the value returned by the context manager is a dictionary where created mocks are keyed by name:\\n\\n>>> with patch.multiple(\\'__main__\\', thing=DEFAULT, other=DEFAULT) as values:\\n... assert \\'other\\' in repr(values[\\'other\\'])\\n... assert \\'thing\\' in repr(values[\\'thing\\'])\\n... assert values[\\'thing\\'] is thing\\n... assert values[\\'other\\'] is other\\n...\\n\\npatch methods: start and stop¶\\n\\nAll the patchers have start() and stop() methods. These make it simpler to do patching in setUp methods or where you want to do multiple patches without nesting decorators or with statements.\\n\\nTo use them call patch(), patch.object() or patch.dict() as normal and keep a reference to the returned patcher object. You can then call start() to put the patch in place and stop() to undo it.\\n\\nIf you are using patch() to create a mock for you then it will be returned by the call to patcher.start.\\n\\n>>> patcher = patch(\\'package.module.ClassName\\')\\n>>> from package import module\\n>>> original = module.ClassName\\n>>> new_mock = patcher.start()\\n>>> assert module.ClassName is not original\\n>>> assert module.ClassName is new_mock\\n>>> patcher.stop()\\n>>> assert module.ClassName is original\\n>>> assert module.ClassName is not new_mock\\n\\nA typical use case for this might be for doing multiple patches in the setUp method of a TestCase:\\n\\n>>> class MyTest(unittest.TestCase):\\n... def setUp(self):\\n... self.patcher1 = patch(\\'package.module.Class1\\')\\n... self.patcher2 = patch(\\'package.module.Class2\\')\\n... self.MockClass1 = self.patcher1.start()\\n... self.MockClass2 = self.patcher2.start()\\n...\\n... def tearDown(self):\\n... self.patcher1.stop()\\n... self.patcher2.stop()\\n...\\n... def test_something(self):\\n... assert package.module.Class1 is self.MockClass1\\n... assert package.module.Class2 is self.MockClass2\\n...\\n>>> MyTest(\\'test_something\\').run()\\n\\nCaution\\n\\nIf you use this technique you must ensure that the patching is “undone” by calling stop. This can be fiddlier than you might think, because if an exception is raised in the setUp then tearDown is not called. unittest.TestCase.addCleanup() makes this easier:\\n\\n>>> class MyTest(unittest.TestCase):\\n... def setUp(self):\\n... patcher = patch(\\'package.module.Class\\')\\n... self.MockClass = patcher.start()\\n... self.addCleanup(patcher.stop)\\n...\\n... def test_something(self):\\n... assert package.module.Class is self.MockClass\\n...\\n\\nAs an added bonus you no longer need to keep a reference to the patcher object.\\n\\nIt is also possible to stop all patches which have been started by using patch.stopall().\\n\\npatch builtins¶\\n\\nYou can patch any builtins within a module. The following example patches builtin ord():\\n\\n>>> @patch(\\'__main__.ord\\')\\n... def test(mock_ord):\\n... mock_ord.return_value = 101\\n... print(ord(\\'c\\'))\\n...\\n>>> test()\\n101\\n\\nTEST_PREFIX¶\\n\\nAll of the patchers can be used as class decorators. When used in this way they wrap every test method on the class. The patchers recognise methods that start with \\'test\\' as being test methods. This is the same way that the unittest.TestLoader finds test methods by default.\\n\\nIt is possible that you want to use a different prefix for your tests. You can inform the patchers of the different prefix by setting patch.TEST_PREFIX:\\n\\n>>> patch.TEST_PREFIX = \\'foo\\'\\n>>> value = 3\\n>>>\\n>>> @patch(\\'__main__.value\\', \\'not three\\')\\n... class Thing:\\n... def foo_one(self):\\n... print(value)\\n... def foo_two(self):\\n... print(value)\\n...\\n>>>\\n>>> Thing().foo_one()\\nnot three\\n>>> Thing().foo_two()\\nnot three\\n>>> value\\n3\\n\\nNesting Patch Decorators¶\\n\\nIf you want to perform multiple patches then you can simply stack up the decorators.\\n\\nYou can stack up multiple patch decorators using this pattern:\\n\\n>>> @patch.object(SomeClass, \\'class_method\\')\\n... @patch.object(SomeClass, \\'static_method\\')\\n... def test(mock1, mock2):\\n... assert SomeClass.static_method is mock1\\n... assert SomeClass.class_method is mock2\\n... SomeClass.static_method(\\'foo\\')\\n... SomeClass.class_method(\\'bar\\')\\n... return mock1, mock2\\n...\\n>>> mock1, mock2 = test()\\n>>> mock1.assert_called_once_with(\\'foo\\')\\n>>> mock2.assert_called_once_with(\\'bar\\')\\n\\nNote that the decorators are applied from the bottom upwards. This is the standard way that Python applies decorators. The order of the created mocks passed into your test function matches this order.\\n\\nWhere to patch¶\\n\\npatch() works by (temporarily) changing the object that a name points to with another one. There can be many names pointing to any individual object, so for patching to work you must ensure that you patch the name used by the system under test.\\n\\nThe basic principle is that you patch where an object is looked up, which is not necessarily the same place as where it is defined. A couple of examples will help to clarify this.\\n\\nImagine we have a project that we want to test with the following structure:\\n\\na.py\\n -> Defines SomeClass\\n\\nb.py\\n -> from a import SomeClass\\n -> some_function instantiates SomeClass\\n\\nNow we want to test some_function but we want to mock out SomeClass using patch(). The problem is that when we import module b, which we will have to do when it imports SomeClass from module a. If we use patch() to mock out a.SomeClass then it will have no effect on our test; module b already has a reference to the real SomeClass and it looks like our patching had no effect.\\n\\nThe key is to patch out SomeClass where it is used (or where it is looked up). In this case some_function will actually look up SomeClass in module b, where we have imported it. The patching should look like:\\n\\n@patch(\\'b.SomeClass\\')\\n\\nHowever, consider the alternative scenario where instead of from a import SomeClass module b does import a and some_function uses a.SomeClass. Both of these import forms are common. In this case the class we want to patch is being looked up in the module and so we have to patch a.SomeClass instead:\\n\\n@patch(\\'a.SomeClass\\')\\n\\nPatching Descriptors and Proxy Objects¶\\n\\nBoth patch and patch.object correctly patch and restore descriptors: class methods, static methods and properties. You should patch these on the class rather than an instance. They also work with some objects that proxy attribute access, like the django settings object.\\n\\nMagicMock and magic method support¶\\n\\nMocking Magic Methods¶\\n\\nMock supports mocking the Python protocol methods, also known as “magic methods”. This allows mock objects to replace containers or other objects that implement Python protocols.\\n\\nBecause magic methods are looked up differently from normal methods [2], this support has been specially implemented. This means that only specific magic methods are supported. The supported list includes almost all of them. If there are any missing that you need please let us know.\\n\\nYou mock magic methods by setting the method you are interested in to a function or a mock instance. If you are using a function then it must take self as the first argument [3].\\n\\n>>> def __str__(self):\\n... return \\'fooble\\'\\n...\\n>>> mock = Mock()\\n>>> mock.__str__ = __str__\\n>>> str(mock)\\n\\'fooble\\'\\n\\n>>> mock = Mock()\\n>>> mock.__str__ = Mock()\\n>>> mock.__str__.return_value = \\'fooble\\'\\n>>> str(mock)\\n\\'fooble\\'\\n\\n>>> mock = Mock()\\n>>> mock.__iter__ = Mock(return_value=iter([]))\\n>>> list(mock)\\n[]\\n\\nOne use case for this is for mocking objects used as context managers in a with statement:\\n\\n>>> mock = Mock()\\n>>> mock.__enter__ = Mock(return_value=\\'foo\\')\\n>>> mock.__exit__ = Mock(return_value=False)\\n>>> with mock as m:\\n... assert m == \\'foo\\'\\n...\\n>>> mock.__enter__.assert_called_with()\\n>>> mock.__exit__.assert_called_with(None, None, None)\\n\\nCalls to magic methods do not appear in method_calls, but they are recorded in mock_calls.\\n\\nNote\\n\\nIf you use the spec keyword argument to create a mock then attempting to set a magic method that isn’t in the spec will raise an AttributeError.\\n\\nThe full list of supported magic methods is:\\n\\n__hash__, __sizeof__, __repr__ and __str__\\n\\n__dir__, __format__ and __subclasses__\\n\\n__round__, __floor__, __trunc__ and __ceil__\\n\\nComparisons: __lt__, __gt__, __le__, __ge__, __eq__ and __ne__\\n\\nContainer methods: __getitem__, __setitem__, __delitem__, __contains__, __len__, __iter__, __reversed__ and __missing__\\n\\nContext manager: __enter__, __exit__, __aenter__ and __aexit__\\n\\nUnary numeric methods: __neg__, __pos__ and __invert__\\n\\nThe numeric methods (including right hand and in-place variants): __add__, __sub__, __mul__, __matmul__, __truediv__, __floordiv__, __mod__, __divmod__, __lshift__, __rshift__, __and__, __xor__, __or__, and __pow__\\n\\nNumeric conversion methods: __complex__, __int__, __float__ and __index__\\n\\nDescriptor methods: __get__, __set__ and __delete__\\n\\nPickling: __reduce__, __reduce_ex__, __getinitargs__, __getnewargs__, __getstate__ and __setstate__\\n\\nFile system path representation: __fspath__\\n\\nAsynchronous iteration methods: __aiter__ and __anext__\\n\\nChanged in version 3.8: Added support for os.PathLike.__fspath__().\\n\\nChanged in version 3.8: Added support for __aenter__, __aexit__, __aiter__ and __anext__.\\n\\nThe following methods exist but are not supported as they are either in use by mock, can’t be set dynamically, or can cause problems:\\n\\n__getattr__, __setattr__, __init__ and __new__\\n\\n__prepare__, __instancecheck__, __subclasscheck__, __del__\\n\\nMagic Mock¶\\n\\nThere are two MagicMock variants: MagicMock and NonCallableMagicMock.\\n\\nThe magic methods are setup with MagicMock objects, so you can configure them and use them in the usual way:\\n\\n>>> mock = MagicMock()\\n>>> mock[3] = \\'fish\\'\\n>>> mock.__setitem__.assert_called_with(3, \\'fish\\')\\n>>> mock.__getitem__.return_value = \\'result\\'\\n>>> mock[2]\\n\\'result\\'\\n\\nBy default many of the protocol methods are required to return objects of a specific type. These methods are preconfigured with a default return value, so that they can be used without you having to do anything if you aren’t interested in the return value. You can still set the return value manually if you want to change the default.\\n\\nMethods and their defaults:\\n\\n__lt__: NotImplemented\\n\\n__gt__: NotImplemented\\n\\n__le__: NotImplemented\\n\\n__ge__: NotImplemented\\n\\n__int__: 1\\n\\n__contains__: False\\n\\n__len__: 0\\n\\n__iter__: iter([])\\n\\n__exit__: False\\n\\n__aexit__: False\\n\\n__complex__: 1j\\n\\n__float__: 1.0\\n\\n__bool__: True\\n\\n__index__: 1\\n\\n__hash__: default hash for the mock\\n\\n__str__: default str for the mock\\n\\n__sizeof__: default sizeof for the mock\\n\\nFor example:\\n\\n>>> mock = MagicMock()\\n>>> int(mock)\\n1\\n>>> len(mock)\\n0\\n>>> list(mock)\\n[]\\n>>> object() in mock\\nFalse\\n\\nThe two equality methods, __eq__() and __ne__(), are special. They do the default equality comparison on identity, using the side_effect attribute, unless you change their return value to return something else:\\n\\n>>> MagicMock() == 3\\nFalse\\n>>> MagicMock() != 3\\nTrue\\n>>> mock = MagicMock()\\n>>> mock.__eq__.return_value = True\\n>>> mock == 3\\nTrue\\n\\nThe return value of MagicMock.__iter__() can be any iterable object and isn’t required to be an iterator:\\n\\n>>> mock = MagicMock()\\n>>> mock.__iter__.return_value = [\\'a\\', \\'b\\', \\'c\\']\\n>>> list(mock)\\n[\\'a\\', \\'b\\', \\'c\\']\\n>>> list(mock)\\n[\\'a\\', \\'b\\', \\'c\\']\\n\\nIf the return value is an iterator, then iterating over it once will consume it and subsequent iterations will result in an empty list:\\n\\n>>> mock.__iter__.return_value = iter([\\'a\\', \\'b\\', \\'c\\'])\\n>>> list(mock)\\n[\\'a\\', \\'b\\', \\'c\\']\\n>>> list(mock)\\n[]\\n\\nMagicMock has all of the supported magic methods configured except for some of the obscure and obsolete ones. You can still set these up if you want.\\n\\nMagic methods that are supported but not setup by default in MagicMock are:\\n\\n__subclasses__\\n\\n__dir__\\n\\n__format__\\n\\n__get__, __set__ and __delete__\\n\\n__reversed__ and __missing__\\n\\n__reduce__, __reduce_ex__, __getinitargs__, __getnewargs__, __getstate__ and __setstate__\\n\\n__getformat__\\n\\n[2]\\n\\nMagic methods should be looked up on the class rather than the instance. Different versions of Python are inconsistent about applying this rule. The supported protocol methods should work with all supported versions of Python.\\n\\n[3]\\n\\nThe function is basically hooked up to the class, but each Mock instance is kept isolated from the others.\\n\\nHelpers¶\\n\\nsentinel¶\\n\\nSometimes when testing you need to test that a specific object is passed as an argument to another method, or returned. It can be common to create named sentinel objects to test this. sentinel provides a convenient way of creating and testing the identity of objects like this.\\n\\nIn this example we monkey patch method to return sentinel.some_object:\\n\\n>>> real = ProductionClass()\\n>>> real.method = Mock(name=\"method\")\\n>>> real.method.return_value = sentinel.some_object\\n>>> result = real.method()\\n>>> assert result is sentinel.some_object\\n>>> result\\nsentinel.some_object\\n\\nDEFAULT¶\\n\\ncall¶\\n\\ncall_list is particularly useful for making assertions on “chained calls”. A chained call is multiple calls on a single line of code. This results in multiple entries in mock_calls on a mock. Manually constructing the sequence of calls can be tedious.\\n\\ncall_list() can construct the sequence of calls from the same chained call:\\n\\n>>> m = MagicMock()\\n>>> m(1).method(arg=\\'foo\\').other(\\'bar\\')(2.0)\\n\\n>>> kall = call(1).method(arg=\\'foo\\').other(\\'bar\\')(2.0)\\n>>> kall.call_list()\\n[call(1),\\n call().method(arg=\\'foo\\'),\\n call().method().other(\\'bar\\'),\\n call().method().other()(2.0)]\\n>>> m.mock_calls == kall.call_list()\\nTrue\\n\\nA call object is either a tuple of (positional args, keyword args) or (name, positional args, keyword args) depending on how it was constructed. When you construct them yourself this isn’t particularly interesting, but the call objects that are in the Mock.call_args, Mock.call_args_list and Mock.mock_calls attributes can be introspected to get at the individual arguments they contain.\\n\\nThe call objects in Mock.call_args and Mock.call_args_list are two-tuples of (positional args, keyword args) whereas the call objects in Mock.mock_calls, along with ones you construct yourself, are three-tuples of (name, positional args, keyword args).\\n\\nYou can use their “tupleness” to pull out the individual arguments for more complex introspection and assertions. The positional arguments are a tuple (an empty tuple if there are no positional arguments) and the keyword arguments are a dictionary:\\n\\n>>> m = MagicMock(return_value=None)\\n>>> m(1, 2, 3, arg=\\'one\\', arg2=\\'two\\')\\n>>> kall = m.call_args\\n>>> kall.args\\n(1, 2, 3)\\n>>> kall.kwargs\\n{\\'arg\\': \\'one\\', \\'arg2\\': \\'two\\'}\\n>>> kall.args is kall[0]\\nTrue\\n>>> kall.kwargs is kall[1]\\nTrue\\n\\n>>> m = MagicMock()\\n>>> m.foo(4, 5, 6, arg=\\'two\\', arg2=\\'three\\')\\n\\n>>> kall = m.mock_calls[0]\\n>>> name, args, kwargs = kall\\n>>> name\\n\\'foo\\'\\n>>> args\\n(4, 5, 6)\\n>>> kwargs\\n{\\'arg\\': \\'two\\', \\'arg2\\': \\'three\\'}\\n>>> name is m.mock_calls[0][0]\\nTrue\\n\\ncreate_autospec¶\\n\\nSee Autospeccing for examples of how to use auto-speccing with create_autospec() and the autospec argument to patch().\\n\\nChanged in version 3.8: create_autospec() now returns an AsyncMock if the target is an async function.\\n\\nANY¶\\n\\nSometimes you may need to make assertions about some of the arguments in a call to mock, but either not care about some of the arguments or want to pull them individually out of call_args and make more complex assertions on them.\\n\\nTo ignore certain arguments you can pass in objects that compare equal to everything. Calls to assert_called_with() and assert_called_once_with() will then succeed no matter what was passed in.\\n\\n>>> mock = Mock(return_value=None)\\n>>> mock(\\'foo\\', bar=object())\\n>>> mock.assert_called_once_with(\\'foo\\', bar=ANY)\\n\\nANY can also be used in comparisons with call lists like mock_calls:\\n\\n>>> m = MagicMock(return_value=None)\\n>>> m(1)\\n>>> m(1, 2)\\n>>> m(object())\\n>>> m.mock_calls == [call(1), call(1, 2), ANY]\\nTrue\\n\\nANY is not limited to comparisons with call objects and so can also be used in test assertions:\\n\\nclass TestStringMethods(unittest.TestCase):\\n\\n def test_split(self):\\n s = \\'hello world\\'\\n self.assertEqual(s.split(), [\\'hello\\', ANY])\\n\\nFILTER_DIR¶\\n\\nFILTER_DIR is a module level variable that controls the way mock objects respond to dir(). The default is True, which uses the filtering described below, to only show useful members. If you dislike this filtering, or need to switch it off for diagnostic purposes, then set mock.FILTER_DIR = False.\\n\\nWith filtering on, dir(some_mock) shows only useful attributes and will include any dynamically created attributes that wouldn’t normally be shown. If the mock was created with a spec (or autospec of course) then all the attributes from the original are shown, even if they haven’t been accessed yet:\\n\\n>>> dir(Mock())\\n[\\'assert_any_call\\',\\n \\'assert_called\\',\\n \\'assert_called_once\\',\\n \\'assert_called_once_with\\',\\n \\'assert_called_with\\',\\n \\'assert_has_calls\\',\\n \\'assert_not_called\\',\\n \\'attach_mock\\',\\n ...\\n>>> from urllib import request\\n>>> dir(Mock(spec=request))\\n[\\'AbstractBasicAuthHandler\\',\\n \\'AbstractDigestAuthHandler\\',\\n \\'AbstractHTTPHandler\\',\\n \\'BaseHandler\\',\\n ...\\n\\nMany of the not-very-useful (private to Mock rather than the thing being mocked) underscore and double underscore prefixed attributes have been filtered from the result of calling dir() on a Mock. If you dislike this behaviour you can switch it off by setting the module level switch FILTER_DIR:\\n\\n>>> from unittest import mock\\n>>> mock.FILTER_DIR = False\\n>>> dir(mock.Mock())\\n[\\'_NonCallableMock__get_return_value\\',\\n \\'_NonCallableMock__get_side_effect\\',\\n \\'_NonCallableMock__return_value_doc\\',\\n \\'_NonCallableMock__set_return_value\\',\\n \\'_NonCallableMock__set_side_effect\\',\\n \\'__call__\\',\\n \\'__class__\\',\\n ...\\n\\nAlternatively you can just use vars(my_mock) (instance members) and dir(type(my_mock)) (type members) to bypass the filtering irrespective of FILTER_DIR.\\n\\nmock_open¶\\n\\nUsing open() as a context manager is a great way to ensure your file handles are closed properly and is becoming common:\\n\\nwith open(\\'/some/path\\', \\'w\\') as f:\\n f.write(\\'something\\')\\n\\nThe issue is that even if you mock out the call to open() it is the returned object that is used as a context manager (and has __enter__() and __exit__() called).\\n\\nMocking context managers with a MagicMock is common enough and fiddly enough that a helper function is useful.\\n\\n>>> m = mock_open()\\n>>> with patch(\\'__main__.open\\', m):\\n... with open(\\'foo\\', \\'w\\') as h:\\n... h.write(\\'some stuff\\')\\n...\\n>>> m.mock_calls\\n[call(\\'foo\\', \\'w\\'),\\n call().__enter__(),\\n call().write(\\'some stuff\\'),\\n call().__exit__(None, None, None)]\\n>>> m.assert_called_once_with(\\'foo\\', \\'w\\')\\n>>> handle = m()\\n>>> handle.write.assert_called_once_with(\\'some stuff\\')\\n\\nAnd for reading files:\\n\\n>>> with patch(\\'__main__.open\\', mock_open(read_data=\\'bibble\\')) as m:\\n... with open(\\'foo\\') as h:\\n... result = h.read()\\n...\\n>>> m.assert_called_once_with(\\'foo\\')\\n>>> assert result == \\'bibble\\'\\n\\nAutospeccing¶\\n\\nAutospeccing is based on the existing spec feature of mock. It limits the api of mocks to the api of an original object (the spec), but it is recursive (implemented lazily) so that attributes of mocks only have the same api as the attributes of the spec. In addition mocked functions / methods have the same call signature as the original so they raise a TypeError if they are called incorrectly.\\n\\nBefore I explain how auto-speccing works, here’s why it is needed.\\n\\nMock 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.\\n\\nChanged in version 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 unsafe=True to Mock.\\n\\nNote that this is another reason why you need integration tests as well as unit tests. Testing everything in isolation is all fine and dandy, but if you don’t test how your units are “wired together” there is still lots of room for bugs that tests might have caught.\\n\\nunittest.mock already provides a feature to help with this, called speccing. If you use a class or instance as the spec for a mock then you can only access attributes on the mock that exist on the real class:\\n\\n>>> from urllib import request\\n>>> mock = Mock(spec=request.Request)\\n>>> mock.assret_called_with # Intentional typo!\\nTraceback (most recent call last):\\n ...\\nAttributeError: Mock object has no attribute \\'assret_called_with\\'\\n\\nThe spec only applies to the mock itself, so we still have the same issue with any methods on the mock:\\n\\n>>> mock.header_items()\\n\\n>>> mock.header_items.assret_called_with() # Intentional typo!\\n\\nAuto-speccing solves this problem. You can either pass autospec=True to patch() / patch.object() or use the create_autospec() function to create a mock with a spec. If you use the autospec=True argument to patch() then the object that is being replaced will be used as the spec object. Because the speccing is done “lazily” (the spec is created as attributes on the mock are accessed) you can use it with very complex or deeply nested objects (like modules that import modules that import modules) without a big performance hit.\\n\\nHere’s an example of it in use:\\n\\n>>> from urllib import request\\n>>> patcher = patch(\\'__main__.request\\', autospec=True)\\n>>> mock_request = patcher.start()\\n>>> request is mock_request\\nTrue\\n>>> mock_request.Request\\n\\n\\nYou can see that request.Request has a spec. request.Request takes two arguments in the constructor (one of which is self). Here’s what happens if we try to call it incorrectly:\\n\\n>>> req = request.Request()\\nTraceback (most recent call last):\\n ...\\nTypeError: () takes at least 2 arguments (1 given)\\n\\nThe spec also applies to instantiated classes (i.e. the return value of specced mocks):\\n\\n>>> req = request.Request(\\'foo\\')\\n>>> req\\n\\n\\nRequest objects are not callable, so the return value of instantiating our mocked out request.Request is a non-callable mock. With the spec in place any typos in our asserts will raise the correct error:\\n\\n>>> req.add_header(\\'spam\\', \\'eggs\\')\\n\\n>>> req.add_header.assret_called_with # Intentional typo!\\nTraceback (most recent call last):\\n ...\\nAttributeError: Mock object has no attribute \\'assret_called_with\\'\\n>>> req.add_header.assert_called_with(\\'spam\\', \\'eggs\\')\\n\\nIn many cases you will just be able to add autospec=True to your existing patch() calls and then be protected against bugs due to typos and api changes.\\n\\nAs well as using autospec through patch() there is a create_autospec() for creating autospecced mocks directly:\\n\\n>>> from urllib import request\\n>>> mock_request = create_autospec(request)\\n>>> mock_request.Request(\\'foo\\', \\'bar\\')\\n\\n\\nThis isn’t without caveats and limitations however, which is why it is not the default behaviour. In order to know what attributes are available on the spec object, autospec has to introspect (access attributes) the spec. As you traverse attributes on the mock a corresponding traversal of the original object is happening under the hood. If any of your specced objects have properties or descriptors that can trigger code execution then you may not be able to use autospec. On the other hand it is much better to design your objects so that introspection is safe [4].\\n\\nA more serious problem is that it is common for instance attributes to be created in the __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.\\n\\n>>> class Something:\\n... def __init__(self):\\n... self.a = 33\\n...\\n>>> with patch(\\'__main__.Something\\', autospec=True):\\n... thing = Something()\\n... thing.a\\n...\\nTraceback (most recent call last):\\n ...\\nAttributeError: Mock object has no attribute \\'a\\'\\n\\nThere are a few different ways of resolving this problem. The easiest, but not necessarily the least annoying, way is to simply set the required attributes on the mock after creation. Just because autospec doesn’t allow you to fetch attributes that don’t exist on the spec it doesn’t prevent you setting them:\\n\\n>>> with patch(\\'__main__.Something\\', autospec=True):\\n... thing = Something()\\n... thing.a = 33\\n...\\n\\nThere is a more aggressive version of both spec and autospec that does prevent you setting non-existent attributes. This is useful if you want to ensure your code only sets valid attributes too, but obviously it prevents this particular scenario:\\n\\n>>> with patch(\\'__main__.Something\\', autospec=True, spec_set=True):\\n... thing = Something()\\n... thing.a = 33\\n...\\nTraceback (most recent call last):\\n ...\\nAttributeError: Mock object has no attribute \\'a\\'\\n\\nProbably the best way of solving the problem is to add class attributes as default values for instance members initialised in __init__(). Note that if you are only setting default attributes in __init__() then providing them via class attributes (shared between instances of course) is faster too. e.g.\\n\\nclass Something:\\n a = 33\\n\\nThis brings up another issue. It is relatively common to provide a default value of None for members that will later be an object of a different type. None would be useless as a spec because it wouldn’t let you access any attributes or methods on it. As None is never going to be useful as a spec, and probably indicates a member that will normally of some other type, autospec doesn’t use a spec for members that are set to None. These will just be ordinary mocks (well - MagicMocks):\\n\\n>>> class Something:\\n... member = None\\n...\\n>>> mock = create_autospec(Something)\\n>>> mock.member.foo.bar.baz()\\n\\n\\nIf modifying your production classes to add defaults isn’t to your liking then there are more options. One of these is simply to use an instance as the spec rather than the class. The other is to create a subclass of the production class and add the defaults to the subclass without affecting the production class. Both of these require you to use an alternative object as the spec. Thankfully patch() supports this - you can simply pass the alternative object as the autospec argument:\\n\\n>>> class Something:\\n... def __init__(self):\\n... self.a = 33\\n...\\n>>> class SomethingForTest(Something):\\n... a = 33\\n...\\n>>> p = patch(\\'__main__.Something\\', autospec=SomethingForTest)\\n>>> mock = p.start()\\n>>> mock.a\\n\\n\\n[4]\\n\\nThis only applies to classes or already instantiated objects. Calling a mocked class to create a mock instance does not create a real instance. It is only attribute lookups - along with calls to dir() - that are done.\\n\\nSealing mocks¶\\n\\nOrder of precedence of side_effect, return_value and wraps¶\\n\\nThe order of their precedence is:\\n\\nside_effect\\n\\nreturn_value\\n\\nwraps\\n\\nIf all three are set, mock will return the value from side_effect, ignoring 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.\\n\\n>>> from unittest.mock import Mock\\n>>> class Order:\\n... @staticmethod\\n... def get_value():\\n... return \"third\"\\n...\\n>>> order_mock = Mock(spec=Order, wraps=Order)\\n>>> order_mock.get_value.side_effect = [\"first\"]\\n>>> order_mock.get_value.return_value = \"second\"\\n>>> order_mock.get_value()\\n\\'first\\'\\n\\nAs None is the default value of side_effect, if you reassign its value back to None, the order of precedence will be checked between return_value and the wrapped object, ignoring side_effect.\\n\\n>>> order_mock.get_value.side_effect = None\\n>>> order_mock.get_value()\\n\\'second\\'\\n\\nIf the value being returned by side_effect is DEFAULT, it is ignored and the order of precedence moves to the successor to obtain the value to return.\\n\\n>>> from unittest.mock import DEFAULT\\n>>> order_mock.get_value.side_effect = [DEFAULT]\\n>>> order_mock.get_value()\\n\\'second\\'\\n\\nWhen Mock wraps an object, the default value of return_value will be DEFAULT.\\n\\n>>> order_mock = Mock(spec=Order, wraps=Order)\\n>>> order_mock.return_value\\nsentinel.DEFAULT\\n>>> order_mock.get_value.return_value\\nsentinel.DEFAULT\\n\\nThe order of precedence will ignore this value and it will move to the last successor which is the wrapped object.\\n\\nAs 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.\\n\\n>>> order_mock_instance = order_mock()\\n>>> isinstance(order_mock_instance, Order)\\nTrue\\n>>> order_mock_instance.get_value()\\n\\'third\\'\\n\\n>>> order_mock.get_value.return_value = DEFAULT\\n>>> order_mock.get_value()\\n\\'third\\'\\n\\n>>> order_mock.get_value.return_value = \"second\"\\n>>> order_mock.get_value()\\n\\'second\\'\\n\\nBut if you assign 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.\\n\\n>>> order_mock.get_value.return_value = None\\n>>> order_mock.get_value() is None\\nTrue\\n\\nEven if you set all three at once when initializing the mock, the order of precedence remains the same:\\n\\n>>> order_mock = Mock(spec=Order, wraps=Order,\\n... **{\"get_value.side_effect\": [\"first\"],\\n... \"get_value.return_value\": \"second\"}\\n... )\\n...\\n>>> order_mock.get_value()\\n\\'first\\'\\n>>> order_mock.get_value.side_effect = None\\n>>> order_mock.get_value()\\n\\'second\\'\\n>>> order_mock.get_value.return_value = DEFAULT\\n>>> order_mock.get_value()\\n\\'third\\'\\n\\nIf side_effect is exhausted, the order of precedence will not cause a value to be obtained from the successors. Instead, StopIteration exception is raised.\\n\\n>>> order_mock = Mock(spec=Order, wraps=Order)\\n>>> order_mock.get_value.side_effect = [\"first side effect value\",\\n... \"another side effect value\"]\\n>>> order_mock.get_value.return_value = \"second\"\\n\\n>>> order_mock.get_value()\\n\\'first side effect value\\'\\n>>> order_mock.get_value()\\n\\'another side effect value\\'\\n\\n>>> order_mock.get_value()\\nTraceback (most recent call last):\\n ...\\nStopIteration\\n\\nTable of Contents\\n\\nunittest.mock — mock object library\\n\\nQuick Guide\\n\\nThe Mock Class\\n\\nCalling\\n\\nDeleting Attributes\\n\\nMock names and the name attribute\\n\\nAttaching Mocks as Attributes\\n\\nThe patchers\\n\\npatch\\n\\npatch.object\\n\\npatch.dict\\n\\npatch.multiple\\n\\npatch methods: start and stop\\n\\npatch builtins\\n\\nTEST_PREFIX\\n\\nNesting Patch Decorators\\n\\nWhere to patch\\n\\nPatching Descriptors and Proxy Objects\\n\\nMagicMock and magic method support\\n\\nMocking Magic Methods\\n\\nMagic Mock\\n\\nHelpers\\n\\nsentinel\\n\\nDEFAULT\\n\\ncall\\n\\ncreate_autospec\\n\\nANY\\n\\nFILTER_DIR\\n\\nmock_open\\n\\nAutospeccing\\n\\nSealing mocks\\n\\nOrder of precedence of side_effect, return_value and wraps\\n\\nPrevious topic\\n\\nunittest — Unit testing framework\\n\\nNext topic\\n\\nunittest.mock — getting started\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nDevelopment Tools »\\n\\nunittest.mock — mock object library\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\unix.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nUnix-specific services\\n\\n|\\n\\nUnix-specific services¶\\n\\nThe modules described in this chapter provide interfaces to features that are unique to the Unix operating system, or in some cases to some or many variants of it. Here’s an overview:\\n\\nshlex — Simple lexical analysis\\n\\nshlex Objects\\n\\nParsing Rules\\n\\nImproved Compatibility with Shells\\n\\nposix — The most common POSIX system calls\\n\\nLarge File Support\\n\\nNotable Module Contents\\n\\npwd — The password database\\n\\ngrp — The group database\\n\\ntermios — POSIX style tty control\\n\\nExample\\n\\ntty — Terminal control functions\\n\\npty — Pseudo-terminal utilities\\n\\nExample\\n\\nfcntl — The fcntl and ioctl system calls\\n\\nresource — Resource usage information\\n\\nResource Limits\\n\\nResource Usage\\n\\nsyslog — Unix syslog library routines\\n\\nExamples\\n\\nSimple example\\n\\nPrevious topic\\n\\nwinsound — Sound-playing interface for Windows\\n\\nNext topic\\n\\nshlex — Simple lexical analysis\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nUnix-specific services\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\urllib.error.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Protocols and Support »\\n\\nurllib.error — Exception classes raised by urllib.request\\n\\n|\\n\\nurllib.error — Exception classes raised by urllib.request¶\\n\\nSource code: Lib/urllib/error.py\\n\\nThe urllib.error module defines the exception classes for exceptions raised by urllib.request. The base exception class is URLError.\\n\\nThe following exceptions are raised by urllib.error as appropriate:\\n\\nPrevious topic\\n\\nurllib.parse — Parse URLs into components\\n\\nNext topic\\n\\nurllib.robotparser — Parser for robots.txt\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Protocols and Support »\\n\\nurllib.error — Exception classes raised by urllib.request\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\urllib.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Protocols and Support »\\n\\nurllib — URL handling modules\\n\\n|\\n\\nurllib — URL handling modules¶\\n\\nSource code: Lib/urllib/\\n\\nurllib is a package that collects several modules for working with URLs:\\n\\nurllib.request for opening and reading URLs\\n\\nurllib.error containing the exceptions raised by urllib.request\\n\\nurllib.parse for parsing URLs\\n\\nurllib.robotparser for parsing robots.txt files\\n\\nPrevious topic\\n\\nwsgiref — WSGI Utilities and Reference Implementation\\n\\nNext topic\\n\\nurllib.request — Extensible library for opening URLs\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Protocols and Support »\\n\\nurllib — URL handling modules\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\urllib.parse.html'}, page_content=\"Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Protocols and Support »\\n\\nurllib.parse — Parse URLs into components\\n\\n|\\n\\nurllib.parse — Parse URLs into components¶\\n\\nSource code: Lib/urllib/parse.py\\n\\nThis module defines a standard interface to break Uniform Resource Locator (URL) strings up in components (addressing scheme, network location, path etc.), to combine the components back into a URL string, and to convert a “relative URL” to an absolute URL given a “base URL.”\\n\\nThe module has been designed to match the internet RFC on Relative Uniform Resource Locators. It supports the following URL schemes: file, ftp, gopher, hdl, http, https, imap, itms-services, mailto, mms, news, nntp, prospero, rsync, rtsp, rtsps, rtspu, sftp, shttp, sip, sips, snews, svn, svn+ssh, telnet, wais, ws, wss.\\n\\nCPython implementation detail: The inclusion of the 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 itms-services scheme is always removed on iOS; on macOS, it may be removed if CPython has been built with the --with-app-store-compliance option.\\n\\nThe 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.\\n\\nThis module’s functions use the deprecated term netloc (or net_loc), which was introduced in RFC 1808. However, this term has been obsoleted by RFC 3986, which introduced the term authority as its replacement. The use of netloc is continued for backward compatibility.\\n\\nURL Parsing¶\\n\\nThe URL parsing functions focus on splitting a URL string into its components, or on combining URL components into a URL string.\\n\\nURL parsing security¶\\n\\nThe urlsplit() and 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.\\n\\nInstead of raising an exception on unusual input, they may instead return some component parts as empty strings or None (depending on the value of the missing_as_none argument). Or components may contain more than perhaps they should.\\n\\nWe 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 scheme make sense? Is that a sensible path? Is there anything strange about that hostname? etc.\\n\\nWhat constitutes a URL is not universally well defined. Different applications have different needs and desired constraints. For instance the living WHATWG spec describes what user facing web clients such as a web browser require. While RFC 3986 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.\\n\\nParsing ASCII Encoded Bytes¶\\n\\nThe URL parsing functions were originally designed to operate on character strings only. In practice, it is useful to be able to manipulate properly quoted and encoded URLs as sequences of ASCII bytes. Accordingly, the URL parsing functions in this module all operate on bytes and bytearray objects in addition to str objects.\\n\\nIf str data is passed in, the result will also contain only str data. If bytes or bytearray data is passed in, the result will contain only bytes data.\\n\\nAttempting to mix str data with bytes or bytearray in a single function call will result in a TypeError being raised, while attempting to pass in non-ASCII byte values will trigger UnicodeDecodeError.\\n\\nTo support easier conversion of result objects between str and bytes, all return values from URL parsing functions provide either an encode() method (when the result contains str data) or a decode() method (when the result contains bytes data). The signatures of these methods match those of the corresponding str and bytes methods (except that the default encoding is 'ascii' rather than 'utf-8'). Each produces a value of a corresponding type that contains either bytes data (for encode() methods) or str data (for decode() methods).\\n\\nApplications that need to operate on potentially improperly quoted URLs that may contain non-ASCII data will need to do their own decoding from bytes to characters before invoking the URL parsing methods.\\n\\nThe behaviour described in this section applies only to the URL parsing functions. The URL quoting functions use their own rules when producing or consuming byte sequences as detailed in the documentation of the individual URL quoting functions.\\n\\nChanged in version 3.2: URL parsing functions now accept ASCII encoded byte sequences\\n\\nStructured Parse Results¶\\n\\nThe result objects from the urlsplit(), urlparse() and urldefrag() functions are subclasses of the 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:\\n\\nThe following classes provide the implementations of the structured parse results when operating on str objects:\\n\\nThe following classes provide the implementations of the parse results when operating on bytes or bytearray objects:\\n\\nURL Quoting¶\\n\\nThe URL quoting functions focus on taking program data and making it safe for use as URL components by quoting special characters and appropriately encoding non-ASCII text. They also support reversing these operations to recreate the original data from the contents of a URL component if that task isn’t already covered by the URL parsing functions above.\\n\\nSee also\\n\\nTable of Contents\\n\\nurllib.parse — Parse URLs into components\\n\\nURL Parsing\\n\\nURL parsing security\\n\\nParsing ASCII Encoded Bytes\\n\\nStructured Parse Results\\n\\nURL Quoting\\n\\nPrevious topic\\n\\nurllib.request — Extensible library for opening URLs\\n\\nNext topic\\n\\nurllib.error — Exception classes raised by urllib.request\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Protocols and Support »\\n\\nurllib.parse — Parse URLs into components\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.\"), Document(metadata={'source': '..\\\\..\\\\docs\\\\urllib.request.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Protocols and Support »\\n\\nurllib.request — Extensible library for opening URLs\\n\\n|\\n\\nurllib.request — Extensible library for opening URLs¶\\n\\nSource code: Lib/urllib/request.py\\n\\nThe 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.\\n\\nSee also\\n\\nThe Requests package is recommended for a higher-level HTTP client interface.\\n\\nWarning\\n\\nOn macOS it is unsafe to use this module in programs using os.fork() because the getproxies() implementation for macOS uses a higher-level system API. Set the environment variable no_proxy to * to avoid this problem (e.g. os.environ[\"no_proxy\"] = \"*\").\\n\\nAvailability: not WASI.\\n\\nThis module does not work or is not available on WebAssembly. See WebAssembly platforms for more information.\\n\\nThe urllib.request module defines the following functions:\\n\\nThe following classes are provided:\\n\\nRequest Objects¶\\n\\nThe following methods describe Request’s public interface, and so all may be overridden in subclasses. It also defines several public attributes that can be used by clients to inspect the parsed request.\\n\\nChanged in version 3.4: The request methods add_data, has_data, get_data, get_type, get_host, get_selector, get_origin_req_host and is_unverifiable that were deprecated since 3.3 have been removed.\\n\\nOpenerDirector Objects¶\\n\\nOpenerDirector instances have the following methods:\\n\\nOpenerDirector objects open URLs in three stages:\\n\\nThe order in which these methods are called within each stage is determined by sorting the handler instances.\\n\\nEvery handler with a method named like _request() has that method called to pre-process the request.\\n\\nHandlers with a method named like _open() are called to handle the request. This stage ends when a handler either returns a non-None value (ie. a response), or raises an exception (usually URLError). Exceptions are allowed to propagate.\\n\\nIn fact, the above algorithm is first tried for methods named default_open(). If all such methods return None, the algorithm is repeated for methods named like _open(). If all such methods return None, the algorithm is repeated for methods named unknown_open().\\n\\nNote that the implementation of these methods may involve calls of the parent OpenerDirector instance’s open() and error() methods.\\n\\nEvery handler with a method named like _response() has that method called to post-process the response.\\n\\nBaseHandler Objects¶\\n\\nBaseHandler objects provide a couple of methods that are directly useful, and others that are meant to be used by derived classes. These are intended for direct use:\\n\\nThe following attribute and methods should only be used by classes derived from BaseHandler.\\n\\nNote\\n\\nThe convention has been adopted that subclasses defining _request() or _response() methods are named *Processor; all others are named *Handler.\\n\\nHTTPRedirectHandler Objects¶\\n\\nNote\\n\\nSome HTTP redirections require action from this module’s client code. If this is the case, HTTPError is raised. See RFC 2616 for details of the precise meanings of the various redirection codes.\\n\\nAn HTTPError exception raised as a security consideration if the HTTPRedirectHandler is presented with a redirected URL which is not an HTTP, HTTPS or FTP URL.\\n\\nHTTPCookieProcessor Objects¶\\n\\nHTTPCookieProcessor instances have one attribute:\\n\\nProxyHandler Objects¶\\n\\nHTTPPasswordMgr Objects¶\\n\\nThese methods are available on HTTPPasswordMgr and HTTPPasswordMgrWithDefaultRealm objects.\\n\\nHTTPPasswordMgrWithPriorAuth Objects¶\\n\\nThis password manager extends HTTPPasswordMgrWithDefaultRealm to support tracking URIs for which authentication credentials should always be sent.\\n\\nAbstractBasicAuthHandler Objects¶\\n\\nHTTPBasicAuthHandler Objects¶\\n\\nProxyBasicAuthHandler Objects¶\\n\\nAbstractDigestAuthHandler Objects¶\\n\\nHTTPDigestAuthHandler Objects¶\\n\\nProxyDigestAuthHandler Objects¶\\n\\nHTTPHandler Objects¶\\n\\nHTTPSHandler Objects¶\\n\\nFileHandler Objects¶\\n\\nDataHandler Objects¶\\n\\nFTPHandler Objects¶\\n\\nCacheFTPHandler Objects¶\\n\\nCacheFTPHandler objects are FTPHandler objects with the following additional methods:\\n\\nUnknownHandler Objects¶\\n\\nHTTPErrorProcessor Objects¶\\n\\nExamples¶\\n\\nIn addition to the examples below, more examples are given in HOWTO Fetch Internet Resources Using The urllib Package.\\n\\nThis example gets the python.org main page and displays the first 300 bytes of it:\\n\\n>>> import urllib.request\\n>>> with urllib.request.urlopen(\\'http://www.python.org/\\') as f:\\n... print(f.read(300))\\n...\\nb\\'\\\\n\\\\n\\\\n\\n>> import urllib.request\\n>>> f = urllib.request.urlopen(\\'http://www.python.org/\\')\\n>>> try:\\n... print(f.read(100).decode(\\'utf-8\\'))\\n... finally:\\n... f.close()\\n...\\n\\n\\n\\', char.text)\\n\\nA better way to search the namespaced XML example is to create a dictionary with your own prefixes and use those in the search functions:\\n\\nns = {\\'real_person\\': \\'http://people.example.com\\',\\n \\'role\\': \\'http://characters.example.com\\'}\\n\\nfor actor in root.findall(\\'real_person:actor\\', ns):\\n name = actor.find(\\'real_person:name\\', ns)\\n print(name.text)\\n for char in actor.findall(\\'role:character\\', ns):\\n print(\\' |-->\\', char.text)\\n\\nThese two approaches both output:\\n\\nJohn Cleese\\n |--> Lancelot\\n |--> Archie Leach\\nEric Idle\\n |--> Sir Robin\\n |--> Gunther\\n |--> Commander Clement\\n\\nXPath support¶\\n\\nThis module provides limited support for XPath expressions for locating elements in a tree. The goal is to support a small subset of the abbreviated syntax; a full XPath engine is outside the scope of the module.\\n\\nExample¶\\n\\nHere’s an example that demonstrates some of the XPath capabilities of the module. We’ll be using the countrydata XML document from the Parsing XML section:\\n\\nimport xml.etree.ElementTree as ET\\n\\nroot = ET.fromstring(countrydata)\\n\\n# Top-level elements\\nroot.findall(\".\")\\n\\n# All \\'neighbor\\' grand-children of \\'country\\' children of the top-level\\n# elements\\nroot.findall(\"./country/neighbor\")\\n\\n# Nodes with name=\\'Singapore\\' that have a \\'year\\' child\\nroot.findall(\".//year/..[@name=\\'Singapore\\']\")\\n\\n# \\'year\\' nodes that are children of nodes with name=\\'Singapore\\'\\nroot.findall(\".//*[@name=\\'Singapore\\']/year\")\\n\\n# All \\'neighbor\\' nodes that are the second child of their parent\\nroot.findall(\".//neighbor[2]\")\\n\\nFor XML with namespaces, use the usual qualified {namespace}tag notation:\\n\\n# All dublin-core \"title\" tags in the document\\nroot.findall(\".//{http://purl.org/dc/elements/1.1/}title\")\\n\\nSupported XPath syntax¶\\n\\nSyntax Meaning tag Selects all child elements with the given tag.\\nFor example, spam selects all child elements\\nnamed spam , and spam/egg selects all\\ngrandchildren named egg in all children named spam . {namespace}* selects all tags in the\\ngiven namespace, {*}spam selects tags named spam in any (or no) namespace, and {}* only selects tags that are not in a namespace. Changed in version 3.8: Support for star-wildcards was added. * Selects all child elements, including comments and\\nprocessing instructions. For example, */egg selects all grandchildren named egg . . Selects the current node. This is mostly useful\\nat the beginning of the path, to indicate that it’s\\na relative path. // Selects all subelements, on all levels beneath the\\ncurrent element. For example, .//egg selects\\nall egg elements in the entire tree. .. Selects the parent element. Returns None if the\\npath attempts to reach the ancestors of the start\\nelement (the element find was called on). [@attrib] Selects all elements that have the given attribute. [@attrib=\\'value\\'] Selects all elements for which the given attribute\\nhas the given value. The value cannot contain\\nquotes. [@attrib!=\\'value\\'] Selects all elements for which the given attribute\\ndoes not have the given value. The value cannot\\ncontain quotes. Added in version 3.10. [tag] Selects all elements that have a child named tag . Only immediate children are supported. [.=\\'text\\'] Selects all elements whose complete text content,\\nincluding descendants, equals the given text . Added in version 3.7. [.!=\\'text\\'] Selects all elements whose complete text content,\\nincluding descendants, does not equal the given text . Added in version 3.10. [tag=\\'text\\'] Selects all elements that have a child named tag whose complete text content, including\\ndescendants, equals the given text . [tag!=\\'text\\'] Selects all elements that have a child named tag whose complete text content, including\\ndescendants, does not equal the given text . Added in version 3.10. [position] Selects all elements that are located at the given\\nposition. The position can be either an integer\\n(1 is the first position), the expression last() (for the last position), or a position relative to\\nthe last position (e.g. last()-1 ).\\n\\nPredicates (expressions within square brackets) must be preceded by a tag name, an asterisk, or another predicate. position predicates must be preceded by a tag name.\\n\\nReference¶\\n\\nFunctions¶\\n\\nXInclude support¶\\n\\nThis module provides limited support for XInclude directives, via the 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.\\n\\nExample¶\\n\\nHere’s an example that demonstrates use of the XInclude module. To include an XML document in the current document, use the {http://www.w3.org/2001/XInclude}include element and set the parse attribute to \"xml\", and use the href attribute to specify the document to include.\\n\\n\\n\\n \\n\\n\\nBy 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.\\n\\nTo process this file, load it as usual, and pass the root element to the xml.etree.ElementTree module:\\n\\nfrom xml.etree import ElementTree, ElementInclude\\n\\ntree = ElementTree.parse(\"document.xml\")\\nroot = tree.getroot()\\n\\nElementInclude.include(root)\\n\\nThe ElementInclude module replaces the {http://www.w3.org/2001/XInclude}include element with the root element from the source.xml document. The result might look something like this:\\n\\n\\n This is a paragraph.\\n\\n\\nIf the parse attribute is omitted, it defaults to “xml”. The href attribute is required.\\n\\nTo include a text document, use the {http://www.w3.org/2001/XInclude}include element, and set the parse attribute to “text”:\\n\\n\\n\\n Copyright (c) .\\n\\n\\nThe result might look something like:\\n\\n\\n Copyright (c) 2003.\\n\\n\\nReference¶\\n\\nFunctions¶\\n\\nElement Objects¶\\n\\nElementTree Objects¶\\n\\nThis is the XML file that is going to be manipulated:\\n\\n\\n \\n Example page\\n \\n \\n

Moved to example.org\\n or example.com.

\\n \\n\\n\\nExample of changing the attribute “target” of every link in first paragraph:\\n\\n>>> from xml.etree.ElementTree import ElementTree\\n>>> tree = ElementTree()\\n>>> tree.parse(\"index.xhtml\")\\n\\n>>> p = tree.find(\"body/p\") # Finds first occurrence of tag p in body\\n>>> p\\n\\n>>> links = list(p.iter(\"a\")) # Returns list of all links\\n>>> links\\n[, ]\\n>>> for i in links: # Iterates through all found links\\n... i.attrib[\"target\"] = \"blank\"\\n...\\n>>> tree.write(\"output.xhtml\")\\n\\nQName Objects¶\\n\\nTreeBuilder Objects¶\\n\\nXMLParser Objects¶\\n\\nXMLPullParser Objects¶\\n\\nExceptions¶\\n\\nFootnotes\\n\\n[1] (1,2,3,4)\\n\\nThe encoding string included in XML output should conform to the appropriate standards. For example, “UTF-8” is valid, but “UTF8” is not. See https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl and https://www.iana.org/assignments/character-sets/character-sets.xhtml.\\n\\nTable of Contents\\n\\nxml.etree.ElementTree — The ElementTree XML API\\n\\nTutorial\\n\\nXML tree and elements\\n\\nParsing XML\\n\\nPull API for non-blocking parsing\\n\\nFinding interesting elements\\n\\nModifying an XML File\\n\\nBuilding XML documents\\n\\nParsing XML with Namespaces\\n\\nXPath support\\n\\nExample\\n\\nSupported XPath syntax\\n\\nReference\\n\\nFunctions\\n\\nXInclude support\\n\\nExample\\n\\nReference\\n\\nFunctions\\n\\nElement Objects\\n\\nElementTree Objects\\n\\nQName Objects\\n\\nTreeBuilder Objects\\n\\nXMLParser Objects\\n\\nXMLPullParser Objects\\n\\nExceptions\\n\\nPrevious topic\\n\\nXML Processing Modules\\n\\nNext topic\\n\\nxml.dom — The Document Object Model API\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nStructured Markup Processing Tools »\\n\\nxml.etree.ElementTree — The ElementTree XML API\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\xml.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nStructured Markup Processing Tools »\\n\\nXML Processing Modules\\n\\n|\\n\\nXML Processing Modules¶\\n\\nSource code: Lib/xml/\\n\\nPython’s interfaces for processing XML are grouped in the xml package.\\n\\nNote\\n\\nIf you need to parse untrusted or unauthenticated data, see XML security.\\n\\nIt is important to note that modules in the xml package require that there be at least one SAX-compliant XML parser available. The Expat parser is included with Python, so the xml.parsers.expat module will always be available.\\n\\nThe documentation for the xml.dom and xml.sax packages are the definition of the Python bindings for the DOM and SAX interfaces.\\n\\nThe XML handling submodules are:\\n\\nxml.etree.ElementTree: the ElementTree API, a simple and lightweight XML processor\\n\\nxml.dom: the DOM API definition\\n\\nxml.dom.minidom: a minimal DOM implementation\\n\\nxml.dom.pulldom: support for building partial DOM trees\\n\\nxml.sax: SAX2 base classes and convenience functions\\n\\nxml.parsers.expat: the Expat parser binding\\n\\nXML security¶\\n\\nAn 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.\\n\\nThe built-in XML parsers of Python rely on the library libexpat, commonly called Expat, for parsing XML.\\n\\nBy default, Expat itself does not access local files or create network connections.\\n\\nExpat 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 has been configured in your environment. Python may be vulnerable if it uses such older versions of Expat. Check pyexpat.EXPAT_VERSION.\\n\\nxmlrpc is vulnerable to the “decompression bomb” attack.\\n\\nTable of Contents\\n\\nXML Processing Modules\\n\\nXML security\\n\\nPrevious topic\\n\\nhtml.entities — Definitions of HTML general entities\\n\\nNext topic\\n\\nxml.etree.ElementTree — The ElementTree XML API\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nStructured Markup Processing Tools »\\n\\nXML Processing Modules\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\xml.sax.handler.html'}, page_content=\"Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nStructured Markup Processing Tools »\\n\\nxml.sax.handler — Base classes for SAX handlers\\n\\n|\\n\\nxml.sax.handler — Base classes for SAX handlers¶\\n\\nSource code: Lib/xml/sax/handler.py\\n\\nThe 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 xml.sax.handler, so that all methods get default implementations.\\n\\nIn addition to these classes, xml.sax.handler provides symbolic constants for the feature and property names.\\n\\nContentHandler Objects¶\\n\\nUsers are expected to subclass ContentHandler to support their application. The following methods are called by the parser on the appropriate events in the input document:\\n\\nDTDHandler Objects¶\\n\\nDTDHandler instances provide the following methods:\\n\\nEntityResolver Objects¶\\n\\nErrorHandler Objects¶\\n\\nObjects with this interface are used to receive error and warning information from the XMLReader. If you create an object that implements this interface, then register the object with your 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 SAXParseException as the only parameter. Errors and warnings may be converted to an exception by raising the passed-in exception object.\\n\\nLexicalHandler Objects¶\\n\\nOptional SAX2 handler for lexical events.\\n\\nThis 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.\\n\\nSet the LexicalHandler of an XMLReader by using the setProperty method with the property identifier 'http://xml.org/sax/properties/lexical-handler'.\\n\\nTable of Contents\\n\\nxml.sax.handler — Base classes for SAX handlers\\n\\nContentHandler Objects\\n\\nDTDHandler Objects\\n\\nEntityResolver Objects\\n\\nErrorHandler Objects\\n\\nLexicalHandler Objects\\n\\nPrevious topic\\n\\nxml.sax — Support for SAX2 parsers\\n\\nNext topic\\n\\nxml.sax.saxutils — SAX Utilities\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nStructured Markup Processing Tools »\\n\\nxml.sax.handler — Base classes for SAX handlers\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.\"), Document(metadata={'source': '..\\\\..\\\\docs\\\\xml.sax.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nStructured Markup Processing Tools »\\n\\nxml.sax — Support for SAX2 parsers\\n\\n|\\n\\nxml.sax — Support for SAX2 parsers¶\\n\\nSource code: Lib/xml/sax/__init__.py\\n\\nThe 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.\\n\\nNote\\n\\nIf you need to parse untrusted or unauthenticated data, see XML security.\\n\\nChanged in version 3.7.1: The SAX parser no longer processes general external entities by default to increase security. Before, the parser created network connections to fetch remote files or loaded local files from the file system for DTD and entities. The feature can be enabled again with method setFeature() on the parser object and argument feature_external_ges.\\n\\nThe convenience functions are:\\n\\nA typical SAX application uses three kinds of objects: readers, handlers and input sources. “Reader” in this context is another term for parser, i.e. some piece of code that reads the bytes or characters from the input source, and produces a sequence of events. The events then get distributed to the handler objects, i.e. the reader invokes a method on the handler. A SAX application must therefore obtain a reader object, create or open the input sources, create the handlers, and connect these objects all together. As the final step of preparation, the reader is called to parse the input. During parsing, methods on the handler objects are called based on structural and syntactic events from the input data.\\n\\nFor 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 InputSource, Locator, Attributes, AttributesNS, and XMLReader interfaces are defined in the module xml.sax.xmlreader. The handler interfaces are defined in xml.sax.handler. For convenience, InputSource (which is often instantiated directly) and the handler classes are also available from xml.sax. These interfaces are described below.\\n\\nIn addition to these classes, xml.sax provides the following exception classes.\\n\\nSee also\\n\\nSAXException Objects¶\\n\\nThe SAXException exception class supports the following methods:\\n\\nTable of Contents\\n\\nxml.sax — Support for SAX2 parsers\\n\\nSAXException Objects\\n\\nPrevious topic\\n\\nxml.dom.pulldom — Support for building partial DOM trees\\n\\nNext topic\\n\\nxml.sax.handler — Base classes for SAX handlers\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nStructured Markup Processing Tools »\\n\\nxml.sax — Support for SAX2 parsers\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\xml.sax.reader.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nStructured Markup Processing Tools »\\n\\nxml.sax.xmlreader — Interface for XML parsers\\n\\n|\\n\\nxml.sax.xmlreader — Interface for XML parsers¶\\n\\nSource code: Lib/xml/sax/xmlreader.py\\n\\nSAX parsers implement the XMLReader interface. They are implemented in a Python module, which must provide a function create_parser(). This function is invoked by xml.sax.make_parser() with no arguments to create a new parser object.\\n\\nXMLReader Objects¶\\n\\nThe XMLReader interface supports the following methods:\\n\\nIncrementalParser Objects¶\\n\\nInstances of IncrementalParser offer the following additional methods:\\n\\nLocator Objects¶\\n\\nInstances of Locator provide these methods:\\n\\nInputSource Objects¶\\n\\nThe Attributes Interface¶\\n\\nAttributes objects implement a portion of the mapping protocol, including the methods copy(), get(), __contains__(), items(), keys(), and values(). The following methods are also provided:\\n\\nThe AttributesNS Interface¶\\n\\nThis interface is a subtype of the Attributes interface (see section The Attributes Interface). All methods supported by that interface are also available on AttributesNS objects.\\n\\nThe following methods are also available:\\n\\nTable of Contents\\n\\nxml.sax.xmlreader — Interface for XML parsers\\n\\nXMLReader Objects\\n\\nIncrementalParser Objects\\n\\nLocator Objects\\n\\nInputSource Objects\\n\\nThe Attributes Interface\\n\\nThe AttributesNS Interface\\n\\nPrevious topic\\n\\nxml.sax.saxutils — SAX Utilities\\n\\nNext topic\\n\\nxml.parsers.expat — Fast XML parsing using Expat\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nStructured Markup Processing Tools »\\n\\nxml.sax.xmlreader — Interface for XML parsers\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\xml.sax.utils.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nStructured Markup Processing Tools »\\n\\nxml.sax.saxutils — SAX Utilities\\n\\n|\\n\\nxml.sax.saxutils — SAX Utilities¶\\n\\nSource code: Lib/xml/sax/saxutils.py\\n\\nThe module 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.\\n\\nPrevious topic\\n\\nxml.sax.handler — Base classes for SAX handlers\\n\\nNext topic\\n\\nxml.sax.xmlreader — Interface for XML parsers\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nStructured Markup Processing Tools »\\n\\nxml.sax.saxutils — SAX Utilities\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\xmlrpc.client.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Protocols and Support »\\n\\nxmlrpc.client — XML-RPC client access\\n\\n|\\n\\nxmlrpc.client — XML-RPC client access¶\\n\\nSource code: Lib/xmlrpc/client.py\\n\\nXML-RPC is a Remote Procedure Call method that uses XML passed via HTTP(S) as a transport. With it, a client can call methods with parameters on a remote server (the server is named by a URI) and get back structured data. This module supports writing XML-RPC client code; it handles all the details of translating between conformable Python objects and XML on the wire.\\n\\nWarning\\n\\nThe xmlrpc.client module is not secure against maliciously constructed data. If you need to parse untrusted or unauthenticated data, see XML security.\\n\\nChanged in version 3.5: For HTTPS URIs, xmlrpc.client now performs all the necessary certificate and hostname checks by default.\\n\\nAvailability: not WASI.\\n\\nThis module does not work or is not available on WebAssembly. See WebAssembly platforms for more information.\\n\\nSee also\\n\\nServerProxy Objects¶\\n\\nA ServerProxy instance has a method corresponding to each remote procedure call accepted by the XML-RPC server. Calling the method performs an RPC, dispatched by both name and argument signature (e.g. the same method name can be overloaded with multiple argument signatures). The RPC finishes either by returning data in a conformant type or by raising a Fault or ProtocolError exception indicating an error.\\n\\nServers that support the XML introspection API support some common methods grouped under the reserved system attribute:\\n\\nChanged in version 3.5: Instances of ServerProxy support the context manager protocol for closing the underlying transport.\\n\\nA working example follows. The server code:\\n\\nfrom xmlrpc.server import SimpleXMLRPCServer\\n\\ndef is_even(n):\\n return n % 2 == 0\\n\\nserver = SimpleXMLRPCServer((\"localhost\", 8000))\\nprint(\"Listening on port 8000...\")\\nserver.register_function(is_even, \"is_even\")\\nserver.serve_forever()\\n\\nThe client code for the preceding server:\\n\\nimport xmlrpc.client\\n\\nwith xmlrpc.client.ServerProxy(\"http://localhost:8000/\") as proxy:\\n print(\"3 is even: %s\" % str(proxy.is_even(3)))\\n print(\"100 is even: %s\" % str(proxy.is_even(100)))\\n\\nDateTime Objects¶\\n\\nA working example follows. The server code:\\n\\nimport datetime\\nfrom xmlrpc.server import SimpleXMLRPCServer\\nimport xmlrpc.client\\n\\ndef today():\\n today = datetime.datetime.today()\\n return xmlrpc.client.DateTime(today)\\n\\nserver = SimpleXMLRPCServer((\"localhost\", 8000))\\nprint(\"Listening on port 8000...\")\\nserver.register_function(today, \"today\")\\nserver.serve_forever()\\n\\nThe client code for the preceding server:\\n\\nimport xmlrpc.client\\nimport datetime\\n\\nproxy = xmlrpc.client.ServerProxy(\"http://localhost:8000/\")\\n\\ntoday = proxy.today()\\n# convert the ISO8601 string to a datetime object\\nconverted = datetime.datetime.strptime(today.value, \"%Y%m%dT%H:%M:%S\")\\nprint(\"Today: %s\" % converted.strftime(\"%d.%m.%Y, %H:%M\"))\\n\\nBinary Objects¶\\n\\nExample usage of the binary objects. We’re going to transfer an image over XMLRPC:\\n\\nfrom xmlrpc.server import SimpleXMLRPCServer\\nimport xmlrpc.client\\n\\ndef python_logo():\\n with open(\"python_logo.jpg\", \"rb\") as handle:\\n return xmlrpc.client.Binary(handle.read())\\n\\nserver = SimpleXMLRPCServer((\"localhost\", 8000))\\nprint(\"Listening on port 8000...\")\\nserver.register_function(python_logo, \\'python_logo\\')\\n\\nserver.serve_forever()\\n\\nThe client gets the image and saves it to a file:\\n\\nimport xmlrpc.client\\n\\nproxy = xmlrpc.client.ServerProxy(\"http://localhost:8000/\")\\nwith open(\"fetched_python_logo.jpg\", \"wb\") as handle:\\n handle.write(proxy.python_logo().data)\\n\\nFault Objects¶\\n\\nIn the following example we’re going to intentionally cause a Fault by returning a complex type object. The server code:\\n\\nfrom xmlrpc.server import SimpleXMLRPCServer\\n\\n# A marshalling error is going to occur because we\\'re returning a\\n# complex number\\ndef add(x, y):\\n return x+y+0j\\n\\nserver = SimpleXMLRPCServer((\"localhost\", 8000))\\nprint(\"Listening on port 8000...\")\\nserver.register_function(add, \\'add\\')\\n\\nserver.serve_forever()\\n\\nThe client code for the preceding server:\\n\\nimport xmlrpc.client\\n\\nproxy = xmlrpc.client.ServerProxy(\"http://localhost:8000/\")\\ntry:\\n proxy.add(2, 5)\\nexcept xmlrpc.client.Fault as err:\\n print(\"A fault occurred\")\\n print(\"Fault code: %d\" % err.faultCode)\\n print(\"Fault string: %s\" % err.faultString)\\n\\nProtocolError Objects¶\\n\\nIn the following example we’re going to intentionally cause a ProtocolError by providing an invalid URI:\\n\\nimport xmlrpc.client\\n\\n# create a ServerProxy with a URI that doesn\\'t respond to XMLRPC requests\\nproxy = xmlrpc.client.ServerProxy(\"http://google.com/\")\\n\\ntry:\\n proxy.some_method()\\nexcept xmlrpc.client.ProtocolError as err:\\n print(\"A protocol error occurred\")\\n print(\"URL: %s\" % err.url)\\n print(\"HTTP/HTTPS headers: %s\" % err.headers)\\n print(\"Error code: %d\" % err.errcode)\\n print(\"Error message: %s\" % err.errmsg)\\n\\nMultiCall Objects¶\\n\\nThe MultiCall object provides a way to encapsulate multiple calls to a remote server into a single request [1].\\n\\nA usage example of this class follows. The server code:\\n\\nfrom xmlrpc.server import SimpleXMLRPCServer\\n\\ndef add(x, y):\\n return x + y\\n\\ndef subtract(x, y):\\n return x - y\\n\\ndef multiply(x, y):\\n return x * y\\n\\ndef divide(x, y):\\n return x // y\\n\\n# A simple server with simple arithmetic functions\\nserver = SimpleXMLRPCServer((\"localhost\", 8000))\\nprint(\"Listening on port 8000...\")\\nserver.register_multicall_functions()\\nserver.register_function(add, \\'add\\')\\nserver.register_function(subtract, \\'subtract\\')\\nserver.register_function(multiply, \\'multiply\\')\\nserver.register_function(divide, \\'divide\\')\\nserver.serve_forever()\\n\\nThe client code for the preceding server:\\n\\nimport xmlrpc.client\\n\\nproxy = xmlrpc.client.ServerProxy(\"http://localhost:8000/\")\\nmulticall = xmlrpc.client.MultiCall(proxy)\\nmulticall.add(7, 3)\\nmulticall.subtract(7, 3)\\nmulticall.multiply(7, 3)\\nmulticall.divide(7, 3)\\nresult = multicall()\\n\\nprint(\"7+3=%d, 7-3=%d, 7*3=%d, 7//3=%d\" % tuple(result))\\n\\nConvenience Functions¶\\n\\nExample of Client Usage¶\\n\\n# simple test program (from the XML-RPC specification)\\nfrom xmlrpc.client import ServerProxy, Error\\n\\n# server = ServerProxy(\"http://localhost:8000\") # local server\\nwith ServerProxy(\"http://betty.userland.com\") as proxy:\\n\\n print(proxy)\\n\\n try:\\n print(proxy.examples.getStateName(41))\\n except Error as v:\\n print(\"ERROR\", v)\\n\\nTo access an XML-RPC server through a HTTP proxy, you need to define a custom transport. The following example shows how:\\n\\nimport http.client\\nimport xmlrpc.client\\n\\nclass ProxiedTransport(xmlrpc.client.Transport):\\n\\n def set_proxy(self, host, port=None, headers=None):\\n self.proxy = host, port\\n self.proxy_headers = headers\\n\\n def make_connection(self, host):\\n connection = http.client.HTTPConnection(*self.proxy)\\n connection.set_tunnel(host, headers=self.proxy_headers)\\n self._connection = host, connection\\n return connection\\n\\ntransport = ProxiedTransport()\\ntransport.set_proxy(\\'proxy-server\\', 8080)\\nserver = xmlrpc.client.ServerProxy(\\'http://betty.userland.com\\', transport=transport)\\nprint(server.examples.getStateName(41))\\n\\nExample of Client and Server Usage¶\\n\\nSee SimpleXMLRPCServer Example.\\n\\nFootnotes\\n\\n[1]\\n\\nThis approach has been first presented in a discussion on xmlrpc.com.\\n\\nTable of Contents\\n\\nxmlrpc.client — XML-RPC client access\\n\\nServerProxy Objects\\n\\nDateTime Objects\\n\\nBinary Objects\\n\\nFault Objects\\n\\nProtocolError Objects\\n\\nMultiCall Objects\\n\\nConvenience Functions\\n\\nExample of Client Usage\\n\\nExample of Client and Server Usage\\n\\nPrevious topic\\n\\nxmlrpc — XMLRPC server and client modules\\n\\nNext topic\\n\\nxmlrpc.server — Basic XML-RPC servers\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Protocols and Support »\\n\\nxmlrpc.client — XML-RPC client access\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\xmlrpc.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Protocols and Support »\\n\\nxmlrpc — XMLRPC server and client modules\\n\\n|\\n\\nxmlrpc — XMLRPC server and client modules¶\\n\\nXML-RPC is a Remote Procedure Call method that uses XML passed via HTTP as a transport. With it, a client can call methods with parameters on a remote server (the server is named by a URI) and get back structured data.\\n\\nxmlrpc is a package that collects server and client modules implementing XML-RPC. The modules are:\\n\\nxmlrpc.client\\n\\nxmlrpc.server\\n\\nPrevious topic\\n\\nhttp.cookiejar — Cookie handling for HTTP clients\\n\\nNext topic\\n\\nxmlrpc.client — XML-RPC client access\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Protocols and Support »\\n\\nxmlrpc — XMLRPC server and client modules\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\xmlrpc.server.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Protocols and Support »\\n\\nxmlrpc.server — Basic XML-RPC servers\\n\\n|\\n\\nxmlrpc.server — Basic XML-RPC servers¶\\n\\nSource code: Lib/xmlrpc/server.py\\n\\nThe xmlrpc.server module provides a basic server framework for XML-RPC servers written in Python. Servers can either be free standing, using SimpleXMLRPCServer, or embedded in a CGI environment, using CGIXMLRPCRequestHandler.\\n\\nWarning\\n\\nThe xmlrpc.server module is not secure against maliciously constructed data. If you need to parse untrusted or unauthenticated data, see XML security.\\n\\nAvailability: not WASI.\\n\\nThis module does not work or is not available on WebAssembly. See WebAssembly platforms for more information.\\n\\nSimpleXMLRPCServer Objects¶\\n\\nThe SimpleXMLRPCServer class is based on socketserver.TCPServer and provides a means of creating simple, stand alone XML-RPC servers.\\n\\nSimpleXMLRPCServer Example¶\\n\\nServer code:\\n\\nfrom xmlrpc.server import SimpleXMLRPCServer\\nfrom xmlrpc.server import SimpleXMLRPCRequestHandler\\n\\n# Restrict to a particular path.\\nclass RequestHandler(SimpleXMLRPCRequestHandler):\\n rpc_paths = (\\'/RPC2\\',)\\n\\n# Create server\\nwith SimpleXMLRPCServer((\\'localhost\\', 8000),\\n requestHandler=RequestHandler) as server:\\n server.register_introspection_functions()\\n\\n # Register pow() function; this will use the value of\\n # pow.__name__ as the name, which is just \\'pow\\'.\\n server.register_function(pow)\\n\\n # Register a function under a different name\\n def adder_function(x, y):\\n return x + y\\n server.register_function(adder_function, \\'add\\')\\n\\n # Register an instance; all the methods of the instance are\\n # published as XML-RPC methods (in this case, just \\'mul\\').\\n class MyFuncs:\\n def mul(self, x, y):\\n return x * y\\n\\n server.register_instance(MyFuncs())\\n\\n # Run the server\\'s main loop\\n server.serve_forever()\\n\\nThe following client code will call the methods made available by the preceding server:\\n\\nimport xmlrpc.client\\n\\ns = xmlrpc.client.ServerProxy(\\'http://localhost:8000\\')\\nprint(s.pow(2,3)) # Returns 2**3 = 8\\nprint(s.add(2,3)) # Returns 5\\nprint(s.mul(5,2)) # Returns 5*2 = 10\\n\\n# Print list of available methods\\nprint(s.system.listMethods())\\n\\nregister_function() can also be used as a decorator. The previous server example can register functions in a decorator way:\\n\\nfrom xmlrpc.server import SimpleXMLRPCServer\\nfrom xmlrpc.server import SimpleXMLRPCRequestHandler\\n\\nclass RequestHandler(SimpleXMLRPCRequestHandler):\\n rpc_paths = (\\'/RPC2\\',)\\n\\nwith SimpleXMLRPCServer((\\'localhost\\', 8000),\\n requestHandler=RequestHandler) as server:\\n server.register_introspection_functions()\\n\\n # Register pow() function; this will use the value of\\n # pow.__name__ as the name, which is just \\'pow\\'.\\n server.register_function(pow)\\n\\n # Register a function under a different name, using\\n # register_function as a decorator. *name* can only be given\\n # as a keyword argument.\\n @server.register_function(name=\\'add\\')\\n def adder_function(x, y):\\n return x + y\\n\\n # Register a function under function.__name__.\\n @server.register_function\\n def mul(x, y):\\n return x * y\\n\\n server.serve_forever()\\n\\nThe following example included in the Lib/xmlrpc/server.py module shows a server allowing dotted names and registering a multicall function.\\n\\nWarning\\n\\nEnabling 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.\\n\\nimport datetime\\n\\nclass ExampleService:\\n def getData(self):\\n return \\'42\\'\\n\\n class currentTime:\\n @staticmethod\\n def getCurrentTime():\\n return datetime.datetime.now()\\n\\nwith SimpleXMLRPCServer((\"localhost\", 8000)) as server:\\n server.register_function(pow)\\n server.register_function(lambda x,y: x+y, \\'add\\')\\n server.register_instance(ExampleService(), allow_dotted_names=True)\\n server.register_multicall_functions()\\n print(\\'Serving XML-RPC on localhost port 8000\\')\\n try:\\n server.serve_forever()\\n except KeyboardInterrupt:\\n print(\"\\\\nKeyboard interrupt received, exiting.\")\\n sys.exit(0)\\n\\nThis ExampleService demo can be invoked from the command line:\\n\\npython -m xmlrpc.server\\n\\nThe client that interacts with the above server is included in Lib/xmlrpc/client.py:\\n\\nserver = ServerProxy(\"http://localhost:8000\")\\n\\ntry:\\n print(server.currentTime.getCurrentTime())\\nexcept Error as v:\\n print(\"ERROR\", v)\\n\\nmulti = MultiCall(server)\\nmulti.getData()\\nmulti.pow(2,9)\\nmulti.add(1,2)\\ntry:\\n for response in multi():\\n print(response)\\nexcept Error as v:\\n print(\"ERROR\", v)\\n\\nThis client which interacts with the demo XMLRPC server can be invoked as:\\n\\npython -m xmlrpc.client\\n\\nCGIXMLRPCRequestHandler¶\\n\\nThe CGIXMLRPCRequestHandler class can be used to handle XML-RPC requests sent to Python CGI scripts.\\n\\nExample:\\n\\nclass MyFuncs:\\n def mul(self, x, y):\\n return x * y\\n\\n\\nhandler = CGIXMLRPCRequestHandler()\\nhandler.register_function(pow)\\nhandler.register_function(lambda x,y: x+y, \\'add\\')\\nhandler.register_introspection_functions()\\nhandler.register_instance(MyFuncs())\\nhandler.handle_request()\\n\\nDocumenting XMLRPC server¶\\n\\nThese classes extend the above classes to serve HTML documentation in response to HTTP GET requests. Servers can either be free standing, using DocXMLRPCServer, or embedded in a CGI environment, using DocCGIXMLRPCRequestHandler.\\n\\nDocXMLRPCServer Objects¶\\n\\nThe DocXMLRPCServer class is derived from SimpleXMLRPCServer and provides a means of creating self-documenting, stand alone XML-RPC servers. HTTP POST requests are handled as XML-RPC method calls. HTTP GET requests are handled by generating pydoc-style HTML documentation. This allows a server to provide its own web-based documentation.\\n\\nDocCGIXMLRPCRequestHandler¶\\n\\nThe DocCGIXMLRPCRequestHandler class is derived from CGIXMLRPCRequestHandler and provides a means of creating self-documenting, XML-RPC CGI scripts. HTTP POST requests are handled as XML-RPC method calls. HTTP GET requests are handled by generating pydoc-style HTML documentation. This allows a server to provide its own web-based documentation.\\n\\nTable of Contents\\n\\nxmlrpc.server — Basic XML-RPC servers\\n\\nSimpleXMLRPCServer Objects\\n\\nSimpleXMLRPCServer Example\\n\\nCGIXMLRPCRequestHandler\\n\\nDocumenting XMLRPC server\\n\\nDocXMLRPCServer Objects\\n\\nDocCGIXMLRPCRequestHandler\\n\\nPrevious topic\\n\\nxmlrpc.client — XML-RPC client access\\n\\nNext topic\\n\\nipaddress — IPv4/IPv6 manipulation library\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nInternet Protocols and Support »\\n\\nxmlrpc.server — Basic XML-RPC servers\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\zipapp.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nSoftware Packaging and Distribution »\\n\\nzipapp — Manage executable Python zip archives\\n\\n|\\n\\nzipapp — Manage executable Python zip archives¶\\n\\nAdded in version 3.5.\\n\\nSource code: Lib/zipapp.py\\n\\nThis module provides tools to manage the creation of zip files containing Python code, which can be executed directly by the Python interpreter. The module provides both a Command-Line Interface and a Python API.\\n\\nBasic Example¶\\n\\nThe following example shows how the Command-Line Interface can be used to create an executable archive from a directory containing Python code. When run, the archive will execute the main function from the module myapp in the archive.\\n\\n$ python -m zipapp myapp -m \"myapp:main\"\\n$ python myapp.pyz\\n\\n\\nCommand-Line Interface¶\\n\\nWhen called as a program from the command line, the following form is used:\\n\\n$ python -m zipapp source [options]\\n\\nIf source is a directory, this will create an archive from the contents of source. If source is a file, it should be an archive, and it will be copied to the target archive (or the contents of its shebang line will be displayed if the –info option is specified).\\n\\nThe following options are understood:\\n\\nPython API¶\\n\\nThe module defines two convenience functions:\\n\\nExamples¶\\n\\nPack up a directory into an archive, and run it.\\n\\n$ python -m zipapp myapp\\n$ python myapp.pyz\\n\\n\\nThe same can be done using the create_archive() function:\\n\\n>>> import zipapp\\n>>> zipapp.create_archive(\\'myapp\\', \\'myapp.pyz\\')\\n\\nTo make the application directly executable on POSIX, specify an interpreter to use.\\n\\n$ python -m zipapp myapp -p \"/usr/bin/env python\"\\n$ ./myapp.pyz\\n\\n\\nTo replace the shebang line on an existing archive, create a modified archive using the create_archive() function:\\n\\n>>> import zipapp\\n>>> zipapp.create_archive(\\'old_archive.pyz\\', \\'new_archive.pyz\\', \\'/usr/bin/python3\\')\\n\\nTo update the file in place, do the replacement in memory using a BytesIO object, and then overwrite the source afterwards. Note that there is a risk when overwriting a file in place that an error will result in the loss of the original file. This code does not protect against such errors, but production code should do so. Also, this method will only work if the archive fits in memory:\\n\\n>>> import zipapp\\n>>> import io\\n>>> temp = io.BytesIO()\\n>>> zipapp.create_archive(\\'myapp.pyz\\', temp, \\'/usr/bin/python2\\')\\n>>> with open(\\'myapp.pyz\\', \\'wb\\') as f:\\n>>> f.write(temp.getvalue())\\n\\nSpecifying the Interpreter¶\\n\\nNote 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 #! line, but there are other issues to consider:\\n\\nIf 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.\\n\\nIf 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).\\n\\nThere 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.\\n\\nTypically, 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.\\n\\nCreating Standalone Applications with zipapp¶\\n\\nUsing the 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.\\n\\nThe steps to create a standalone archive are as follows:\\n\\nCreate your application in a directory as normal, so you have a myapp directory containing a __main__.py file, and any supporting application code.\\n\\nInstall all of your application’s dependencies into the myapp directory, using pip:\\n\\n$ python -m pip install -r requirements.txt --target myapp\\n\\n(this assumes you have your project requirements in a requirements.txt file - if not, you can just list the dependencies manually on the pip command line).\\n\\nPackage the application using:\\n\\n$ python -m zipapp -p \"interpreter\" myapp\\n\\nThis will produce a standalone executable, which can be run on any machine with the appropriate interpreter available. See Specifying the Interpreter for details. It can be shipped to users as a single file.\\n\\nOn Unix, the myapp.pyz file is executable as it stands. You can rename the file to remove the .pyz extension if you prefer a “plain” command name. On Windows, the myapp.pyz[w] file is executable by virtue of the fact that the Python interpreter registers the .pyz and .pyzw file extensions when installed.\\n\\nCaveats¶\\n\\nIf 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 __main__.py to include the directory containing the unzipped module in 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 sys.path at runtime, based on the user’s machine).\\n\\nThe Python Zip Application Archive Format¶\\n\\nPython has been able to execute zip files which contain a __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 __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 sys.path and thus further modules can be imported from the zip file.\\n\\nThe 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 (#!/path/to/interpreter).\\n\\nFormally, the Python zip application format is therefore:\\n\\nAn optional shebang line, containing the characters b\\'#!\\' followed by an interpreter name, and then a newline (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 sys.getfilesystemencoding() on POSIX.\\n\\nStandard zipfile data, as generated by the zipfile module. The zipfile content must include a file called __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.\\n\\nIf an application archive has a shebang line, it may have the executable bit set on POSIX systems, to allow it to be executed directly.\\n\\nThere 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.\\n\\nTable of Contents\\n\\nzipapp — Manage executable Python zip archives\\n\\nBasic Example\\n\\nCommand-Line Interface\\n\\nPython API\\n\\nExamples\\n\\nSpecifying the Interpreter\\n\\nCreating Standalone Applications with zipapp\\n\\nCaveats\\n\\nThe Python Zip Application Archive Format\\n\\nPrevious topic\\n\\nvenv — Creation of virtual environments\\n\\nNext topic\\n\\nPython Runtime Services\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nSoftware Packaging and Distribution »\\n\\nzipapp — Manage executable Python zip archives\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\zipfile.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Compression and Archiving »\\n\\nzipfile — Work with ZIP archives\\n\\n|\\n\\nzipfile — Work with ZIP archives¶\\n\\nSource code: Lib/zipfile/\\n\\nThe ZIP file format is a common archive and compression standard. This module provides tools to create, read, write, append, and list a ZIP file. Any advanced use of this module will require an understanding of the format, as defined in PKZIP Application Note.\\n\\nThis 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.\\n\\nHandling compressed archives requires optional modules such as zlib, bz2, lzma, and 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 Requirements for optional modules.\\n\\nThe module defines the following items:\\n\\nNote\\n\\nThe 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.\\n\\nSee also\\n\\nZipFile objects¶\\n\\nThe following data attributes are also available:\\n\\nPath objects¶\\n\\nPath objects expose the following features of pathlib.Path objects:\\n\\nPath objects are traversable using the / operator or joinpath.\\n\\nThe zipp project provides backports of the latest path object functionality to older Pythons. Use zipp.Path in place of zipfile.Path for early access to changes.\\n\\nPyZipFile objects¶\\n\\nThe PyZipFile constructor takes the same parameters as the ZipFile constructor, and one additional parameter, optimize.\\n\\nZipInfo objects¶\\n\\nInstances of the ZipInfo class are returned by the getinfo() and infolist() methods of ZipFile objects. Each object stores information about a single member of the ZIP archive.\\n\\nThere is one classmethod to make a ZipInfo instance for a filesystem file:\\n\\nInstances have the following methods and attributes:\\n\\nCommand-line interface¶\\n\\nThe zipfile module provides a simple command-line interface to interact with ZIP archives.\\n\\nIf you want to create a new ZIP archive, specify its name after the -c option and then list the filename(s) that should be included:\\n\\n$ python -m zipfile -c monty.zip spam.txt eggs.txt\\n\\nPassing a directory is also acceptable:\\n\\n$ python -m zipfile -c monty.zip life-of-brian_1979/\\n\\nIf you want to extract a ZIP archive into the specified directory, use the -e option:\\n\\n$ python -m zipfile -e monty.zip target-dir/\\n\\nFor a list of the files in a ZIP archive, use the -l option:\\n\\n$ python -m zipfile -l monty.zip\\n\\nCommand-line options¶\\n\\nDecompression pitfalls¶\\n\\nThe extraction in zipfile module might fail due to some pitfalls listed below.\\n\\nFrom file itself¶\\n\\nDecompression may fail due to incorrect password / CRC checksum / ZIP format or unsupported compression method / decryption.\\n\\nFile system limitations¶\\n\\nExceeding 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.\\n\\nResources limitations¶\\n\\nThe lack of memory or disk volume would lead to decompression failed. For example, decompression bombs (aka ZIP bomb) apply to zipfile library that can cause disk volume exhaustion.\\n\\nInterruption¶\\n\\nInterruption during the decompression, such as pressing control-C or killing the decompression process may result in incomplete decompression of the archive.\\n\\nDefault behaviors of extraction¶\\n\\nNot knowing the default extraction behaviors can cause unexpected decompression results. For example, when extracting the same archive twice, it overwrites files without asking.\\n\\nTable of Contents\\n\\nzipfile — Work with ZIP archives\\n\\nZipFile objects\\n\\nPath objects\\n\\nPyZipFile objects\\n\\nZipInfo objects\\n\\nCommand-line interface\\n\\nCommand-line options\\n\\nDecompression pitfalls\\n\\nFrom file itself\\n\\nFile system limitations\\n\\nResources limitations\\n\\nInterruption\\n\\nDefault behaviors of extraction\\n\\nPrevious topic\\n\\nlzma — Compression using the LZMA algorithm\\n\\nNext topic\\n\\ntarfile — Read and write tar archive files\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Compression and Archiving »\\n\\nzipfile — Work with ZIP archives\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\zipimport.html'}, page_content=\"Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nImporting Modules »\\n\\nzipimport — Import modules from Zip archives\\n\\n|\\n\\nzipimport — Import modules from Zip archives¶\\n\\nSource code: Lib/zipimport.py\\n\\nThis module adds the ability to import Python modules (*.py, *.pyc) and packages from ZIP-format archives. It is usually not needed to use the zipimport module explicitly; it is automatically used by the built-in import mechanism for sys.path items that are paths to ZIP archives.\\n\\nTypically, sys.path is a list of directory names as strings. This module also allows an item of sys.path to be a string naming a ZIP file archive. The ZIP archive can contain a subdirectory structure to support package imports, and a path within the archive can be specified to only import from a subdirectory. For example, the path example.zip/lib/ would only import from the lib/ subdirectory within the archive.\\n\\nAny files may be present in the ZIP archive, but importers are only invoked for .py and .pyc files. ZIP import of dynamic modules (.pyd, .so) is disallowed. Note that if an archive only contains .py files, Python will not attempt to modify the archive by adding the corresponding .pyc file, meaning that if a ZIP archive doesn’t contain .pyc files, importing may be rather slow.\\n\\nChanged in version 3.15: Zstandard (zstd) compressed zip file entries are supported.\\n\\nChanged in version 3.13: ZIP64 is supported\\n\\nChanged in version 3.8: Previously, ZIP archives with an archive comment were not supported.\\n\\nSee also\\n\\nThis module defines an exception:\\n\\nzipimporter Objects¶\\n\\nzipimporter is the class for importing ZIP files.\\n\\nExamples¶\\n\\nHere is an example that imports a module from a ZIP archive - note that the zipimport module is not explicitly used.\\n\\n$ unzip -l example_archive.zip\\nArchive: example_archive.zip\\n Length Date Time Name\\n -------- ---- ---- ----\\n 8467 01-01-00 12:30 example.py\\n -------- -------\\n 8467 1 file\\n\\n>>> import sys\\n>>> # Add the archive to the front of the module search path\\n>>> sys.path.insert(0, 'example_archive.zip')\\n>>> import example\\n>>> example.__file__\\n'example_archive.zip/example.py'\\n\\nTable of Contents\\n\\nzipimport — Import modules from Zip archives\\n\\nzipimporter Objects\\n\\nExamples\\n\\nPrevious topic\\n\\nImporting Modules\\n\\nNext topic\\n\\npkgutil — Package extension utility\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nImporting Modules »\\n\\nzipimport — Import modules from Zip archives\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.\"), Document(metadata={'source': '..\\\\..\\\\docs\\\\zlib.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Compression and Archiving »\\n\\nzlib — Compression compatible with gzip\\n\\n|\\n\\nzlib — Compression compatible with gzip¶\\n\\nFor applications that require data compression, the functions in this module allow compression and decompression, using the zlib library.\\n\\nThis is an 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 Requirements for optional modules.\\n\\nzlib’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 for authoritative information.\\n\\nFor reading and writing .gz files see the gzip module.\\n\\nThe available exception and functions in this module are:\\n\\nCompression objects support the following methods:\\n\\nChanged in version 3.8: Added copy.copy() and copy.deepcopy() support to compression objects.\\n\\nDecompression objects support the following methods and attributes:\\n\\nChanged in version 3.8: Added copy.copy() and copy.deepcopy() support to decompression objects.\\n\\nThe following constants are available to configure compression and decompression behavior:\\n\\nInformation about the version of the zlib library in use is available through the following constants:\\n\\nSee also\\n\\nIn case gzip (de)compression is a bottleneck, the python-isal package speeds up (de)compression with a mostly compatible API.\\n\\nPrevious topic\\n\\ncompression.zstd — Compression compatible with the Zstandard format\\n\\nNext topic\\n\\ngzip — Support for gzip files\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Compression and Archiving »\\n\\nzlib — Compression compatible with gzip\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\zoneinfo.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Types »\\n\\nzoneinfo — IANA time zone support\\n\\n|\\n\\nzoneinfo — IANA time zone support¶\\n\\nAdded in version 3.9.\\n\\nSource code: Lib/zoneinfo\\n\\nThe zoneinfo module provides a concrete time zone implementation to support the IANA time zone database as originally specified in PEP 615. By default, 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 package available on PyPI.\\n\\nSee also\\n\\nAvailability: not WASI.\\n\\nThis module does not work or is not available on WebAssembly. See WebAssembly platforms for more information.\\n\\nUsing ZoneInfo¶\\n\\nZoneInfo is a concrete implementation of the datetime.tzinfo abstract base class, and is intended to be attached to tzinfo, either via the constructor, the datetime.replace method or datetime.astimezone:\\n\\n>>> from zoneinfo import ZoneInfo\\n>>> from datetime import datetime, timedelta\\n\\n>>> dt = datetime(2020, 10, 31, 12, tzinfo=ZoneInfo(\"America/Los_Angeles\"))\\n>>> print(dt)\\n2020-10-31 12:00:00-07:00\\n\\n>>> dt.tzname()\\n\\'PDT\\'\\n\\nDatetimes constructed in this way are compatible with datetime arithmetic and handle daylight saving time transitions with no further intervention:\\n\\n>>> dt_add = dt + timedelta(days=1)\\n\\n>>> print(dt_add)\\n2020-11-01 12:00:00-08:00\\n\\n>>> dt_add.tzname()\\n\\'PST\\'\\n\\nThese time zones also support the fold attribute introduced in PEP 495. 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 fold=0, and the offset after the transition is used when fold=1, for example:\\n\\n>>> dt = datetime(2020, 11, 1, 1, tzinfo=ZoneInfo(\"America/Los_Angeles\"))\\n>>> print(dt)\\n2020-11-01 01:00:00-07:00\\n\\n>>> print(dt.replace(fold=1))\\n2020-11-01 01:00:00-08:00\\n\\nWhen converting from another time zone, the fold will be set to the correct value:\\n\\n>>> from datetime import timezone\\n>>> LOS_ANGELES = ZoneInfo(\"America/Los_Angeles\")\\n>>> dt_utc = datetime(2020, 11, 1, 8, tzinfo=timezone.utc)\\n\\n>>> # Before the PDT -> PST transition\\n>>> print(dt_utc.astimezone(LOS_ANGELES))\\n2020-11-01 01:00:00-07:00\\n\\n>>> # After the PDT -> PST transition\\n>>> print((dt_utc + timedelta(hours=1)).astimezone(LOS_ANGELES))\\n2020-11-01 01:00:00-08:00\\n\\nData sources¶\\n\\nThe 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, 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 ZoneInfo will raise ZoneInfoNotFoundError.\\n\\nConfiguring the data sources¶\\n\\nWhen ZoneInfo(key) is called, the constructor first searches the directories specified in TZPATH for a file matching key, and on failure looks for a match in the tzdata package. This behavior can be configured in three ways:\\n\\nThe default TZPATH when not otherwise specified can be configured at compile time.\\n\\nTZPATH can be configured using an environment variable.\\n\\nAt runtime, the search path can be manipulated using the reset_tzpath() function.\\n\\nCompile-time configuration¶\\n\\nThe default 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 TZPATH (or, more likely, the configure flag --with-tzpath), which should be a string delimited by os.pathsep.\\n\\nOn all platforms, the configured value is available as the TZPATH key in sysconfig.get_config_var().\\n\\nEnvironment configuration¶\\n\\nWhen initializing TZPATH (either at import time or whenever reset_tzpath() is called with no arguments), the zoneinfo module will use the environment variable PYTHONTZPATH, if it exists, to set the search path.\\n\\nTo set the system to ignore the system data and use the tzdata package instead, set PYTHONTZPATH=\"\".\\n\\nRuntime configuration¶\\n\\nThe TZ search path can also be configured at runtime using the 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).\\n\\nThe ZoneInfo class¶\\n\\nThe ZoneInfo class has two alternate constructors:\\n\\nThe following class methods are also available:\\n\\nThe class has one attribute:\\n\\nString representations¶\\n\\nThe string representation returned when calling str on a ZoneInfo object defaults to using the ZoneInfo.key attribute (see the note on usage in the attribute documentation):\\n\\n>>> zone = ZoneInfo(\"Pacific/Kwajalein\")\\n>>> str(zone)\\n\\'Pacific/Kwajalein\\'\\n\\n>>> dt = datetime(2020, 4, 1, 3, 15, tzinfo=zone)\\n>>> f\"{dt.isoformat()} [{dt.tzinfo}]\"\\n\\'2020-04-01T03:15:00+12:00 [Pacific/Kwajalein]\\'\\n\\nFor objects constructed from a file without specifying a key parameter, str falls back to calling repr(). ZoneInfo’s repr is implementation-defined and not necessarily stable between versions, but it is guaranteed not to be a valid ZoneInfo key.\\n\\nPickle serialization¶\\n\\nRather than serializing all transition data, ZoneInfo objects are serialized by key, and ZoneInfo objects constructed from files (even those with a value for key specified) cannot be pickled.\\n\\nThe behavior of a ZoneInfo file depends on how it was constructed:\\n\\nZoneInfo(key): When constructed with the primary constructor, a 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 europe_berlin_pkl is a string containing a pickle constructed from ZoneInfo(\"Europe/Berlin\"), one would expect the following behavior:\\n\\n>>> a = ZoneInfo(\"Europe/Berlin\")\\n>>> b = pickle.loads(europe_berlin_pkl)\\n>>> a is b\\nTrue\\n\\nZoneInfo.no_cache(key): When constructed from the cache-bypassing constructor, the ZoneInfo object is also serialized by key, but when deserialized, the deserializing process uses the cache bypassing constructor. If europe_berlin_pkl_nc is a string containing a pickle constructed from ZoneInfo.no_cache(\"Europe/Berlin\"), one would expect the following behavior:\\n\\n>>> a = ZoneInfo(\"Europe/Berlin\")\\n>>> b = pickle.loads(europe_berlin_pkl_nc)\\n>>> a is b\\nFalse\\n\\nZoneInfo.from_file(file_obj, /, key=None): When constructed from a file, the ZoneInfo object raises an exception on pickling. If an end user wants to pickle a 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.\\n\\nThis 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 ZoneInfo pickled in an environment with a different version of the time zone data.\\n\\nFunctions¶\\n\\nGlobals¶\\n\\nExceptions and warnings¶\\n\\nTable of Contents\\n\\nzoneinfo — IANA time zone support\\n\\nUsing ZoneInfo\\n\\nData sources\\n\\nConfiguring the data sources\\n\\nCompile-time configuration\\n\\nEnvironment configuration\\n\\nRuntime configuration\\n\\nThe ZoneInfo class\\n\\nString representations\\n\\nPickle serialization\\n\\nFunctions\\n\\nGlobals\\n\\nExceptions and warnings\\n\\nPrevious topic\\n\\ndatetime — Basic date and time types\\n\\nNext topic\\n\\ncalendar — General calendar-related functions\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nData Types »\\n\\nzoneinfo — IANA time zone support\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\_thread.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nConcurrent Execution »\\n\\n_thread — Low-level threading API\\n\\n|\\n\\n_thread — Low-level threading API¶\\n\\nThis module provides low-level primitives for working with multiple threads (also called light-weight processes or tasks) — multiple threads of control sharing their global data space. For synchronization, simple locks (also called mutexes or binary semaphores) are provided. The threading module provides an easier to use and higher-level threading API built on top of this module.\\n\\nChanged in version 3.7: This module used to be optional, it is now always available.\\n\\nThis module defines the following constants and functions:\\n\\nLock objects have the following methods:\\n\\nIn addition to these methods, lock objects can also be used via the with statement, e.g.:\\n\\nimport _thread\\n\\na_lock = _thread.allocate_lock()\\n\\nwith a_lock:\\n print(\"a_lock is locked while this executes\")\\n\\nCaveats:\\n\\nInterrupts always go to the main thread (the KeyboardInterrupt exception will be received by that thread.)\\n\\nCalling sys.exit() or raising the SystemExit exception is equivalent to calling _thread.exit().\\n\\nWhen the main thread exits, it is system defined whether the other threads survive. On most systems, they are killed without executing try … finally clauses or executing object destructors.\\n\\nPrevious topic\\n\\ncontextvars — Context Variables\\n\\nNext topic\\n\\nNetworking and Interprocess Communication\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nConcurrent Execution »\\n\\n_thread — Low-level threading API\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\__future__.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Runtime Services »\\n\\n__future__ — Future statement definitions\\n\\n|\\n\\n__future__ — Future statement definitions¶\\n\\nSource code: Lib/__future__.py\\n\\nImports of the form from __future__ import feature are called future statements. These are special-cased by the Python compiler to allow the use of new Python features in modules containing the future statement before the release in which the feature becomes standard.\\n\\nWhile these future statements are given additional special meaning by the Python compiler, they are still executed like any other import statement and the __future__ exists and is handled by the import system the same way any other Python module would be. This design serves three purposes:\\n\\nTo avoid confusing existing tools that analyze import statements and expect to find the modules they’re importing.\\n\\nTo 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 __future__ and examining its contents.\\n\\nTo ensure that future statements run under releases prior to Python 2.1 at least yield runtime exceptions (the import of __future__ will fail, because there was no module of that name prior to 2.1).\\n\\nModule Contents¶\\n\\nNo feature description will ever be deleted from __future__. Since its introduction in Python 2.1 the following features have found their way into the language using this mechanism:\\n\\nfeature optional in mandatory in effect __future__. nested_scopes ¶ 2.1.0b1 2.2 PEP 227 : Statically Nested Scopes __future__. generators ¶ 2.2.0a1 2.3 PEP 255 : Simple Generators __future__. division ¶ 2.2.0a2 3.0 PEP 238 : Changing the Division Operator __future__. absolute_import ¶ 2.5.0a1 3.0 PEP 328 : Imports: Multi-Line and Absolute/Relative __future__. with_statement ¶ 2.5.0a1 2.6 PEP 343 : The “with” Statement __future__. print_function ¶ 2.6.0a2 3.0 PEP 3105 : Make print a function __future__. unicode_literals ¶ 2.6.0a2 3.0 PEP 3112 : Bytes literals in Python 3000 __future__. generator_stop ¶ 3.5.0b1 3.7 PEP 479 : StopIteration handling inside generators __future__. annotations ¶ 3.7.0b1 Never [ 1 ] PEP 563 : Postponed evaluation of annotations , PEP 649 : Deferred evaluation of annotations using descriptors\\n\\n[1]\\n\\nfrom __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 PEP 649 and PEP 749.\\n\\nSee also\\n\\nTable of Contents\\n\\n__future__ — Future statement definitions\\n\\nModule Contents\\n\\nPrevious topic\\n\\ntraceback — Print or retrieve a stack traceback\\n\\nNext topic\\n\\ngc — Garbage Collector interface\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Runtime Services »\\n\\n__future__ — Future statement definitions\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.'), Document(metadata={'source': '..\\\\..\\\\docs\\\\__main__.html'}, page_content='Navigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Runtime Services »\\n\\n__main__ — Top-level code environment\\n\\n|\\n\\n__main__ — Top-level code environment¶\\n\\nIn Python, the special name __main__ is used for two important constructs:\\n\\nthe name of the top-level environment of the program, which can be checked using the __name__ == \\'__main__\\' expression; and\\n\\nthe __main__.py file in Python packages.\\n\\nBoth of these mechanisms are related to Python modules; how users interact with them and how they interact with each other. They are explained in detail below. If you’re new to Python modules, see the tutorial section Modules for an introduction.\\n\\n__name__ == \\'__main__\\'¶\\n\\nWhen a Python module or package is imported, __name__ is set to the module’s name. Usually, this is the name of the Python file itself without the .py extension:\\n\\n>>> import configparser\\n>>> configparser.__name__\\n\\'configparser\\'\\n\\nIf the file is part of a package, __name__ will also include the parent package’s path:\\n\\n>>> from concurrent.futures import process\\n>>> process.__name__\\n\\'concurrent.futures.process\\'\\n\\nHowever, if the module is executed in the top-level code environment, its __name__ is set to the string \\'__main__\\'.\\n\\nWhat is the “top-level code environment”?¶\\n\\n__main__ is the name of the environment where top-level code is run. “Top-level code” is the first user-specified Python module that starts running. It’s “top-level” because it imports all other modules that the program needs. Sometimes “top-level code” is called an entry point to the application.\\n\\nThe top-level code environment can be:\\n\\nthe scope of an interactive prompt:\\n\\n>>> __name__\\n\\'__main__\\'\\n\\nthe Python module passed to the Python interpreter as a file argument:\\n\\n$ python helloworld.py\\nHello, world!\\n\\nthe Python module or package passed to the Python interpreter with the -m argument:\\n\\n$ python -m tarfile\\nusage: tarfile.py [-h] [-v] (...)\\n\\nPython code read by the Python interpreter from standard input:\\n\\n$ echo \"import this\" | python\\nThe Zen of Python, by Tim Peters\\n\\nBeautiful is better than ugly.\\nExplicit is better than implicit.\\n...\\n\\nPython code passed to the Python interpreter with the -c argument:\\n\\n$ python -c \"import this\"\\nThe Zen of Python, by Tim Peters\\n\\nBeautiful is better than ugly.\\nExplicit is better than implicit.\\n...\\n\\nIn each of these situations, the top-level module’s __name__ is set to \\'__main__\\'.\\n\\nAs a result, a module can discover whether or not it is running in the top-level environment by checking its own __name__, which allows a common idiom for conditionally executing code when the module is not initialized from an import statement:\\n\\nif __name__ == \\'__main__\\':\\n # Execute when the module is not initialized from an import statement.\\n ...\\n\\nSee also\\n\\nFor a more detailed look at how __name__ is set in all situations, see the tutorial section Modules.\\n\\nIdiomatic Usage¶\\n\\nSome modules contain code that is intended for script use only, like parsing command-line arguments or fetching data from standard input. If a module like this was imported from a different module, for example to unit test it, the script code would unintentionally execute as well.\\n\\nThis is where using the if __name__ == \\'__main__\\' code block comes in handy. Code within this block won’t run unless the module is executed in the top-level environment.\\n\\nPutting as few statements as possible in the block below if __name__ == \\'__main__\\' can improve code clarity and correctness. Most often, a function named main encapsulates the program’s primary behavior:\\n\\n# echo.py\\n\\nimport shlex\\nimport sys\\n\\ndef echo(phrase: str) -> None:\\n \"\"\"A dummy wrapper around print.\"\"\"\\n # for demonstration purposes, you can imagine that there is some\\n # valuable and reusable logic inside this function\\n print(phrase)\\n\\ndef main() -> int:\\n \"\"\"Echo the input arguments to standard output\"\"\"\\n phrase = shlex.join(sys.argv)\\n echo(phrase)\\n return 0\\n\\nif __name__ == \\'__main__\\':\\n sys.exit(main()) # next section explains the use of sys.exit\\n\\nNote that if the module didn’t encapsulate code inside the main function but instead put it directly within the if __name__ == \\'__main__\\' block, the phrase variable would be global to the entire module. This is error-prone as other functions within the module could be unintentionally using the global variable instead of a local name. A main function solves this problem.\\n\\nUsing a main function has the added benefit of the echo function itself being isolated and importable elsewhere. When echo.py is imported, the echo and main functions will be defined, but neither of them will be called, because __name__ != \\'__main__\\'.\\n\\nPackaging Considerations¶\\n\\nmain functions are often used to create command-line tools by specifying them as entry points for console scripts. When this is done, pip inserts the function call into a template script, where the return value of main is passed into sys.exit(). For example:\\n\\nsys.exit(main())\\n\\nSince the call to main is wrapped in sys.exit(), the expectation is that your function will return some value acceptable as an input to sys.exit(); typically, an integer or None (which is implicitly returned if your function does not have a return statement).\\n\\nBy proactively following this convention ourselves, our module will have the same behavior when run directly (i.e. python echo.py) as it will have if we later package it as a console script entry-point in a pip-installable package.\\n\\nIn particular, be careful about returning strings from your main function. sys.exit() will interpret a string argument as a failure message, so your program will have an exit code of 1, indicating failure, and the string will be written to sys.stderr. The echo.py example from earlier exemplifies using the sys.exit(main()) convention.\\n\\nSee also\\n\\nPython Packaging User Guide contains a collection of tutorials and references on how to distribute and install Python packages with modern tools.\\n\\n__main__.py in Python Packages¶\\n\\nIf you are not familiar with Python packages, see section Packages of the tutorial. Most commonly, the __main__.py file is used to provide a command-line interface for a package. Consider the following hypothetical package, “bandclass”:\\n\\nbandclass\\n ├── __init__.py\\n ├── __main__.py\\n └── student.py\\n\\n__main__.py will be executed when the package itself is invoked directly from the command line using the -m flag. For example:\\n\\n$ python -m bandclass\\n\\nThis command will cause __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:\\n\\n# bandclass/__main__.py\\n\\nimport sys\\nfrom .student import search_students\\n\\nstudent_name = sys.argv[1] if len(sys.argv) >= 2 else \\'\\'\\nprint(f\\'Found student: {search_students(student_name)}\\')\\n\\nNote that 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 Intra-package References in the Modules section of the tutorial.\\n\\nIdiomatic Usage¶\\n\\nThe content of __main__.py typically isn’t fenced with an 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.\\n\\nIf used, an if __name__ == \\'__main__\\' block will still work as expected for a __main__.py file within a package, because its __name__ attribute will include the package’s path if imported:\\n\\n>>> import asyncio.__main__\\n>>> asyncio.__main__.__name__\\n\\'asyncio.__main__\\'\\n\\nThis won’t work for __main__.py files in the root directory of a .zip file though. Hence, for consistency, a minimal __main__.py without a __name__ check is preferred.\\n\\nSee also\\n\\nSee venv for an example of a package with a minimal __main__.py in the standard library. It doesn’t contain a if __name__ == \\'__main__\\' block. You can invoke it with python -m venv [directory].\\n\\nSee runpy for more details on the -m flag to the interpreter executable.\\n\\nSee zipapp for how to run applications packaged as .zip files. In this case Python looks for a __main__.py file in the root directory of the archive.\\n\\nimport __main__¶\\n\\nRegardless of which module a Python program was started with, other modules running within that same program can import the top-level environment’s scope (namespace) by importing the __main__ module. This doesn’t import a __main__.py file but rather whichever module that received the special name \\'__main__\\'.\\n\\nHere is an example module that consumes the __main__ namespace:\\n\\n# namely.py\\n\\nimport __main__\\n\\ndef did_user_define_their_name():\\n return \\'my_name\\' in dir(__main__)\\n\\ndef print_user_name():\\n if not did_user_define_their_name():\\n raise ValueError(\\'Define the variable `my_name`!\\')\\n\\n print(__main__.my_name)\\n\\nExample usage of this module could be as follows:\\n\\n# start.py\\n\\nimport sys\\n\\nfrom namely import print_user_name\\n\\n# my_name = \"Dinsdale\"\\n\\ndef main():\\n try:\\n print_user_name()\\n except ValueError as ve:\\n return str(ve)\\n\\nif __name__ == \"__main__\":\\n sys.exit(main())\\n\\nNow, if we started our program, the result would look like this:\\n\\n$ python start.py\\nDefine the variable `my_name`!\\n\\nThe exit code of the program would be 1, indicating an error. Uncommenting the line with my_name = \"Dinsdale\" fixes the program and now it exits with status code 0, indicating success:\\n\\n$ python start.py\\nDinsdale\\n\\nNote that importing __main__ doesn’t cause any issues with unintentionally running top-level code meant for script use which is put in the if __name__ == \"__main__\" block of the start module. Why does this work?\\n\\nPython inserts an empty __main__ module in sys.modules at interpreter startup, and populates it by running top-level code. In our example this is the start module which runs line by line and imports namely. In turn, namely imports __main__ (which is really start). That’s an import cycle! Fortunately, since the partially populated __main__ module is present in sys.modules, Python passes that to namely. See Special considerations for __main__ in the import system’s reference for details on how this works.\\n\\nThe Python REPL is another example of a “top-level environment”, so anything defined in the REPL becomes part of the __main__ scope:\\n\\n>>> import namely\\n>>> namely.did_user_define_their_name()\\nFalse\\n>>> namely.print_user_name()\\nTraceback (most recent call last):\\n...\\nValueError: Define the variable `my_name`!\\n>>> my_name = \\'Jabberwocky\\'\\n>>> namely.did_user_define_their_name()\\nTrue\\n>>> namely.print_user_name()\\nJabberwocky\\n\\nThe __main__ scope is used in the implementation of pdb and rlcompleter.\\n\\nTable of Contents\\n\\n__main__ — Top-level code environment\\n\\n__name__ == \\'__main__\\'\\n\\nWhat is the “top-level code environment”?\\n\\nIdiomatic Usage\\n\\nPackaging Considerations\\n\\n__main__.py in Python Packages\\n\\nIdiomatic Usage\\n\\nimport __main__\\n\\nPrevious topic\\n\\nbuiltins — Built-in objects\\n\\nNext topic\\n\\nwarnings — Warning control\\n\\nThis page\\n\\nReport a bug\\n\\nImprove this page\\n\\nShow source\\n\\nNavigation\\n\\nindex\\n\\nmodules |\\n\\nnext |\\n\\nprevious |\\n\\nPython logo\\n\\nPython »\\n\\n3.15.0a6 Documentation »\\n\\nThe Python Standard Library »\\n\\nPython Runtime Services »\\n\\n__main__ — Top-level code environment\\n\\n|\\n\\n© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.')]\n" ] } ], "source": [ "base_dir = Path(\"../../docs\")\n", "paths = list(base_dir.rglob(\"*\"))\n", "\n", "def load_docs(paths):\n", " all_docs = []\n", " for p in paths:\n", " if not p.is_file():\n", " continue\n", "\n", " ext = p.suffix.lower()\n", " try:\n", " if ext == \".html\":\n", " # Try UnstructuredHTMLLoader first, fallback to BSHTMLLoader if it fails\n", " try:\n", " loader = UnstructuredHTMLLoader(p)\n", " docs = loader.load()\n", " except (AttributeError, Exception) as e:\n", " # Fallback to BSHTMLLoader for problematic HTML files\n", " print(f\"Warning: UnstructuredHTMLLoader failed for {p}, using BSHTMLLoader instead. Error: {type(e).__name__}\")\n", " loader = BSHTMLLoader(p)\n", " docs = loader.load()\n", " elif ext == \".md\":\n", " loader = UnstructuredMarkdownLoader(p)\n", " docs = loader.load()\n", " elif ext == \".txt\":\n", " loader = TextLoader(p)\n", " docs = loader.load()\n", " else:\n", " print(f\"Skipping {p} because it is not a supported file type\")\n", " continue\n", " \n", " all_docs.extend(docs)\n", " except Exception as e:\n", " print(f\"Error loading {p}: {type(e).__name__}: {e}\")\n", " continue\n", " \n", " return all_docs\n", "\n", "print(load_docs(paths))\n" ] }, { "cell_type": "code", "execution_count": 35, "id": "75ecf5a3", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "page_content='Navigation\n", "\n", "index\n", "\n", "modules |\n", "\n", "next |\n", "\n", "previous |\n", "\n", "Python logo\n", "\n", "Python »\n", "\n", "3.15.0a6 Documentation »\n", "\n", "The Python Standard Library »\n", "\n", "Python Runtime Services »\n", "\n", "abc — Abstract Base Classes\n", "\n", "|\n", "\n", "abc — Abstract Base Classes¶\n", "\n", "Source code: Lib/abc.py\n", "\n", "This module provides the infrastructure for defining abstract base classes (ABCs) in Python, as outlined in PEP 3119; see the PEP for why this was added to Python. (See also PEP 3141 and the numbers module regarding a type hierarchy for numbers based on ABCs.)\n", "\n", "The collections module has some concrete classes that derive from ABCs; these can, of course, be further derived. In addition, the collections.abc submodule has some ABCs that can be used to test whether a class or instance provides a particular interface, for example, if it is hashable or if it is a mapping.\n", "\n", "This module provides the metaclass ABCMeta for defining ABCs and a helper class ABC to alternatively define ABCs through inheritance:\n", "\n", "The abc module also provides the following decorator:\n", "\n", "The abc module also supports the following legacy decorators:\n", "\n", "The abc module also provides the following functions:\n", "\n", "Footnotes\n", "\n", "[1]\n", "\n", "C++ programmers should note that Python’s virtual base class concept is not the same as C++’s.\n", "\n", "Previous topic\n", "\n", "contextlib — Utilities for with-statement contexts\n", "\n", "Next topic\n", "\n", "atexit — Exit handlers\n", "\n", "This page\n", "\n", "Report a bug\n", "\n", "Improve this page\n", "\n", "Show source\n", "\n", "Navigation\n", "\n", "index\n", "\n", "modules |\n", "\n", "next |\n", "\n", "previous |\n", "\n", "Python logo\n", "\n", "Python »\n", "\n", "3.15.0a6 Documentation »' metadata={'source': '..\\\\..\\\\docs\\\\abc.html'}\n" ] } ], "source": [ "splitter = RecursiveCharacterTextSplitter(chunk_size=1500, chunk_overlap=200)\n", "texts = splitter.split_documents(load_docs(paths))\n", "print(texts[0])" ] }, { "cell_type": "code", "execution_count": 37, "id": "dbf4aa0e", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "page_content='Next topic\n", "\n", "atexit — Exit handlers\n", "\n", "This page\n", "\n", "Report a bug\n", "\n", "Improve this page\n", "\n", "Show source\n", "\n", "Navigation\n", "\n", "index\n", "\n", "modules |\n", "\n", "next |\n", "\n", "previous |\n", "\n", "Python logo\n", "\n", "Python »\n", "\n", "3.15.0a6 Documentation »\n", "\n", "The Python Standard Library »\n", "\n", "Python Runtime Services »\n", "\n", "abc — Abstract Base Classes\n", "\n", "|\n", "\n", "© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Mar 10, 2026 (08:58 UTC). Found a bug? Created using Sphinx 8.2.3.' metadata={'source': '..\\\\..\\\\docs\\\\abc.html'}\n" ] } ], "source": [ "print(texts[1])" ] }, { "cell_type": "code", "execution_count": 38, "id": "3dada678", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Loading weights: 100%|██████████| 103/103 [00:00<00:00, 2848.21it/s]\n", "\u001b[1mBertModel LOAD REPORT\u001b[0m from: sentence-transformers/all-MiniLM-L6-v2\n", "Key | Status | | \n", "------------------------+------------+--+-\n", "embeddings.position_ids | UNEXPECTED | | \n", "\n", "\u001b[3mNotes:\n", "- UNEXPECTED\u001b[3m\t:can be ignored when loading from different task/architecture; not ok if you expect identical arch.\u001b[0m\n" ] } ], "source": [ "model = HuggingFaceEmbeddings(model_name=\"all-MiniLM-L6-v2\")\n", "\n", "# Chroma.from_documents() expects the embedding MODEL, not pre-computed embeddings\n", "# It will automatically extract text from Document objects and embed them\n", "vectorstore = Chroma.from_documents(\n", " documents=texts,\n", " embedding=model, # Pass the model, not embeddings\n", " persist_directory=\"chroma_db\",\n", ")" ] }, { "cell_type": "code", "execution_count": null, "id": "5a3d4933", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "c4b7bd60", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "venv (3.13.5)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.13.5" } }, "nbformat": 4, "nbformat_minor": 5 }