Python Documentation contents
- What’s New in Python
- What’s New In Python 3.9
- Summary – Release highlights
- You should check for DeprecationWarning in your code
- New Features
- Other Language Changes
- New Modules
- Improved Modules
- ast
- asyncio
- compileall
- concurrent.futures
- curses
- datetime
- distutils
- fcntl
- ftplib
- gc
- hashlib
- http
- IDLE and idlelib
- imaplib
- importlib
- inspect
- ipaddress
- math
- multiprocessing
- nntplib
- os
- pathlib
- pdb
- poplib
- pprint
- pydoc
- random
- signal
- smtplib
- socket
- time
- sys
- tempfile
- tracemalloc
- typing
- unicodedata
- venv
- xml
- Optimizations
- Deprecated
- Removed
- Porting to Python 3.9
- Build Changes
- C API Changes
- Notable changes in Python 3.9.1
- Notable changes in Python 3.9.2
- Notable changes in Python 3.9.3
- Notable changes in Python 3.9.5
- Notable security feature in 3.9.14
- Notable Changes in 3.9.17
- Notable changes in 3.9.20
- Notable changes in 3.9.23
- What’s New In Python 3.8
- Summary – Release highlights
- New Features
- Assignment expressions
- Positional-only parameters
- Parallel filesystem cache for compiled bytecode files
- Debug build uses the same ABI as release build
- f-strings support
=for self-documenting expressions and debugging - PEP 578: Python Runtime Audit Hooks
- PEP 587: Python Initialization Configuration
- PEP 590: Vectorcall: a fast calling protocol for CPython
- Pickle protocol 5 with out-of-band data buffers
- Other Language Changes
- New Modules
- Improved Modules
- ast
- asyncio
- builtins
- collections
- cProfile
- csv
- curses
- ctypes
- datetime
- functools
- gc
- gettext
- gzip
- IDLE and idlelib
- inspect
- io
- itertools
- json.tool
- logging
- math
- mmap
- multiprocessing
- os
- os.path
- pathlib
- pickle
- plistlib
- pprint
- py_compile
- shlex
- shutil
- socket
- ssl
- statistics
- sys
- tarfile
- threading
- tokenize
- tkinter
- time
- typing
- unicodedata
- unittest
- venv
- weakref
- xml
- xmlrpc
- Optimizations
- Build and C API Changes
- Deprecated
- API and Feature Removals
- Porting to Python 3.8
- Notable changes in Python 3.8.1
- Notable changes in Python 3.8.8
- Notable changes in Python 3.8.12
- What’s New In Python 3.7
- Summary – Release Highlights
- New Features
- PEP 563: Postponed Evaluation of Annotations
- PEP 538: Legacy C Locale Coercion
- PEP 540: Forced UTF-8 Runtime Mode
- PEP 553: Built-in
breakpoint() - PEP 539: New C API for Thread-Local Storage
- PEP 562: Customization of Access to Module Attributes
- PEP 564: New Time Functions With Nanosecond Resolution
- PEP 565: Show DeprecationWarning in
__main__ - PEP 560: Core Support for
typingmodule and Generic Types - PEP 552: Hash-based .pyc Files
- PEP 545: Python Documentation Translations
- Python Development Mode (-X dev)
- Other Language Changes
- New Modules
- Improved Modules
- argparse
- asyncio
- binascii
- calendar
- collections
- compileall
- concurrent.futures
- contextlib
- cProfile
- crypt
- datetime
- dbm
- decimal
- dis
- distutils
- enum
- functools
- gc
- hmac
- http.client
- http.server
- idlelib and IDLE
- importlib
- io
- ipaddress
- itertools
- locale
- logging
- math
- mimetypes
- msilib
- multiprocessing
- os
- pathlib
- pdb
- py_compile
- pydoc
- queue
- re
- signal
- socket
- socketserver
- sqlite3
- ssl
- string
- subprocess
- sys
- time
- tkinter
- tracemalloc
- types
- unicodedata
- unittest
- unittest.mock
- urllib.parse
- uu
- uuid
- warnings
- xml.etree
- xmlrpc.server
- zipapp
- zipfile
- C API Changes
- Build Changes
- Optimizations
- Other CPython Implementation Changes
- Deprecated Python Behavior
- Deprecated Python modules, functions and methods
- Deprecated functions and types of the C API
- Platform Support Removals
- API and Feature Removals
- Module Removals
- Windows-only Changes
- Porting to Python 3.7
- Notable changes in Python 3.7.1
- Notable changes in Python 3.7.2
- Notable changes in Python 3.7.6
- Notable changes in Python 3.7.10
- What’s New In Python 3.6
- Summary – Release highlights
- New Features
- PEP 498: Formatted string literals
- PEP 526: Syntax for variable annotations
- PEP 515: Underscores in Numeric Literals
- PEP 525: Asynchronous Generators
- PEP 530: Asynchronous Comprehensions
- PEP 487: Simpler customization of class creation
- PEP 487: Descriptor Protocol Enhancements
- PEP 519: Adding a file system path protocol
- PEP 495: Local Time Disambiguation
- PEP 529: Change Windows filesystem encoding to UTF-8
- PEP 528: Change Windows console encoding to UTF-8
- PEP 520: Preserving Class Attribute Definition Order
- PEP 468: Preserving Keyword Argument Order
- New dict implementation
- PEP 523: Adding a frame evaluation API to CPython
- PYTHONMALLOC environment variable
- DTrace and SystemTap probing support
- Other Language Changes
- New Modules
- Improved Modules
- array
- ast
- asyncio
- binascii
- cmath
- collections
- concurrent.futures
- contextlib
- datetime
- decimal
- distutils
- encodings
- enum
- faulthandler
- fileinput
- hashlib
- http.client
- idlelib and IDLE
- importlib
- inspect
- json
- logging
- math
- multiprocessing
- os
- pathlib
- pdb
- pickle
- pickletools
- pydoc
- random
- re
- readline
- rlcompleter
- shlex
- site
- sqlite3
- socket
- socketserver
- ssl
- statistics
- struct
- subprocess
- sys
- telnetlib
- time
- timeit
- tkinter
- traceback
- tracemalloc
- typing
- unicodedata
- unittest.mock
- urllib.request
- urllib.robotparser
- venv
- warnings
- winreg
- winsound
- xmlrpc.client
- zipfile
- zlib
- Optimizations
- Build and C API Changes
- Other Improvements
- Deprecated
- Removed
- Porting to Python 3.6
- Notable changes in Python 3.6.2
- Notable changes in Python 3.6.4
- Notable changes in Python 3.6.5
- Notable changes in Python 3.6.7
- Notable changes in Python 3.6.10
- Notable changes in Python 3.6.13
- What’s New In Python 3.5
- Summary – Release highlights
- New Features
- PEP 492 - Coroutines with async and await syntax
- PEP 465 - A dedicated infix operator for matrix multiplication
- PEP 448 - Additional Unpacking Generalizations
- PEP 461 - percent formatting support for bytes and bytearray
- PEP 484 - Type Hints
- PEP 471 - os.scandir() function – a better and faster directory iterator
- PEP 475: Retry system calls failing with EINTR
- PEP 479: Change StopIteration handling inside generators
- PEP 485: A function for testing approximate equality
- PEP 486: Make the Python Launcher aware of virtual environments
- PEP 488: Elimination of PYO files
- PEP 489: Multi-phase extension module initialization
- Other Language Changes
- New Modules
- Improved Modules
- argparse
- asyncio
- bz2
- cgi
- cmath
- code
- collections
- collections.abc
- compileall
- concurrent.futures
- configparser
- contextlib
- csv
- curses
- dbm
- difflib
- distutils
- doctest
- enum
- faulthandler
- functools
- glob
- gzip
- heapq
- http
- http.client
- idlelib and IDLE
- imaplib
- imghdr
- importlib
- inspect
- io
- ipaddress
- json
- linecache
- locale
- logging
- lzma
- math
- multiprocessing
- operator
- os
- pathlib
- pickle
- poplib
- re
- readline
- selectors
- shutil
- signal
- smtpd
- smtplib
- sndhdr
- socket
- ssl
- sqlite3
- subprocess
- sys
- sysconfig
- tarfile
- threading
- time
- timeit
- tkinter
- traceback
- types
- unicodedata
- unittest
- unittest.mock
- urllib
- wsgiref
- xmlrpc
- xml.sax
- zipfile
- Other module-level changes
- Optimizations
- Build and C API Changes
- Deprecated
- Removed
- Porting to Python 3.5
- Notable changes in Python 3.5.4
- What’s New In Python 3.4
- Summary – Release Highlights
- New Features
- New Modules
- Improved Modules
- abc
- aifc
- argparse
- audioop
- base64
- collections
- colorsys
- contextlib
- dbm
- dis
- doctest
- filecmp
- functools
- gc
- glob
- hashlib
- hmac
- html
- http
- idlelib and IDLE
- importlib
- inspect
- ipaddress
- logging
- marshal
- mmap
- multiprocessing
- operator
- os
- pdb
- pickle
- plistlib
- poplib
- pprint
- pty
- pydoc
- re
- resource
- select
- shelve
- shutil
- smtpd
- smtplib
- socket
- sqlite3
- ssl
- stat
- struct
- subprocess
- sunau
- sys
- tarfile
- textwrap
- threading
- traceback
- types
- urllib
- unittest
- venv
- wave
- weakref
- xml.etree
- zipfile
- CPython Implementation Changes
- Deprecated
- Removed
- Porting to Python 3.4
- Changed in 3.4.3
- What’s New In Python 3.3
- Summary – Release highlights
- PEP 405: Virtual Environments
- PEP 420: Implicit Namespace Packages
- PEP 3118: New memoryview implementation and buffer protocol documentation
- PEP 393: Flexible String Representation
- PEP 397: Python Launcher for Windows
- PEP 3151: Reworking the OS and IO exception hierarchy
- PEP 380: Syntax for Delegating to a Subgenerator
- PEP 409: Suppressing exception context
- PEP 414: Explicit Unicode literals
- PEP 3155: Qualified name for classes and functions
- PEP 412: Key-Sharing Dictionary
- PEP 362: Function Signature Object
- PEP 421: Adding sys.implementation
- Using importlib as the Implementation of Import
- Other Language Changes
- A Finer-Grained Import Lock
- Builtin functions and types
- New Modules
- Improved Modules
- abc
- array
- base64
- binascii
- bz2
- codecs
- collections
- contextlib
- crypt
- curses
- datetime
- decimal
- ftplib
- functools
- gc
- hmac
- http
- html
- imaplib
- inspect
- io
- itertools
- logging
- math
- mmap
- multiprocessing
- nntplib
- os
- pdb
- pickle
- pydoc
- re
- sched
- select
- shlex
- shutil
- signal
- smtpd
- smtplib
- socket
- socketserver
- sqlite3
- ssl
- stat
- struct
- subprocess
- sys
- tarfile
- tempfile
- textwrap
- threading
- time
- types
- unittest
- urllib
- webbrowser
- xml.etree.ElementTree
- zlib
- Optimizations
- Build and C API Changes
- Deprecated
- Porting to Python 3.3
- What’s New In Python 3.2
- PEP 384: Defining a Stable ABI
- PEP 389: Argparse Command Line Parsing Module
- PEP 391: Dictionary Based Configuration for Logging
- PEP 3148: The
concurrent.futuresmodule - PEP 3147: PYC Repository Directories
- PEP 3149: ABI Version Tagged .so Files
- PEP 3333: Python Web Server Gateway Interface v1.0.1
- Other Language Changes
- New, Improved, and Deprecated Modules
- elementtree
- functools
- itertools
- collections
- threading
- datetime and time
- math
- abc
- io
- reprlib
- logging
- csv
- contextlib
- decimal and fractions
- ftp
- popen
- select
- gzip and zipfile
- tarfile
- hashlib
- ast
- os
- shutil
- sqlite3
- html
- socket
- ssl
- nntp
- certificates
- imaplib
- http.client
- unittest
- random
- poplib
- asyncore
- tempfile
- inspect
- pydoc
- dis
- dbm
- ctypes
- site
- sysconfig
- pdb
- configparser
- urllib.parse
- mailbox
- turtledemo
- Multi-threading
- Optimizations
- Unicode
- Codecs
- Documentation
- IDLE
- Code Repository
- Build and C API Changes
- Porting to Python 3.2
- What’s New In Python 3.1
- What’s New In Python 3.0
- What’s New in Python 2.7
- The Future for Python 2.x
- Changes to the Handling of Deprecation Warnings
- Python 3.1 Features
- PEP 372: Adding an Ordered Dictionary to collections
- PEP 378: Format Specifier for Thousands Separator
- PEP 389: The argparse Module for Parsing Command Lines
- PEP 391: Dictionary-Based Configuration For Logging
- PEP 3106: Dictionary Views
- PEP 3137: The memoryview Object
- Other Language Changes
- New and Improved Modules
- Build and C API Changes
- Other Changes and Fixes
- Porting to Python 2.7
- New Features Added to Python 2.7 Maintenance Releases
- Two new environment variables for debug mode
- PEP 434: IDLE Enhancement Exception for All Branches
- PEP 466: Network Security Enhancements for Python 2.7
- PEP 477: Backport ensurepip (PEP 453) to Python 2.7
- PEP 476: Enabling certificate verification by default for stdlib http clients
- PEP 493: HTTPS verification migration tools for Python 2.7
- New
make regen-allbuild target - Removal of
make touchbuild target
- Acknowledgements
- What’s New in Python 2.6
- Python 3.0
- Changes to the Development Process
- PEP 343: The ‘with’ statement
- PEP 366: Explicit Relative Imports From a Main Module
- PEP 370: Per-user
site-packagesDirectory - PEP 371: The
multiprocessingPackage - PEP 3101: Advanced String Formatting
- PEP 3105:
printAs a Function - PEP 3110: Exception-Handling Changes
- PEP 3112: Byte Literals
- PEP 3116: New I/O Library
- PEP 3118: Revised Buffer Protocol
- PEP 3119: Abstract Base Classes
- PEP 3127: Integer Literal Support and Syntax
- PEP 3129: Class Decorators
- PEP 3141: A Type Hierarchy for Numbers
- Other Language Changes
- New and Improved Modules
- Deprecations and Removals
- Build and C API Changes
- Porting to Python 2.6
- Acknowledgements
- What’s New in Python 2.5
- PEP 308: Conditional Expressions
- PEP 309: Partial Function Application
- PEP 314: Metadata for Python Software Packages v1.1
- PEP 328: Absolute and Relative Imports
- PEP 338: Executing Modules as Scripts
- PEP 341: Unified try/except/finally
- PEP 342: New Generator Features
- PEP 343: The ‘with’ statement
- PEP 352: Exceptions as New-Style Classes
- PEP 353: Using ssize_t as the index type
- PEP 357: The ‘__index__’ method
- Other Language Changes
- New, Improved, and Removed Modules
- Build and C API Changes
- Porting to Python 2.5
- Acknowledgements
- What’s New in Python 2.4
- PEP 218: Built-In Set Objects
- PEP 237: Unifying Long Integers and Integers
- PEP 289: Generator Expressions
- PEP 292: Simpler String Substitutions
- PEP 318: Decorators for Functions and Methods
- PEP 322: Reverse Iteration
- PEP 324: New subprocess Module
- PEP 327: Decimal Data Type
- PEP 328: Multi-line Imports
- PEP 331: Locale-Independent Float/String Conversions
- Other Language Changes
- New, Improved, and Deprecated Modules
- Build and C API Changes
- Porting to Python 2.4
- Acknowledgements
- What’s New in Python 2.3
- PEP 218: A Standard Set Datatype
- PEP 255: Simple Generators
- PEP 263: Source Code Encodings
- PEP 273: Importing Modules from ZIP Archives
- PEP 277: Unicode file name support for Windows NT
- PEP 278: Universal Newline Support
- PEP 279: enumerate()
- PEP 282: The logging Package
- PEP 285: A Boolean Type
- PEP 293: Codec Error Handling Callbacks
- PEP 301: Package Index and Metadata for Distutils
- PEP 302: New Import Hooks
- PEP 305: Comma-separated Files
- PEP 307: Pickle Enhancements
- Extended Slices
- Other Language Changes
- New, Improved, and Deprecated Modules
- Pymalloc: A Specialized Object Allocator
- Build and C API Changes
- Other Changes and Fixes
- Porting to Python 2.3
- Acknowledgements
- What’s New in Python 2.2
- Introduction
- PEPs 252 and 253: Type and Class Changes
- PEP 234: Iterators
- PEP 255: Simple Generators
- PEP 237: Unifying Long Integers and Integers
- PEP 238: Changing the Division Operator
- Unicode Changes
- PEP 227: Nested Scopes
- New and Improved Modules
- Interpreter Changes and Fixes
- Other Changes and Fixes
- Acknowledgements
- What’s New in Python 2.1
- Introduction
- PEP 227: Nested Scopes
- PEP 236: __future__ Directives
- PEP 207: Rich Comparisons
- PEP 230: Warning Framework
- PEP 229: New Build System
- PEP 205: Weak References
- PEP 232: Function Attributes
- PEP 235: Importing Modules on Case-Insensitive Platforms
- PEP 217: Interactive Display Hook
- PEP 208: New Coercion Model
- PEP 241: Metadata in Python Packages
- New and Improved Modules
- Other Changes and Fixes
- Acknowledgements
- What’s New in Python 2.0
- Introduction
- What About Python 1.6?
- New Development Process
- Unicode
- List Comprehensions
- Augmented Assignment
- String Methods
- Garbage Collection of Cycles
- Other Core Changes
- Porting to 2.0
- Extending/Embedding Changes
- Distutils: Making Modules Easy to Install
- XML Modules
- Module changes
- New modules
- IDLE Improvements
- Deleted and Deprecated Modules
- Acknowledgements
- Changelog
- Python 3.9.23 final
- Python 3.9.22 final
- Python 3.9.21 final
- Python 3.9.20 final
- Python 3.9.19 final
- Python 3.9.18 final
- Python 3.9.17 final
- Python 3.9.16 final
- Python 3.9.15 final
- Python 3.9.14 final
- Python 3.9.13 final
- Python 3.9.12 final
- Python 3.9.11 final
- Python 3.9.10 final
- Python 3.9.9 final
- Python 3.9.8 final
- Python 3.9.7 final
- Python 3.9.6 final
- Python 3.9.5 final
- Python 3.9.4 final
- Python 3.9.3 final
- Python 3.9.2 final
- Python 3.9.2 release candidate 1
- Python 3.9.1 final
- Python 3.9.1 release candidate 1
- Python 3.9.0 final
- Python 3.9.0 release candidate 2
- Python 3.9.0 release candidate 1
- Python 3.9.0 beta 5
- Python 3.9.0 beta 4
- Python 3.9.0 beta 3
- Python 3.9.0 beta 2
- Python 3.9.0 beta 1
- Python 3.9.0 alpha 6
- Python 3.9.0 alpha 5
- Python 3.9.0 alpha 4
- Python 3.9.0 alpha 3
- Python 3.9.0 alpha 2
- Python 3.9.0 alpha 1
- Python 3.8.0 beta 1
- Python 3.8.0 alpha 4
- Python 3.8.0 alpha 3
- Python 3.8.0 alpha 2
- Python 3.8.0 alpha 1
- Python 3.7.0 final
- Python 3.7.0 release candidate 1
- Python 3.7.0 beta 5
- Python 3.7.0 beta 4
- Python 3.7.0 beta 3
- Python 3.7.0 beta 2
- Python 3.7.0 beta 1
- Python 3.7.0 alpha 4
- Python 3.7.0 alpha 3
- Python 3.7.0 alpha 2
- Python 3.7.0 alpha 1
- Python 3.6.6 final
- Python 3.6.6 release candidate 1
- Python 3.6.5 final
- Python 3.6.5 release candidate 1
- Python 3.6.4 final
- Python 3.6.4 release candidate 1
- Python 3.6.3 final
- Python 3.6.3 release candidate 1
- Python 3.6.2 final
- Python 3.6.2 release candidate 2
- Python 3.6.2 release candidate 1
- Python 3.6.1 final
- Python 3.6.1 release candidate 1
- Python 3.6.0 final
- Python 3.6.0 release candidate 2
- Python 3.6.0 release candidate 1
- Python 3.6.0 beta 4
- Python 3.6.0 beta 3
- Python 3.6.0 beta 2
- Python 3.6.0 beta 1
- Python 3.6.0 alpha 4
- Python 3.6.0 alpha 3
- Python 3.6.0 alpha 2
- Python 3.6.0 alpha 1
- Python 3.5.5 final
- Python 3.5.5 release candidate 1
- Python 3.5.4 final
- Python 3.5.4 release candidate 1
- Python 3.5.3 final
- Python 3.5.3 release candidate 1
- Python 3.5.2 final
- Python 3.5.2 release candidate 1
- Python 3.5.1 final
- Python 3.5.1 release candidate 1
- Python 3.5.0 final
- Python 3.5.0 release candidate 4
- Python 3.5.0 release candidate 3
- Python 3.5.0 release candidate 2
- Python 3.5.0 release candidate 1
- Python 3.5.0 beta 4
- Python 3.5.0 beta 3
- Python 3.5.0 beta 2
- Python 3.5.0 beta 1
- Python 3.5.0 alpha 4
- Python 3.5.0 alpha 3
- Python 3.5.0 alpha 2
- Python 3.5.0 alpha 1
- What’s New In Python 3.9
- The Python Tutorial
- 1. Whetting Your Appetite
- 2. Using the Python Interpreter
- 3. An Informal Introduction to Python
- 4. More Control Flow Tools
- 4.1.
ifStatements - 4.2.
forStatements - 4.3. The
range()Function - 4.4.
breakandcontinueStatements, andelseClauses on Loops - 4.5.
passStatements - 4.6. Defining Functions
- 4.7. More on Defining Functions
- 4.8. Intermezzo: Coding Style
- 4.1.
- 5. Data Structures
- 6. Modules
- 7. Input and Output
- 8. Errors and Exceptions
- 9. Classes
- 10. Brief Tour of the Standard Library
- 10.1. Operating System Interface
- 10.2. File Wildcards
- 10.3. Command Line Arguments
- 10.4. Error Output Redirection and Program Termination
- 10.5. String Pattern Matching
- 10.6. Mathematics
- 10.7. Internet Access
- 10.8. Dates and Times
- 10.9. Data Compression
- 10.10. Performance Measurement
- 10.11. Quality Control
- 10.12. Batteries Included
- 11. Brief Tour of the Standard Library — Part II
- 12. Virtual Environments and Packages
- 13. What Now?
- 14. Interactive Input Editing and History Substitution
- 15. Floating Point Arithmetic: Issues and Limitations
- 16. Appendix
- Python Setup and Usage
- 1. Command line and environment
- 2. Using Python on Unix platforms
- 3. Using Python on Windows
- 3.1. The full installer
- 3.2. The Microsoft Store package
- 3.3. The nuget.org packages
- 3.4. The embeddable package
- 3.5. Alternative bundles
- 3.6. Configuring Python
- 3.7. UTF-8 mode
- 3.8. Python Launcher for Windows
- 3.9. Finding modules
- 3.10. Additional modules
- 3.11. Compiling Python on Windows
- 3.12. Other Platforms
- 4. Using Python on a Mac
- 5. Editors and IDEs
- The Python Language Reference
- 1. Introduction
- 2. Lexical analysis
- 3. Data model
- 3.1. Objects, values and types
- 3.2. The standard type hierarchy
- 3.3. Special method names
- 3.3.1. Basic customization
- 3.3.2. Customizing attribute access
- 3.3.3. Customizing class creation
- 3.3.4. Customizing instance and subclass checks
- 3.3.5. Emulating generic types
- 3.3.6. Emulating callable objects
- 3.3.7. Emulating container types
- 3.3.8. Emulating numeric types
object.__add__()object.__sub__()object.__mul__()object.__matmul__()object.__truediv__()object.__floordiv__()object.__mod__()object.__divmod__()object.__pow__()object.__lshift__()object.__rshift__()object.__and__()object.__xor__()object.__or__()object.__radd__()object.__rsub__()object.__rmul__()object.__rmatmul__()object.__rtruediv__()object.__rfloordiv__()object.__rmod__()object.__rdivmod__()object.__rpow__()object.__rlshift__()object.__rrshift__()object.__rand__()object.__rxor__()object.__ror__()object.__iadd__()object.__isub__()object.__imul__()object.__imatmul__()object.__itruediv__()object.__ifloordiv__()object.__imod__()object.__ipow__()object.__ilshift__()object.__irshift__()object.__iand__()object.__ixor__()object.__ior__()object.__neg__()object.__pos__()object.__abs__()object.__invert__()object.__complex__()object.__int__()object.__float__()object.__index__()object.__round__()object.__trunc__()object.__floor__()object.__ceil__()
- 3.3.9. With Statement Context Managers
- 3.3.10. Special method lookup
- 3.4. Coroutines
- 4. Execution model
- 5. The import system
- 6. Expressions
- 6.1. Arithmetic conversions
- 6.2. Atoms
- 6.3. Primaries
- 6.4. Await expression
- 6.5. The power operator
- 6.6. Unary arithmetic and bitwise operations
- 6.7. Binary arithmetic operations
- 6.8. Shifting operations
- 6.9. Binary bitwise operations
- 6.10. Comparisons
- 6.11. Boolean operations
- 6.12. Assignment expressions
- 6.13. Conditional expressions
- 6.14. Lambdas
- 6.15. Expression lists
- 6.16. Evaluation order
- 6.17. Operator precedence
- 7. Simple statements
- 7.1. Expression statements
- 7.2. Assignment statements
- 7.3. The
assertstatement - 7.4. The
passstatement - 7.5. The
delstatement - 7.6. The
returnstatement - 7.7. The
yieldstatement - 7.8. The
raisestatement - 7.9. The
breakstatement - 7.10. The
continuestatement - 7.11. The
importstatement - 7.12. The
globalstatement - 7.13. The
nonlocalstatement
- 8. Compound statements
- 9. Top-level components
- 10. Full Grammar specification
- The Python Standard Library
- Introduction
- Built-in Functions
abs()all()any()ascii()bin()boolbreakpoint()callable()chr()classmethod()compile()complexdelattr()dir()divmod()enumerate()eval()exec()filter()floatformat()getattr()globals()hasattr()hash()help()hex()id()input()intisinstance()issubclass()iter()len()locals()map()max()min()next()objectoct()open()ord()pow()print()propertyrepr()reversed()round()setattr()slicesorted()staticmethod()sum()super()typevars()zip()__import__()
- Built-in Constants
- Built-in Types
- Truth Value Testing
- Boolean Operations —
and,or,not - Comparisons
- Numeric Types —
int,float,complex - Iterator Types
- Sequence Types —
list,tuple,range - Text Sequence Type —
strstr- String Methods
str.capitalize()str.casefold()str.center()str.count()str.encode()str.endswith()str.expandtabs()str.find()str.format()str.format_map()str.index()str.isalnum()str.isalpha()str.isascii()str.isdecimal()str.isdigit()str.isidentifier()str.islower()str.isnumeric()str.isprintable()str.isspace()str.istitle()str.isupper()str.join()str.ljust()str.lower()str.lstrip()str.maketrans()str.partition()str.removeprefix()str.removesuffix()str.replace()str.rfind()str.rindex()str.rjust()str.rpartition()str.rsplit()str.rstrip()str.split()str.splitlines()str.startswith()str.strip()str.swapcase()str.title()str.translate()str.upper()str.zfill()
printf-style String Formatting
- Binary Sequence Types —
bytes,bytearray,memoryview- Bytes Objects
- Bytearray Objects
- Bytes and Bytearray Operations
bytes.count()bytearray.count()bytes.removeprefix()bytearray.removeprefix()bytes.removesuffix()bytearray.removesuffix()bytes.decode()bytearray.decode()bytes.endswith()bytearray.endswith()bytes.find()bytearray.find()bytes.index()bytearray.index()bytes.join()bytearray.join()bytes.maketrans()bytearray.maketrans()bytes.partition()bytearray.partition()bytes.replace()bytearray.replace()bytes.rfind()bytearray.rfind()bytes.rindex()bytearray.rindex()bytes.rpartition()bytearray.rpartition()bytes.startswith()bytearray.startswith()bytes.translate()bytearray.translate()bytes.center()bytearray.center()bytes.ljust()bytearray.ljust()bytes.lstrip()bytearray.lstrip()bytes.rjust()bytearray.rjust()bytes.rsplit()bytearray.rsplit()bytes.rstrip()bytearray.rstrip()bytes.split()bytearray.split()bytes.strip()bytearray.strip()bytes.capitalize()bytearray.capitalize()bytes.expandtabs()bytearray.expandtabs()bytes.isalnum()bytearray.isalnum()bytes.isalpha()bytearray.isalpha()bytes.isascii()bytearray.isascii()bytes.isdigit()bytearray.isdigit()bytes.islower()bytearray.islower()bytes.isspace()bytearray.isspace()bytes.istitle()bytearray.istitle()bytes.isupper()bytearray.isupper()bytes.lower()bytearray.lower()bytes.splitlines()bytearray.splitlines()bytes.swapcase()bytearray.swapcase()bytes.title()bytearray.title()bytes.upper()bytearray.upper()bytes.zfill()bytearray.zfill()
printf-style Bytes Formatting- Memory Views
memoryviewmemoryview.__eq__()memoryview.tobytes()memoryview.hex()memoryview.tolist()memoryview.toreadonly()memoryview.release()memoryview.cast()memoryview.objmemoryview.nbytesmemoryview.readonlymemoryview.formatmemoryview.itemsizememoryview.ndimmemoryview.shapememoryview.stridesmemoryview.suboffsetsmemoryview.c_contiguousmemoryview.f_contiguousmemoryview.contiguous
- Set Types —
set,frozensetsetfrozensetfrozenset.isdisjoint()frozenset.issubset()frozenset.issuperset()frozenset.union()frozenset.intersection()frozenset.difference()frozenset.symmetric_difference()frozenset.copy()frozenset.update()frozenset.intersection_update()frozenset.difference_update()frozenset.symmetric_difference_update()frozenset.add()frozenset.remove()frozenset.discard()frozenset.pop()frozenset.clear()
- Mapping Types —
dict - Context Manager Types
- Generic Alias Type
- Other Built-in Types
- Special Attributes
- Integer string conversion length limitation
- Built-in Exceptions
- Exception context
- Inheriting from built-in exceptions
- Base classes
- Concrete exceptions
AssertionErrorAttributeErrorEOFErrorFloatingPointErrorGeneratorExitImportErrorModuleNotFoundErrorIndexErrorKeyErrorKeyboardInterruptMemoryErrorNameErrorNotImplementedErrorOSErrorOverflowErrorRecursionErrorReferenceErrorRuntimeErrorStopIterationStopAsyncIterationSyntaxErrorIndentationErrorTabErrorSystemErrorSystemExitTypeErrorUnboundLocalErrorUnicodeErrorUnicodeEncodeErrorUnicodeDecodeErrorUnicodeTranslateErrorValueErrorZeroDivisionErrorEnvironmentErrorIOErrorWindowsError- OS exceptions
- Warnings
- Exception hierarchy
- Text Processing Services
string— Common string operationsre— Regular expression operationsdifflib— Helpers for computing deltasDifferHtmlDiffcontext_diff()get_close_matches()ndiff()restore()unified_diff()diff_bytes()IS_LINE_JUNK()IS_CHARACTER_JUNK()- SequenceMatcher Objects
SequenceMatcherSequenceMatcher.set_seqs()SequenceMatcher.set_seq1()SequenceMatcher.set_seq2()SequenceMatcher.find_longest_match()SequenceMatcher.get_matching_blocks()SequenceMatcher.get_opcodes()SequenceMatcher.get_grouped_opcodes()SequenceMatcher.ratio()SequenceMatcher.quick_ratio()SequenceMatcher.real_quick_ratio()
- SequenceMatcher Examples
- Differ Objects
- Differ Example
- A command-line interface to difflib
textwrap— Text wrapping and fillingwrap()fill()shorten()dedent()indent()TextWrapperTextWrapper.widthTextWrapper.expand_tabsTextWrapper.tabsizeTextWrapper.replace_whitespaceTextWrapper.drop_whitespaceTextWrapper.initial_indentTextWrapper.subsequent_indentTextWrapper.fix_sentence_endingsTextWrapper.break_long_wordsTextWrapper.break_on_hyphensTextWrapper.max_linesTextWrapper.placeholderTextWrapper.wrap()TextWrapper.fill()
unicodedata— Unicode Databasestringprep— Internet String Preparationreadline— GNU readline interfacerlcompleter— Completion function for GNU readline
- Binary Data Services
struct— Interpret bytes as packed binary datacodecs— Codec registry and base classesencode()decode()lookup()CodecInfogetencoder()getdecoder()getincrementalencoder()getincrementaldecoder()getreader()getwriter()register()open()EncodedFile()iterencode()iterdecode()BOMBOM_BEBOM_LEBOM_UTF8BOM_UTF16BOM_UTF16_BEBOM_UTF16_LEBOM_UTF32BOM_UTF32_BEBOM_UTF32_LE- Codec Base Classes
- Encodings and Unicode
- Standard Encodings
- Python Specific Encodings
encodings.idna— Internationalized Domain Names in Applicationsencodings.mbcs— Windows ANSI codepageencodings.utf_8_sig— UTF-8 codec with BOM signature
- Data Types
datetime— Basic date and time types- Aware and Naive Objects
- Constants
- Available Types
timedeltaObjectsdateObjectsdatedate.today()date.fromtimestamp()date.fromordinal()date.fromisoformat()date.fromisocalendar()date.mindate.maxdate.resolutiondate.yeardate.monthdate.daydate.replace()date.timetuple()date.toordinal()date.weekday()date.isoweekday()date.isocalendar()date.isoformat()date.__str__()date.ctime()date.strftime()date.__format__()- Examples of Usage:
date
datetimeObjectsdatetimedatetime.today()datetime.now()datetime.utcnow()datetime.fromtimestamp()datetime.utcfromtimestamp()datetime.fromordinal()datetime.combine()datetime.fromisoformat()datetime.fromisocalendar()datetime.strptime()datetime.mindatetime.maxdatetime.resolutiondatetime.yeardatetime.monthdatetime.daydatetime.hourdatetime.minutedatetime.seconddatetime.microseconddatetime.tzinfodatetime.folddatetime.date()datetime.time()datetime.timetz()datetime.replace()datetime.astimezone()datetime.utcoffset()datetime.dst()datetime.tzname()datetime.timetuple()datetime.utctimetuple()datetime.toordinal()datetime.timestamp()datetime.weekday()datetime.isoweekday()datetime.isocalendar()datetime.isoformat()datetime.__str__()datetime.ctime()datetime.strftime()datetime.__format__()- Examples of Usage:
datetime
timeObjectstzinfoObjectstimezoneObjectsstrftime()andstrptime()Behavior
zoneinfo— IANA time zone supportcalendar— General calendar-related functionsCalendarCalendar.iterweekdays()Calendar.itermonthdates()Calendar.itermonthdays()Calendar.itermonthdays2()Calendar.itermonthdays3()Calendar.itermonthdays4()Calendar.monthdatescalendar()Calendar.monthdays2calendar()Calendar.monthdayscalendar()Calendar.yeardatescalendar()Calendar.yeardays2calendar()Calendar.yeardayscalendar()
TextCalendarHTMLCalendarLocaleTextCalendarLocaleHTMLCalendarsetfirstweekday()firstweekday()isleap()leapdays()weekday()weekheader()monthrange()monthcalendar()prmonth()month()prcal()calendar()timegm()day_nameday_abbrmonth_namemonth_abbr
collections— Container datatypescollections.abc— Abstract Base Classes for Containersheapq— Heap queue algorithmbisect— Array bisection algorithmarray— Efficient arrays of numeric valuesarraytypecodesarray.typecodearray.itemsizearray.append()array.buffer_info()array.byteswap()array.count()array.extend()array.frombytes()array.fromfile()array.fromlist()array.fromunicode()array.index()array.insert()array.pop()array.remove()array.reverse()array.tobytes()array.tofile()array.tolist()array.tounicode()
weakref— Weak referencesrefproxy()getweakrefcount()getweakrefs()WeakKeyDictionaryWeakKeyDictionary.keyrefs()WeakValueDictionaryWeakValueDictionary.valuerefs()WeakSetWeakMethodfinalizeReferenceTypeProxyTypeCallableProxyTypeProxyTypes- Weak Reference Objects
- Example
- Finalizer Objects
- Comparing finalizers with
__del__()methods
types— Dynamic type creation and names for built-in types- Dynamic Type Creation
- Standard Interpreter Types
FunctionTypeLambdaTypeGeneratorTypeCoroutineTypeAsyncGeneratorTypeCodeTypeCellTypeMethodTypeBuiltinFunctionTypeBuiltinMethodTypeWrapperDescriptorTypeMethodWrapperTypeMethodDescriptorTypeClassMethodDescriptorTypeModuleTypeGenericAliasTracebackTypeFrameTypeGetSetDescriptorTypeMemberDescriptorTypeMappingProxyType
- Additional Utility Classes and Functions
- Coroutine Utility Functions
copy— Shallow and deep copy operationspprint— Data pretty printerreprlib— Alternaterepr()implementationenum— Support for enumerations- Module Contents
- Creating an Enum
- Programmatic access to enumeration members and their attributes
- Duplicating enum members and values
- Ensuring unique enumeration values
- Using automatic values
- Iteration
- Comparisons
- Allowed members and attributes of enumerations
- Restricted Enum subclassing
- Pickling
- Functional API
- Derived Enumerations
- When to use
__new__()vs.__init__() - Interesting examples
- How are Enums different?
graphlib— Functionality to operate with graph-like structures
- Numeric and Mathematical Modules
numbers— Numeric abstract base classesmath— Mathematical functionscmath— Mathematical functions for complex numbersdecimal— Decimal fixed point and floating point arithmetic- Quick-start Tutorial
- Decimal objects
DecimalDecimal.adjusted()Decimal.as_integer_ratio()Decimal.as_tuple()Decimal.canonical()Decimal.compare()Decimal.compare_signal()Decimal.compare_total()Decimal.compare_total_mag()Decimal.conjugate()Decimal.copy_abs()Decimal.copy_negate()Decimal.copy_sign()Decimal.exp()Decimal.from_float()Decimal.fma()Decimal.is_canonical()Decimal.is_finite()Decimal.is_infinite()Decimal.is_nan()Decimal.is_normal()Decimal.is_qnan()Decimal.is_signed()Decimal.is_snan()Decimal.is_subnormal()Decimal.is_zero()Decimal.ln()Decimal.log10()Decimal.logb()Decimal.logical_and()Decimal.logical_invert()Decimal.logical_or()Decimal.logical_xor()Decimal.max()Decimal.max_mag()Decimal.min()Decimal.min_mag()Decimal.next_minus()Decimal.next_plus()Decimal.next_toward()Decimal.normalize()Decimal.number_class()Decimal.quantize()Decimal.radix()Decimal.remainder_near()Decimal.rotate()Decimal.same_quantum()Decimal.scaleb()Decimal.shift()Decimal.sqrt()Decimal.to_eng_string()Decimal.to_integral()Decimal.to_integral_exact()Decimal.to_integral_value()
- Logical operands
- Context objects
getcontext()setcontext()localcontext()BasicContextExtendedContextDefaultContextContextContext.clear_flags()Context.clear_traps()Context.copy()Context.copy_decimal()Context.create_decimal()Context.create_decimal_from_float()Context.Etiny()Context.Etop()Context.abs()Context.add()Context.canonical()Context.compare()Context.compare_signal()Context.compare_total()Context.compare_total_mag()Context.copy_abs()Context.copy_negate()Context.copy_sign()Context.divide()Context.divide_int()Context.divmod()Context.exp()Context.fma()Context.is_canonical()Context.is_finite()Context.is_infinite()Context.is_nan()Context.is_normal()Context.is_qnan()Context.is_signed()Context.is_snan()Context.is_subnormal()Context.is_zero()Context.ln()Context.log10()Context.logb()Context.logical_and()Context.logical_invert()Context.logical_or()Context.logical_xor()Context.max()Context.max_mag()Context.min()Context.min_mag()Context.minus()Context.multiply()Context.next_minus()Context.next_plus()Context.next_toward()Context.normalize()Context.number_class()Context.plus()Context.power()Context.quantize()Context.radix()Context.remainder()Context.remainder_near()Context.rotate()Context.same_quantum()Context.scaleb()Context.shift()Context.sqrt()Context.subtract()Context.to_eng_string()Context.to_integral_exact()Context.to_sci_string()
- Constants
- Rounding modes
- Signals
- Floating Point Notes
- Working with threads
- Recipes
- Decimal FAQ
fractions— Rational numbersrandom— Generate pseudo-random numbersstatistics— Mathematical statistics functions
- Functional Programming Modules
itertools— Functions creating iterators for efficient loopingfunctools— Higher-order functions and operations on callable objectsoperator— Standard operators as functionslt()le()eq()ne()ge()gt()__lt__()__le__()__eq__()__ne__()__ge__()__gt__()not_()__not__()truth()is_()is_not()abs()__abs__()add()__add__()and_()__and__()floordiv()__floordiv__()index()__index__()inv()invert()__inv__()__invert__()lshift()__lshift__()mod()__mod__()mul()__mul__()matmul()__matmul__()neg()__neg__()or_()__or__()pos()__pos__()pow()__pow__()rshift()__rshift__()sub()__sub__()truediv()__truediv__()xor()__xor__()concat()__concat__()contains()__contains__()countOf()delitem()__delitem__()getitem()__getitem__()indexOf()setitem()__setitem__()length_hint()attrgetter()itemgetter()methodcaller()- Mapping Operators to Functions
- In-place Operators
- File and Directory Access
pathlib— Object-oriented filesystem paths- Basic use
- Pure paths
PurePathPurePosixPathPureWindowsPath- General properties
- Operators
- Accessing individual parts
- Methods and properties
PurePath.drivePurePath.rootPurePath.anchorPurePath.parentsPurePath.parentPurePath.namePurePath.suffixPurePath.suffixesPurePath.stemPurePath.as_posix()PurePath.as_uri()PurePath.is_absolute()PurePath.is_relative_to()PurePath.is_reserved()PurePath.joinpath()PurePath.match()PurePath.relative_to()PurePath.with_name()PurePath.with_stem()PurePath.with_suffix()
- Concrete paths
PathPosixPathWindowsPath- Methods
Path.cwd()Path.home()Path.stat()Path.chmod()Path.exists()Path.expanduser()Path.glob()Path.group()Path.is_dir()Path.is_file()Path.is_mount()Path.is_symlink()Path.is_socket()Path.is_fifo()Path.is_block_device()Path.is_char_device()Path.iterdir()Path.lchmod()Path.lstat()Path.mkdir()Path.open()Path.owner()Path.read_bytes()Path.read_text()Path.readlink()Path.rename()Path.replace()Path.resolve()Path.rglob()Path.rmdir()Path.samefile()Path.symlink_to()Path.link_to()Path.touch()Path.unlink()Path.write_bytes()Path.write_text()
- Correspondence to tools in the
osmodule
os.path— Common pathname manipulationsabspath()basename()commonpath()commonprefix()dirname()exists()lexists()expanduser()expandvars()getatime()getmtime()getctime()getsize()isabs()isfile()isdir()islink()ismount()join()normcase()normpath()realpath()ALLOW_MISSINGrelpath()samefile()sameopenfile()samestat()split()splitdrive()splitext()supports_unicode_filenames
fileinput— Iterate over lines from multiple input streamsstat— Interpretingstat()resultsS_ISDIR()S_ISCHR()S_ISBLK()S_ISREG()S_ISFIFO()S_ISLNK()S_ISSOCK()S_ISDOOR()S_ISPORT()S_ISWHT()S_IMODE()S_IFMT()filemode()ST_MODEST_INOST_DEVST_NLINKST_UIDST_GIDST_SIZEST_ATIMEST_MTIMEST_CTIMES_IFSOCKS_IFLNKS_IFREGS_IFBLKS_IFDIRS_IFCHRS_IFIFOS_IFDOORS_IFPORTS_IFWHTS_ISUIDS_ISGIDS_ISVTXS_IRWXUS_IRUSRS_IWUSRS_IXUSRS_IRWXGS_IRGRPS_IWGRPS_IXGRPS_IRWXOS_IROTHS_IWOTHS_IXOTHS_ENFMTS_IREADS_IWRITES_IEXECUF_NODUMPUF_IMMUTABLEUF_APPENDUF_OPAQUEUF_NOUNLINKUF_COMPRESSEDUF_HIDDENSF_ARCHIVEDSF_IMMUTABLESF_APPENDSF_NOUNLINKSF_SNAPSHOTFILE_ATTRIBUTE_ARCHIVEFILE_ATTRIBUTE_COMPRESSEDFILE_ATTRIBUTE_DEVICEFILE_ATTRIBUTE_DIRECTORYFILE_ATTRIBUTE_ENCRYPTEDFILE_ATTRIBUTE_HIDDENFILE_ATTRIBUTE_INTEGRITY_STREAMFILE_ATTRIBUTE_NORMALFILE_ATTRIBUTE_NOT_CONTENT_INDEXEDFILE_ATTRIBUTE_NO_SCRUB_DATAFILE_ATTRIBUTE_OFFLINEFILE_ATTRIBUTE_READONLYFILE_ATTRIBUTE_REPARSE_POINTFILE_ATTRIBUTE_SPARSE_FILEFILE_ATTRIBUTE_SYSTEMFILE_ATTRIBUTE_TEMPORARYFILE_ATTRIBUTE_VIRTUALIO_REPARSE_TAG_SYMLINKIO_REPARSE_TAG_MOUNT_POINTIO_REPARSE_TAG_APPEXECLINK
filecmp— File and Directory Comparisonscmp()cmpfiles()clear_cache()- The
dircmpclassdircmpdircmp.report()dircmp.report_partial_closure()dircmp.report_full_closure()dircmp.leftdircmp.rightdircmp.left_listdircmp.right_listdircmp.commondircmp.left_onlydircmp.right_onlydircmp.common_dirsdircmp.common_filesdircmp.common_funnydircmp.same_filesdircmp.diff_filesdircmp.funny_filesdircmp.subdirs
DEFAULT_IGNORES
tempfile— Generate temporary files and directoriesglob— Unix style pathname pattern expansionfnmatch— Unix filename pattern matchinglinecache— Random access to text linesshutil— High-level file operations
- Data Persistence
pickle— Python object serialization- Relationship to other Python modules
- Data stream format
- Module Interface
- What can be pickled and unpickled?
- Pickling Class Instances
- Custom Reduction for Types, Functions, and Other Objects
- Out-of-band Buffers
- Restricting Globals
- Performance
- Examples
copyreg— Registerpicklesupport functionsshelve— Python object persistencemarshal— Internal Python object serializationdbm— Interfaces to Unix “databases”sqlite3— DB-API 2.0 interface for SQLite databases- Module functions and constants
- Connection Objects
ConnectionConnection.isolation_levelConnection.in_transactionConnection.cursor()Connection.commit()Connection.rollback()Connection.close()Connection.execute()Connection.executemany()Connection.executescript()Connection.create_function()Connection.create_aggregate()Connection.create_collation()Connection.interrupt()Connection.set_authorizer()Connection.set_progress_handler()Connection.set_trace_callback()Connection.enable_load_extension()Connection.load_extension()Connection.row_factoryConnection.text_factoryConnection.total_changesConnection.iterdump()Connection.backup()
- Cursor Objects
- Row Objects
- Exceptions
- SQLite and Python types
- Controlling Transactions
- Using
sqlite3efficiently
- Data Compression and Archiving
zlib— Compression compatible with gzipgzip— Support for gzip filesbz2— Support for bzip2 compressionlzma— Compression using the LZMA algorithmzipfile— Work with ZIP archivesBadZipFileBadZipfileLargeZipFileZipInfois_zipfile()ZIP_STOREDZIP_DEFLATEDZIP_BZIP2ZIP_LZMA- ZipFile Objects
- Path Objects
- PyZipFile Objects
- ZipInfo Objects
ZipInfo.from_file()ZipInfo.is_dir()ZipInfo.filenameZipInfo.date_timeZipInfo.compress_typeZipInfo.commentZipInfo.extraZipInfo.create_systemZipInfo.create_versionZipInfo.extract_versionZipInfo.reservedZipInfo.flag_bitsZipInfo.volumeZipInfo.internal_attrZipInfo.external_attrZipInfo.header_offsetZipInfo.CRCZipInfo.compress_sizeZipInfo.file_size
- Command-Line Interface
- Decompression pitfalls
tarfile— Read and write tar archive filesopen()is_tarfile()TarErrorReadErrorCompressionErrorStreamErrorExtractErrorHeaderErrorFilterErrorAbsolutePathErrorOutsideDestinationErrorSpecialFileErrorAbsoluteLinkErrorLinkOutsideDestinationErrorLinkFallbackErrorENCODINGUSTAR_FORMATGNU_FORMATPAX_FORMATDEFAULT_FORMAT- TarFile Objects
TarFileTarFile.open()TarFile.getmember()TarFile.getmembers()TarFile.getnames()TarFile.list()TarFile.next()TarFile.extractall()TarFile.extract()TarFile.extractfile()TarFile.errorlevelTarFile.extraction_filterTarFile.add()TarFile.addfile()TarFile.gettarinfo()TarFile.close()TarFile.pax_headers
- TarInfo Objects
TarInfoTarInfo.frombuf()TarInfo.fromtarfile()TarInfo.tobuf()TarInfo.nameTarInfo.sizeTarInfo.mtimeTarInfo.modeTarInfo.typeTarInfo.linknameTarInfo.uidTarInfo.gidTarInfo.unameTarInfo.gnameTarInfo.pax_headersTarInfo.isfile()TarInfo.isreg()TarInfo.isdir()TarInfo.issym()TarInfo.islnk()TarInfo.ischr()TarInfo.isblk()TarInfo.isfifo()TarInfo.isdev()
- Extraction filters
- Command-Line Interface
- Examples
- Supported tar formats
- Unicode issues
- File Formats
csv— CSV File Reading and Writingconfigparser— Configuration file parser- Quick Start
- Supported Datatypes
- Fallback Values
- Supported INI File Structure
- Interpolation of values
- Mapping Protocol Access
- Customizing Parser Behaviour
- Legacy API Examples
- ConfigParser Objects
ConfigParserConfigParser.defaults()ConfigParser.sections()ConfigParser.add_section()ConfigParser.has_section()ConfigParser.options()ConfigParser.has_option()ConfigParser.read()ConfigParser.read_file()ConfigParser.read_string()ConfigParser.read_dict()ConfigParser.get()ConfigParser.getint()ConfigParser.getfloat()ConfigParser.getboolean()ConfigParser.items()ConfigParser.set()ConfigParser.write()ConfigParser.remove_option()ConfigParser.remove_section()ConfigParser.optionxform()ConfigParser.readfp()
MAX_INTERPOLATION_DEPTH
- RawConfigParser Objects
- Exceptions
netrc— netrc file processingplistlib— Generate and parse Apple.plistfiles
- Cryptographic Services
- Generic Operating System Services
os— Miscellaneous operating system interfaceserrorname- File Names, Command Line Arguments, and Environment Variables
- Process Parameters
ctermid()environenvironbfsencode()fsdecode()fspath()PathLikegetenv()getenvb()get_exec_path()getegid()geteuid()getgid()getgrouplist()getgroups()getlogin()getpgid()getpgrp()getpid()getppid()getpriority()PRIO_PROCESSPRIO_PGRPPRIO_USERgetresuid()getresgid()getuid()initgroups()putenv()setegid()seteuid()setgid()setgroups()setpgrp()setpgid()setpriority()setregid()setresgid()setresuid()setreuid()getsid()setsid()setuid()strerror()supports_bytes_environumask()uname()unsetenv()
- File Object Creation
- File Descriptor Operations
close()closerange()copy_file_range()device_encoding()dup()dup2()fchmod()fchown()fdatasync()fpathconf()fstat()fstatvfs()fsync()ftruncate()get_blocking()isatty()lockf()F_LOCKF_TLOCKF_ULOCKF_TESTlseek()SEEK_SETSEEK_CURSEEK_ENDopen()O_RDONLYO_WRONLYO_RDWRO_APPENDO_CREATO_EXCLO_TRUNCO_DSYNCO_RSYNCO_SYNCO_NDELAYO_NONBLOCKO_NOCTTYO_CLOEXECO_BINARYO_NOINHERITO_SHORT_LIVEDO_TEMPORARYO_RANDOMO_SEQUENTIALO_TEXTO_ASYNCO_DIRECTO_DIRECTORYO_NOFOLLOWO_NOATIMEO_PATHO_TMPFILEO_SHLOCKO_EXLOCKopenpty()pipe()pipe2()posix_fallocate()posix_fadvise()POSIX_FADV_NORMALPOSIX_FADV_SEQUENTIALPOSIX_FADV_RANDOMPOSIX_FADV_NOREUSEPOSIX_FADV_WILLNEEDPOSIX_FADV_DONTNEEDpread()preadv()RWF_NOWAITRWF_HIPRIpwrite()pwritev()RWF_DSYNCRWF_SYNCread()sendfile()set_blocking()SF_NODISKIOSF_MNOWAITSF_SYNCreadv()tcgetpgrp()tcsetpgrp()ttyname()write()writev()- Querying the size of a terminal
- Inheritance of File Descriptors
- Files and Directories
access()F_OKR_OKW_OKX_OKchdir()chflags()chmod()chown()chroot()fchdir()getcwd()getcwdb()lchflags()lchmod()lchown()link()listdir()lstat()mkdir()makedirs()mkfifo()mknod()major()minor()makedev()pathconf()pathconf_namesreadlink()remove()removedirs()rename()renames()replace()rmdir()scandir()DirEntrystat()stat_resultstat_result.st_modestat_result.st_inostat_result.st_devstat_result.st_nlinkstat_result.st_uidstat_result.st_gidstat_result.st_sizestat_result.st_atimestat_result.st_mtimestat_result.st_ctimestat_result.st_atime_nsstat_result.st_mtime_nsstat_result.st_ctime_nsstat_result.st_blocksstat_result.st_blksizestat_result.st_rdevstat_result.st_flagsstat_result.st_genstat_result.st_birthtimestat_result.st_fstypestat_result.st_rsizestat_result.st_creatorstat_result.st_typestat_result.st_file_attributesstat_result.st_reparse_tag
statvfs()supports_dir_fdsupports_effective_idssupports_fdsupports_follow_symlinkssymlink()sync()truncate()unlink()utime()walk()fwalk()memfd_create()MFD_CLOEXECMFD_ALLOW_SEALINGMFD_HUGETLBMFD_HUGE_SHIFTMFD_HUGE_MASKMFD_HUGE_64KBMFD_HUGE_512KBMFD_HUGE_1MBMFD_HUGE_2MBMFD_HUGE_8MBMFD_HUGE_16MBMFD_HUGE_32MBMFD_HUGE_256MBMFD_HUGE_512MBMFD_HUGE_1GBMFD_HUGE_2GBMFD_HUGE_16GB- Linux extended attributes
- Process Management
abort()add_dll_directory()execl()execle()execlp()execlpe()execv()execve()execvp()execvpe()_exit()EX_OKEX_USAGEEX_DATAERREX_NOINPUTEX_NOUSEREX_NOHOSTEX_UNAVAILABLEEX_SOFTWAREEX_OSERREX_OSFILEEX_CANTCREATEX_IOERREX_TEMPFAILEX_PROTOCOLEX_NOPERMEX_CONFIGEX_NOTFOUNDfork()forkpty()kill()killpg()nice()pidfd_open()plock()popen()posix_spawn()posix_spawnp()register_at_fork()spawnl()spawnle()spawnlp()spawnlpe()spawnv()spawnve()spawnvp()spawnvpe()P_NOWAITP_NOWAITOP_WAITP_DETACHP_OVERLAYstartfile()system()times()wait()waitid()P_PIDP_PGIDP_ALLP_PIDFDWEXITEDWSTOPPEDWNOWAITCLD_EXITEDCLD_KILLEDCLD_DUMPEDCLD_TRAPPEDCLD_STOPPEDCLD_CONTINUEDwaitpid()wait3()wait4()waitstatus_to_exitcode()WNOHANGWCONTINUEDWUNTRACEDWCOREDUMP()WIFCONTINUED()WIFSTOPPED()WIFSIGNALED()WIFEXITED()WEXITSTATUS()WSTOPSIG()WTERMSIG()
- Interface to the scheduler
SCHED_OTHERSCHED_BATCHSCHED_IDLESCHED_SPORADICSCHED_FIFOSCHED_RRSCHED_RESET_ON_FORKsched_paramsched_get_priority_min()sched_get_priority_max()sched_setscheduler()sched_getscheduler()sched_setparam()sched_getparam()sched_rr_get_interval()sched_yield()sched_setaffinity()sched_getaffinity()
- Miscellaneous System Information
- Random numbers
io— Core tools for working with streamstime— Time access and conversions- Functions
asctime()pthread_getcpuclockid()clock_getres()clock_gettime()clock_gettime_ns()clock_settime()clock_settime_ns()ctime()get_clock_info()gmtime()localtime()mktime()monotonic()monotonic_ns()perf_counter()perf_counter_ns()process_time()process_time_ns()sleep()strftime()strptime()struct_timetime()thread_time()thread_time_ns()time_ns()tzset()
- Clock ID Constants
- Timezone Constants
- Functions
argparse— Parser for command-line options, arguments and sub-commandsgetopt— C-style parser for command line optionslogging— Logging facility for Python- Logger Objects
LoggerLogger.propagateLogger.setLevel()Logger.isEnabledFor()Logger.getEffectiveLevel()Logger.getChild()Logger.debug()Logger.info()Logger.warning()Logger.error()Logger.critical()Logger.log()Logger.exception()Logger.addFilter()Logger.removeFilter()Logger.filter()Logger.addHandler()Logger.removeHandler()Logger.findCaller()Logger.handle()Logger.makeRecord()Logger.hasHandlers()
- Logging Levels
- Handler Objects
- Formatter Objects
- Filter Objects
- LogRecord Objects
- LogRecord attributes
- LoggerAdapter Objects
- Thread Safety
- Module-Level Functions
- Module-Level Attributes
- Integration with the warnings module
- Logger Objects
logging.config— Logging configurationlogging.handlers— Logging handlersgetpass— Portable password inputcurses— Terminal handling for character-cell displays- Functions
errorbaudrate()beep()can_change_color()cbreak()color_content()color_pair()curs_set()def_prog_mode()def_shell_mode()delay_output()doupdate()echo()endwin()erasechar()filter()flash()flushinp()getmouse()getsyx()getwin()has_colors()has_ic()has_il()has_key()halfdelay()init_color()init_pair()initscr()is_term_resized()isendwin()keyname()killchar()longname()meta()mouseinterval()mousemask()napms()newpad()newwin()nl()nocbreak()noecho()nonl()noqiflush()noraw()pair_content()pair_number()putp()qiflush()raw()reset_prog_mode()reset_shell_mode()resetty()resize_term()resizeterm()savetty()get_escdelay()set_escdelay()get_tabsize()set_tabsize()setsyx()setupterm()start_color()termattrs()termname()tigetflag()tigetnum()tigetstr()tparm()typeahead()unctrl()ungetch()update_lines_cols()unget_wch()ungetmouse()use_env()use_default_colors()wrapper()
- Window Objects
window.addch()window.addnstr()window.addstr()window.attroff()window.attron()window.attrset()window.bkgd()window.bkgdset()window.border()window.box()window.chgat()window.clear()window.clearok()window.clrtobot()window.clrtoeol()window.cursyncup()window.delch()window.deleteln()window.derwin()window.echochar()window.enclose()window.encodingwindow.erase()window.getbegyx()window.getbkgd()window.getch()window.get_wch()window.getkey()window.getmaxyx()window.getparyx()window.getstr()window.getyx()window.hline()window.idcok()window.idlok()window.immedok()window.inch()window.insch()window.insdelln()window.insertln()window.insnstr()window.insstr()window.instr()window.is_linetouched()window.is_wintouched()window.keypad()window.leaveok()window.move()window.mvderwin()window.mvwin()window.nodelay()window.notimeout()window.noutrefresh()window.overlay()window.overwrite()window.putwin()window.redrawln()window.redrawwin()window.refresh()window.resize()window.scroll()window.scrollok()window.setscrreg()window.standend()window.standout()window.subpad()window.subwin()window.syncdown()window.syncok()window.syncup()window.timeout()window.touchline()window.touchwin()window.untouchwin()window.vline()
- Constants
- Functions
curses.textpad— Text input widget for curses programscurses.ascii— Utilities for ASCII characterscurses.panel— A panel stack extension for cursesplatform— Access to underlying platform’s identifying dataerrno— Standard errno system symbolserrorcodeEPERMENOENTESRCHEINTREIOENXIOE2BIGENOEXECEBADFECHILDEAGAINENOMEMEACCESEFAULTENOTBLKEBUSYEEXISTEXDEVENODEVENOTDIREISDIREINVALENFILEEMFILEENOTTYETXTBSYEFBIGENOSPCESPIPEEROFSEMLINKEPIPEEDOMERANGEEDEADLKENAMETOOLONGENOLCKENOSYSENOTEMPTYELOOPEWOULDBLOCKENOMSGEIDRMECHRNGEL2NSYNCEL3HLTEL3RSTELNRNGEUNATCHENOCSIEL2HLTEBADEEBADREXFULLENOANOEBADRQCEBADSLTEDEADLOCKEBFONTENOSTRENODATAETIMEENOSRENONETENOPKGEREMOTEENOLINKEADVESRMNTECOMMEPROTOEMULTIHOPEDOTDOTEBADMSGEOVERFLOWENOTUNIQEBADFDEREMCHGELIBACCELIBBADELIBSCNELIBMAXELIBEXECEILSEQERESTARTESTRPIPEEUSERSENOTSOCKEDESTADDRREQEMSGSIZEEPROTOTYPEENOPROTOOPTEPROTONOSUPPORTESOCKTNOSUPPORTEOPNOTSUPPEPFNOSUPPORTEAFNOSUPPORTEADDRINUSEEADDRNOTAVAILENETDOWNENETUNREACHENETRESETECONNABORTEDECONNRESETENOBUFSEISCONNENOTCONNESHUTDOWNETOOMANYREFSETIMEDOUTECONNREFUSEDEHOSTDOWNEHOSTUNREACHEALREADYEINPROGRESSESTALEEUCLEANENOTNAMENAVAILEISNAMEREMOTEIOEDQUOT
ctypes— A foreign function library for Python- ctypes tutorial
- Loading dynamic link libraries
- Accessing functions from loaded dlls
- Calling functions
- Fundamental data types
- Calling functions, continued
- Calling functions with your own custom data types
- Specifying the required argument types (function prototypes)
- Return types
- Passing pointers (or: passing parameters by reference)
- Structures and unions
- Structure/union alignment and byte order
- Bit fields in structures and unions
- Arrays
- Pointers
- Type conversions
- Incomplete Types
- Callback functions
- Accessing values exported from dlls
- Surprises
- Variable-sized data types
- ctypes reference
- Finding shared libraries
- Loading shared libraries
- Foreign functions
- Function prototypes
- Utility functions
addressof()alignment()byref()cast()create_string_buffer()create_unicode_buffer()DllCanUnloadNow()DllGetClassObject()find_library()find_msvcrt()FormatError()GetLastError()get_errno()get_last_error()memmove()memset()POINTER()pointer()resize()set_errno()set_last_error()sizeof()string_at()WinError()wstring_at()
- Data types
- Fundamental data types
- Structured data types
- Arrays and pointers
- ctypes tutorial
- Concurrent Execution
threading— Thread-based parallelismactive_count()current_thread()excepthook()get_ident()get_native_id()enumerate()main_thread()settrace()setprofile()stack_size()TIMEOUT_MAX- Thread-Local Data
- Thread Objects
- Lock Objects
- RLock Objects
- Condition Objects
- Semaphore Objects
- Event Objects
- Timer Objects
- Barrier Objects
- Using locks, conditions, and semaphores in the
withstatement
multiprocessing— Process-based parallelism- Introduction
- Reference
Processand exceptions- Pipes and Queues
- Miscellaneous
- Connection Objects
- Synchronization primitives
- Shared
ctypesObjects - Managers
- Proxy Objects
- Process Pools
- Listeners and Clients
- Authentication keys
- Logging
- The
multiprocessing.dummymodule
- Programming guidelines
- Examples
multiprocessing.shared_memory— Provides shared memory for direct access across processes- The
concurrentpackage concurrent.futures— Launching parallel taskssubprocess— Subprocess management- Using the
subprocessModule - Security Considerations
- Popen Objects
- Windows Popen Helpers
STARTUPINFO- Windows Constants
STD_INPUT_HANDLESTD_OUTPUT_HANDLESTD_ERROR_HANDLESW_HIDESTARTF_USESTDHANDLESSTARTF_USESHOWWINDOWCREATE_NEW_CONSOLECREATE_NEW_PROCESS_GROUPABOVE_NORMAL_PRIORITY_CLASSBELOW_NORMAL_PRIORITY_CLASSHIGH_PRIORITY_CLASSIDLE_PRIORITY_CLASSNORMAL_PRIORITY_CLASSREALTIME_PRIORITY_CLASSCREATE_NO_WINDOWDETACHED_PROCESSCREATE_DEFAULT_ERROR_MODECREATE_BREAKAWAY_FROM_JOB
- Older high-level API
- Replacing Older Functions with the
subprocessModule - Legacy Shell Invocation Functions
- Notes
- Using the
sched— Event schedulerqueue— A synchronized queue classcontextvars— Context Variables_thread— Low-level threading API
- Networking and Interprocess Communication
asyncio— Asynchronous I/O- Coroutines and Tasks
- Streams
- Synchronization Primitives
- Subprocesses
- Creating Subprocesses
- Constants
- Interacting with Subprocesses
asyncio.subprocess.Processasyncio.subprocess.Process.wait()asyncio.subprocess.Process.communicate()asyncio.subprocess.Process.send_signal()asyncio.subprocess.Process.terminate()asyncio.subprocess.Process.kill()asyncio.subprocess.Process.stdinasyncio.subprocess.Process.stdoutasyncio.subprocess.Process.stderrasyncio.subprocess.Process.pidasyncio.subprocess.Process.returncode
- Subprocess and Threads
- Examples
- Queues
- Exceptions
- Event Loop
get_running_loop()get_event_loop()set_event_loop()new_event_loop()- Event Loop Methods
- Running and stopping the loop
- Scheduling callbacks
- Scheduling delayed callbacks
- Creating Futures and Tasks
- Opening network connections
- Creating network servers
- Transferring files
- TLS Upgrade
- Watching file descriptors
- Working with socket objects directly
- DNS
- Working with pipes
- Unix signals
- Executing code in thread or process pools
- Error Handling API
- Enabling debug mode
- Running Subprocesses
- Callback Handles
- Server Objects
- Event Loop Implementations
- Examples
- Futures
- Transports and Protocols
- Policies
- Getting and Setting the Policy
- Policy Objects
- Process Watchers
- Custom Policies
- Platform Support
- High-level API Index
- Low-level API Index
- Developing with asyncio
socket— Low-level networking interface- Socket families
- Module contents
- Exceptions
- Constants
AF_UNIXAF_INETAF_INET6SOCK_STREAMSOCK_DGRAMSOCK_RAWSOCK_RDMSOCK_SEQPACKETSOCK_CLOEXECSOCK_NONBLOCKSOMAXCONNAF_CANPF_CANCAN_BCMCAN_RAW_FD_FRAMESCAN_RAW_JOIN_FILTERSCAN_ISOTPCAN_J1939AF_PACKETPF_PACKETAF_RDSPF_RDSSOL_RDSSIO_RCVALLSIO_KEEPALIVE_VALSSIO_LOOPBACK_FAST_PATHAF_ALGSOL_ALGAF_VSOCKIOCTL_VM_SOCKETS_GET_LOCAL_CIDAF_LINKhas_ipv6BDADDR_ANYBDADDR_LOCALHCI_FILTERHCI_TIME_STAMPHCI_DATA_DIRAF_QIPCRTR
- Functions
- Creating sockets
- Other functions
close()getaddrinfo()getfqdn()gethostbyname()gethostbyname_ex()gethostname()gethostbyaddr()getnameinfo()getprotobyname()getservbyname()getservbyport()ntohl()ntohs()htonl()htons()inet_aton()inet_ntoa()inet_pton()inet_ntop()CMSG_LEN()CMSG_SPACE()getdefaulttimeout()setdefaulttimeout()sethostname()if_nameindex()if_nametoindex()if_indextoname()send_fds()recv_fds()
- Socket Objects
socket.accept()socket.bind()socket.close()socket.connect()socket.connect_ex()socket.detach()socket.dup()socket.fileno()socket.get_inheritable()socket.getpeername()socket.getsockname()socket.getsockopt()socket.getblocking()socket.gettimeout()socket.ioctl()socket.listen()socket.makefile()socket.recv()socket.recvfrom()socket.recvmsg()socket.recvmsg_into()socket.recvfrom_into()socket.recv_into()socket.send()socket.sendall()socket.sendto()socket.sendmsg()socket.sendmsg_afalg()socket.sendfile()socket.set_inheritable()socket.setblocking()socket.settimeout()socket.setsockopt()socket.shutdown()socket.share()socket.familysocket.typesocket.proto
- Notes on socket timeouts
- Example
ssl— TLS/SSL wrapper for socket objects- Functions, Constants, and Exceptions
- Socket creation
- Context creation
- Exceptions
- Random generation
- Certificate handling
- Constants
CERT_NONECERT_OPTIONALCERT_REQUIREDVerifyModeVERIFY_DEFAULTVERIFY_CRL_CHECK_LEAFVERIFY_CRL_CHECK_CHAINVERIFY_X509_STRICTVERIFY_X509_TRUSTED_FIRSTVerifyFlagsPROTOCOL_TLSPROTOCOL_TLS_CLIENTPROTOCOL_TLS_SERVERPROTOCOL_SSLv23PROTOCOL_SSLv2PROTOCOL_SSLv3PROTOCOL_TLSv1PROTOCOL_TLSv1_1PROTOCOL_TLSv1_2OP_ALLOP_NO_SSLv2OP_NO_SSLv3OP_NO_TLSv1OP_NO_TLSv1_1OP_NO_TLSv1_2OP_NO_TLSv1_3OP_NO_RENEGOTIATIONOP_CIPHER_SERVER_PREFERENCEOP_SINGLE_DH_USEOP_SINGLE_ECDH_USEOP_ENABLE_MIDDLEBOX_COMPATOP_NO_COMPRESSIONOptionsOP_NO_TICKETOP_IGNORE_UNEXPECTED_EOFHAS_ALPNHAS_NEVER_CHECK_COMMON_NAMEHAS_ECDHHAS_SNIHAS_NPNHAS_SSLv2HAS_SSLv3HAS_TLSv1HAS_TLSv1_1HAS_TLSv1_2HAS_TLSv1_3CHANNEL_BINDING_TYPESOPENSSL_VERSIONOPENSSL_VERSION_INFOOPENSSL_VERSION_NUMBERALERT_DESCRIPTION_HANDSHAKE_FAILUREALERT_DESCRIPTION_INTERNAL_ERRORAlertDescriptionPurpose.SERVER_AUTHPurpose.CLIENT_AUTHSSLErrorNumberTLSVersionTLSVersion.MINIMUM_SUPPORTEDTLSVersion.MAXIMUM_SUPPORTEDTLSVersion.SSLv3TLSVersion.TLSv1TLSVersion.TLSv1_1TLSVersion.TLSv1_2TLSVersion.TLSv1_3
- SSL Sockets
SSLSocketSSLSocket.read()SSLSocket.write()SSLSocket.do_handshake()SSLSocket.getpeercert()SSLSocket.cipher()SSLSocket.shared_ciphers()SSLSocket.compression()SSLSocket.get_channel_binding()SSLSocket.selected_alpn_protocol()SSLSocket.selected_npn_protocol()SSLSocket.unwrap()SSLSocket.verify_client_post_handshake()SSLSocket.version()SSLSocket.pending()SSLSocket.contextSSLSocket.server_sideSSLSocket.server_hostnameSSLSocket.sessionSSLSocket.session_reused
- SSL Contexts
SSLContextSSLContext.cert_store_stats()SSLContext.load_cert_chain()SSLContext.load_default_certs()SSLContext.load_verify_locations()SSLContext.get_ca_certs()SSLContext.get_ciphers()SSLContext.set_default_verify_paths()SSLContext.set_ciphers()SSLContext.set_alpn_protocols()SSLContext.set_npn_protocols()SSLContext.sni_callbackSSLContext.set_servername_callbackSSLContext.load_dh_params()SSLContext.set_ecdh_curve()SSLContext.wrap_socket()SSLContext.sslsocket_classSSLContext.wrap_bio()SSLContext.sslobject_classSSLContext.session_stats()SSLContext.check_hostnameSSLContext.keylog_filenameSSLContext.maximum_versionSSLContext.minimum_versionSSLContext.num_ticketsSSLContext.optionsSSLContext.post_handshake_authSSLContext.protocolSSLContext.hostname_checks_common_nameSSLContext.verify_flagsSSLContext.verify_mode
- Certificates
- Examples
- Notes on non-blocking sockets
- Memory BIO Support
- SSL session
- Security considerations
- TLS 1.3
- LibreSSL support
- Functions, Constants, and Exceptions
select— Waiting for I/O completionselectors— High-level I/O multiplexingsignal— Set handlers for asynchronous events- General rules
- Module contents
SIG_DFLSIG_IGNSIGABRTSIGALRMSIGBREAKSIGBUSSIGCHLDSIGCLDSIGCONTSIGFPESIGHUPSIGILLSIGINTSIGKILLSIGPIPESIGSEGVSIGTERMSIGUSR1SIGUSR2SIGWINCHCTRL_C_EVENTCTRL_BREAK_EVENTNSIGITIMER_REALITIMER_VIRTUALITIMER_PROFSIG_BLOCKSIG_UNBLOCKSIG_SETMASKItimerErroralarm()getsignal()strsignal()valid_signals()pause()raise_signal()pidfd_send_signal()pthread_kill()pthread_sigmask()setitimer()getitimer()set_wakeup_fd()siginterrupt()signal()sigpending()sigwait()sigwaitinfo()sigtimedwait()
- Example
- Note on SIGPIPE
- Note on Signal Handlers and Exceptions
mmap— Memory-mapped file support
- Internet Data Handling
email— An email and MIME handling packageemail.message: Representing an email messageEmailMessageEmailMessage.as_string()EmailMessage.__str__()EmailMessage.as_bytes()EmailMessage.__bytes__()EmailMessage.is_multipart()EmailMessage.set_unixfrom()EmailMessage.get_unixfrom()EmailMessage.__len__()EmailMessage.__contains__()EmailMessage.__getitem__()EmailMessage.__setitem__()EmailMessage.__delitem__()EmailMessage.keys()EmailMessage.values()EmailMessage.items()EmailMessage.get()EmailMessage.get_all()EmailMessage.add_header()EmailMessage.replace_header()EmailMessage.get_content_type()EmailMessage.get_content_maintype()EmailMessage.get_content_subtype()EmailMessage.get_default_type()EmailMessage.set_default_type()EmailMessage.set_param()EmailMessage.del_param()EmailMessage.get_filename()EmailMessage.get_boundary()EmailMessage.set_boundary()EmailMessage.get_content_charset()EmailMessage.get_charsets()EmailMessage.is_attachment()EmailMessage.get_content_disposition()EmailMessage.walk()EmailMessage.get_body()EmailMessage.iter_attachments()EmailMessage.iter_parts()EmailMessage.get_content()EmailMessage.set_content()EmailMessage.make_related()EmailMessage.make_alternative()EmailMessage.make_mixed()EmailMessage.add_related()EmailMessage.add_alternative()EmailMessage.add_attachment()EmailMessage.clear()EmailMessage.clear_content()EmailMessage.preambleEmailMessage.epilogueEmailMessage.defects
MIMEPart
email.parser: Parsing email messagesemail.generator: Generating MIME documentsemail.policy: Policy ObjectsPolicyPolicy.max_line_lengthPolicy.linesepPolicy.cte_typePolicy.raise_on_defectPolicy.mangle_from_Policy.message_factoryPolicy.verify_generated_headersPolicy.clone()Policy.handle_defect()Policy.register_defect()Policy.header_max_count()Policy.header_source_parse()Policy.header_store_parse()Policy.header_fetch_parse()Policy.fold()Policy.fold_binary()
EmailPolicydefaultSMTPSMTPUTF8HTTPstrictCompat32compat32
email.errors: Exception and Defect classesemail.headerregistry: Custom Header Objectsemail.contentmanager: Managing MIME Contentemail: Examplesemail.message.Message: Representing an email message using thecompat32APIMessageMessage.as_string()Message.__str__()Message.as_bytes()Message.__bytes__()Message.is_multipart()Message.set_unixfrom()Message.get_unixfrom()Message.attach()Message.get_payload()Message.set_payload()Message.set_charset()Message.get_charset()Message.__len__()Message.__contains__()Message.__getitem__()Message.__setitem__()Message.__delitem__()Message.keys()Message.values()Message.items()Message.get()Message.get_all()Message.add_header()Message.replace_header()Message.get_content_type()Message.get_content_maintype()Message.get_content_subtype()Message.get_default_type()Message.set_default_type()Message.get_params()Message.get_param()Message.set_param()Message.del_param()Message.set_type()Message.get_filename()Message.get_boundary()Message.set_boundary()Message.get_content_charset()Message.get_charsets()Message.get_content_disposition()Message.walk()Message.preambleMessage.epilogueMessage.defects
email.mime: Creating email and MIME objects from scratchemail.header: Internationalized headersemail.charset: Representing character setsCharsetCharset.input_charsetCharset.header_encodingCharset.body_encodingCharset.output_charsetCharset.input_codecCharset.output_codecCharset.get_body_encoding()Charset.get_output_charset()Charset.header_encode()Charset.header_encode_lines()Charset.body_encode()Charset.__str__()Charset.__eq__()Charset.__ne__()
add_charset()add_alias()add_codec()
email.encoders: Encodersemail.utils: Miscellaneous utilitiesemail.iterators: Iterators
json— JSON encoder and decodermailbox— Manipulate mailboxes in various formatsMailboxobjectsMailboxMailbox.add()Mailbox.remove()Mailbox.__delitem__()Mailbox.discard()Mailbox.__setitem__()Mailbox.iterkeys()Mailbox.keys()Mailbox.itervalues()Mailbox.__iter__()Mailbox.values()Mailbox.iteritems()Mailbox.items()Mailbox.get()Mailbox.__getitem__()Mailbox.get_message()Mailbox.get_bytes()Mailbox.get_string()Mailbox.get_file()Mailbox.__contains__()Mailbox.__len__()Mailbox.clear()Mailbox.pop()Mailbox.popitem()Mailbox.update()Mailbox.flush()Mailbox.lock()Mailbox.unlock()Mailbox.close()
MaildirmboxMHBabylMMDF
Messageobjects- Exceptions
- Examples
mimetypes— Map filenames to MIME typesbase64— Base16, Base32, Base64, Base85 Data Encodingsbinhex— Encode and decode binhex4 filesbinascii— Convert between binary and ASCIIquopri— Encode and decode MIME quoted-printable data
- Structured Markup Processing Tools
html— HyperText Markup Language supporthtml.parser— Simple HTML and XHTML parserHTMLParser- Example HTML Parser Application
HTMLParserMethodsHTMLParser.feed()HTMLParser.close()HTMLParser.reset()HTMLParser.getpos()HTMLParser.get_starttag_text()HTMLParser.handle_starttag()HTMLParser.handle_endtag()HTMLParser.handle_startendtag()HTMLParser.handle_data()HTMLParser.handle_entityref()HTMLParser.handle_charref()HTMLParser.handle_comment()HTMLParser.handle_decl()HTMLParser.handle_pi()HTMLParser.unknown_decl()
- Examples
html.entities— Definitions of HTML general entities- XML Processing Modules
xml.etree.ElementTree— The ElementTree XML API- Tutorial
- XPath support
- Reference
- XInclude support
- Reference
- Functions
- Element Objects
ElementElement.tagElement.textElement.tailElement.attribElement.clear()Element.get()Element.items()Element.keys()Element.set()Element.append()Element.extend()Element.find()Element.findall()Element.findtext()Element.insert()Element.iter()Element.iterfind()Element.itertext()Element.makeelement()Element.remove()
- ElementTree Objects
- QName Objects
- TreeBuilder Objects
- XMLParser Objects
- XMLPullParser Objects
- Exceptions
xml.dom— The Document Object Model API- Module Contents
- Objects in the DOM
- DOMImplementation Objects
- Node Objects
Node.nodeTypeNode.parentNodeNode.attributesNode.previousSiblingNode.nextSiblingNode.childNodesNode.firstChildNode.lastChildNode.localNameNode.prefixNode.namespaceURINode.nodeNameNode.nodeValueNode.hasAttributes()Node.hasChildNodes()Node.isSameNode()Node.appendChild()Node.insertBefore()Node.removeChild()Node.replaceChild()Node.normalize()Node.cloneNode()
- NodeList Objects
- DocumentType Objects
- Document Objects
- Element Objects
Element.tagNameElement.getElementsByTagName()Element.getElementsByTagNameNS()Element.hasAttribute()Element.hasAttributeNS()Element.getAttribute()Element.getAttributeNode()Element.getAttributeNS()Element.getAttributeNodeNS()Element.removeAttribute()Element.removeAttributeNode()Element.removeAttributeNS()Element.setAttribute()Element.setAttributeNode()Element.setAttributeNodeNS()Element.setAttributeNS()
- Attr Objects
- NamedNodeMap Objects
- Comment Objects
- Text and CDATASection Objects
- ProcessingInstruction Objects
- Exceptions
- Conformance
xml.dom.minidom— Minimal DOM implementationxml.dom.pulldom— Support for building partial DOM treesxml.sax— Support for SAX2 parsersxml.sax.handler— Base classes for SAX handlersContentHandlerDTDHandlerEntityResolverErrorHandlerfeature_namespacesfeature_namespace_prefixesfeature_string_interningfeature_validationfeature_external_gesfeature_external_pesall_featuresproperty_lexical_handlerproperty_declaration_handlerproperty_dom_nodeproperty_xml_stringall_properties- ContentHandler Objects
ContentHandler.setDocumentLocator()ContentHandler.startDocument()ContentHandler.endDocument()ContentHandler.startPrefixMapping()ContentHandler.endPrefixMapping()ContentHandler.startElement()ContentHandler.endElement()ContentHandler.startElementNS()ContentHandler.endElementNS()ContentHandler.characters()ContentHandler.ignorableWhitespace()ContentHandler.processingInstruction()ContentHandler.skippedEntity()
- DTDHandler Objects
- EntityResolver Objects
- ErrorHandler Objects
xml.sax.saxutils— SAX Utilitiesxml.sax.xmlreader— Interface for XML parsersXMLReaderIncrementalParserLocatorInputSourceAttributesImplAttributesNSImpl- XMLReader Objects
XMLReader.parse()XMLReader.getContentHandler()XMLReader.setContentHandler()XMLReader.getDTDHandler()XMLReader.setDTDHandler()XMLReader.getEntityResolver()XMLReader.setEntityResolver()XMLReader.getErrorHandler()XMLReader.setErrorHandler()XMLReader.setLocale()XMLReader.getFeature()XMLReader.setFeature()XMLReader.getProperty()XMLReader.setProperty()
- IncrementalParser Objects
- Locator Objects
- InputSource Objects
- The
AttributesInterface - The
AttributesNSInterface
xml.parsers.expat— Fast XML parsing using ExpatExpatErrorerrorXMLParserTypeErrorString()ParserCreate()- XMLParser Objects
xmlparser.Parse()xmlparser.ParseFile()xmlparser.SetBase()xmlparser.GetBase()xmlparser.GetInputContext()xmlparser.ExternalEntityParserCreate()xmlparser.SetParamEntityParsing()xmlparser.UseForeignDTD()xmlparser.SetReparseDeferralEnabled()xmlparser.GetReparseDeferralEnabled()xmlparser.buffer_sizexmlparser.buffer_textxmlparser.buffer_usedxmlparser.ordered_attributesxmlparser.specified_attributesxmlparser.ErrorByteIndexxmlparser.ErrorCodexmlparser.ErrorColumnNumberxmlparser.ErrorLineNumberxmlparser.CurrentByteIndexxmlparser.CurrentColumnNumberxmlparser.CurrentLineNumberxmlparser.XmlDeclHandler()xmlparser.StartDoctypeDeclHandler()xmlparser.EndDoctypeDeclHandler()xmlparser.ElementDeclHandler()xmlparser.AttlistDeclHandler()xmlparser.StartElementHandler()xmlparser.EndElementHandler()xmlparser.ProcessingInstructionHandler()xmlparser.CharacterDataHandler()xmlparser.UnparsedEntityDeclHandler()xmlparser.EntityDeclHandler()xmlparser.NotationDeclHandler()xmlparser.StartNamespaceDeclHandler()xmlparser.EndNamespaceDeclHandler()xmlparser.CommentHandler()xmlparser.StartCdataSectionHandler()xmlparser.EndCdataSectionHandler()xmlparser.DefaultHandler()xmlparser.DefaultHandlerExpand()xmlparser.NotStandaloneHandler()xmlparser.ExternalEntityRefHandler()
- ExpatError Exceptions
- Example
- Content Model Descriptions
- Expat error constants
codesmessagesXML_ERROR_ASYNC_ENTITYXML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REFXML_ERROR_BAD_CHAR_REFXML_ERROR_BINARY_ENTITY_REFXML_ERROR_DUPLICATE_ATTRIBUTEXML_ERROR_INCORRECT_ENCODINGXML_ERROR_INVALID_TOKENXML_ERROR_JUNK_AFTER_DOC_ELEMENTXML_ERROR_MISPLACED_XML_PIXML_ERROR_NO_ELEMENTSXML_ERROR_NO_MEMORYXML_ERROR_PARAM_ENTITY_REFXML_ERROR_PARTIAL_CHARXML_ERROR_RECURSIVE_ENTITY_REFXML_ERROR_SYNTAXXML_ERROR_TAG_MISMATCHXML_ERROR_UNCLOSED_TOKENXML_ERROR_UNDEFINED_ENTITYXML_ERROR_UNKNOWN_ENCODINGXML_ERROR_UNCLOSED_CDATA_SECTIONXML_ERROR_EXTERNAL_ENTITY_HANDLINGXML_ERROR_NOT_STANDALONEXML_ERROR_UNEXPECTED_STATEXML_ERROR_ENTITY_DECLARED_IN_PEXML_ERROR_FEATURE_REQUIRES_XML_DTDXML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSINGXML_ERROR_UNBOUND_PREFIXXML_ERROR_UNDECLARING_PREFIXXML_ERROR_INCOMPLETE_PEXML_ERROR_XML_DECLXML_ERROR_TEXT_DECLXML_ERROR_PUBLICIDXML_ERROR_SUSPENDEDXML_ERROR_NOT_SUSPENDEDXML_ERROR_ABORTEDXML_ERROR_FINISHEDXML_ERROR_SUSPEND_PE
- Internet Protocols and Support
webbrowser— Convenient Web-browser controllerwsgiref— WSGI Utilities and Reference Implementationwsgiref.util– WSGI environment utilitieswsgiref.headers– WSGI response header toolswsgiref.simple_server– a simple WSGI HTTP serverwsgiref.validate— WSGI conformance checkerwsgiref.handlers– server/gateway base classesCGIHandlerIISCGIHandlerBaseCGIHandlerSimpleHandlerBaseHandlerBaseHandler.run()BaseHandler._write()BaseHandler._flush()BaseHandler.get_stdin()BaseHandler.get_stderr()BaseHandler.add_cgi_vars()BaseHandler.wsgi_multithreadBaseHandler.wsgi_multiprocessBaseHandler.wsgi_run_onceBaseHandler.os_environBaseHandler.server_softwareBaseHandler.get_scheme()BaseHandler.setup_environ()BaseHandler.log_exception()BaseHandler.traceback_limitBaseHandler.error_output()BaseHandler.error_statusBaseHandler.error_headersBaseHandler.error_bodyBaseHandler.wsgi_file_wrapperBaseHandler.sendfile()BaseHandler.origin_serverBaseHandler.http_version
read_environ()
- Examples
urllib— URL handling modulesurllib.request— Extensible library for opening URLsurlopen()install_opener()build_opener()pathname2url()url2pathname()getproxies()RequestOpenerDirectorBaseHandlerHTTPDefaultErrorHandlerHTTPRedirectHandlerHTTPCookieProcessorProxyHandlerHTTPPasswordMgrHTTPPasswordMgrWithDefaultRealmHTTPPasswordMgrWithPriorAuthAbstractBasicAuthHandlerHTTPBasicAuthHandlerProxyBasicAuthHandlerAbstractDigestAuthHandlerHTTPDigestAuthHandlerProxyDigestAuthHandlerHTTPHandlerHTTPSHandlerFileHandlerDataHandlerFTPHandlerCacheFTPHandlerUnknownHandlerHTTPErrorProcessor- Request Objects
Request.full_urlRequest.typeRequest.hostRequest.origin_req_hostRequest.selectorRequest.dataRequest.unverifiableRequest.methodRequest.get_method()Request.add_header()Request.add_unredirected_header()Request.has_header()Request.remove_header()Request.get_full_url()Request.set_proxy()Request.get_header()Request.header_items()
- OpenerDirector Objects
- BaseHandler Objects
- HTTPRedirectHandler Objects
- HTTPCookieProcessor Objects
- ProxyHandler Objects
- HTTPPasswordMgr Objects
- HTTPPasswordMgrWithPriorAuth Objects
- AbstractBasicAuthHandler Objects
- HTTPBasicAuthHandler Objects
- ProxyBasicAuthHandler Objects
- AbstractDigestAuthHandler Objects
- HTTPDigestAuthHandler Objects
- ProxyDigestAuthHandler Objects
- HTTPHandler Objects
- HTTPSHandler Objects
- FileHandler Objects
- DataHandler Objects
- FTPHandler Objects
- CacheFTPHandler Objects
- UnknownHandler Objects
- HTTPErrorProcessor Objects
- Examples
- Legacy interface
urllib.requestRestrictions
urllib.response— Response classes used by urlliburllib.parse— Parse URLs into componentsurllib.error— Exception classes raised by urllib.requesturllib.robotparser— Parser for robots.txthttp— HTTP moduleshttp.client— HTTP protocol clientHTTPConnectionHTTPSConnectionHTTPResponseparse_headers()HTTPExceptionNotConnectedInvalidURLUnknownProtocolUnknownTransferEncodingUnimplementedFileModeIncompleteReadImproperConnectionStateCannotSendRequestCannotSendHeaderResponseNotReadyBadStatusLineLineTooLongRemoteDisconnectedHTTP_PORTHTTPS_PORTresponses- HTTPConnection Objects
- HTTPResponse Objects
HTTPResponse.read()HTTPResponse.readinto()HTTPResponse.getheader()HTTPResponse.getheaders()HTTPResponse.fileno()HTTPResponse.msgHTTPResponse.versionHTTPResponse.urlHTTPResponse.headersHTTPResponse.statusHTTPResponse.reasonHTTPResponse.debuglevelHTTPResponse.closedHTTPResponse.geturl()HTTPResponse.info()HTTPResponse.getstatus()
- Examples
- HTTPMessage Objects
ftplib— FTP protocol clientFTPFTP_TLSerror_replyerror_temperror_permerror_protoall_errors- FTP Objects
FTP.set_debuglevel()FTP.connect()FTP.getwelcome()FTP.login()FTP.abort()FTP.sendcmd()FTP.voidcmd()FTP.retrbinary()FTP.retrlines()FTP.set_pasv()FTP.storbinary()FTP.storlines()FTP.transfercmd()FTP.ntransfercmd()FTP.mlsd()FTP.nlst()FTP.dir()FTP.rename()FTP.delete()FTP.cwd()FTP.mkd()FTP.pwd()FTP.rmd()FTP.size()FTP.quit()FTP.close()
- FTP_TLS Objects
poplib— POP3 protocol clientimaplib— IMAP4 protocol clientIMAP4IMAP4.errorIMAP4.abortIMAP4.readonlyIMAP4_SSLIMAP4_streamInternaldate2tuple()Int2AP()ParseFlags()Time2Internaldate()- IMAP4 Objects
IMAP4.append()IMAP4.authenticate()IMAP4.check()IMAP4.close()IMAP4.copy()IMAP4.create()IMAP4.delete()IMAP4.deleteacl()IMAP4.enable()IMAP4.expunge()IMAP4.fetch()IMAP4.getacl()IMAP4.getannotation()IMAP4.getquota()IMAP4.getquotaroot()IMAP4.list()IMAP4.login()IMAP4.login_cram_md5()IMAP4.logout()IMAP4.lsub()IMAP4.myrights()IMAP4.namespace()IMAP4.noop()IMAP4.open()IMAP4.partial()IMAP4.proxyauth()IMAP4.read()IMAP4.readline()IMAP4.recent()IMAP4.rename()IMAP4.response()IMAP4.search()IMAP4.select()IMAP4.send()IMAP4.setacl()IMAP4.setannotation()IMAP4.setquota()IMAP4.shutdown()IMAP4.socket()IMAP4.sort()IMAP4.starttls()IMAP4.status()IMAP4.store()IMAP4.subscribe()IMAP4.thread()IMAP4.uid()IMAP4.unsubscribe()IMAP4.unselect()IMAP4.xatom()IMAP4.PROTOCOL_VERSIONIMAP4.debugIMAP4.utf8_enabled
- IMAP4 Example
smtplib— SMTP protocol clientuuid— UUID objects according to RFC 4122socketserver— A framework for network serversTCPServerUDPServerUnixStreamServerUnixDatagramServer- Server Creation Notes
- Server Objects
BaseServerBaseServer.fileno()BaseServer.handle_request()BaseServer.serve_forever()BaseServer.service_actions()BaseServer.shutdown()BaseServer.server_close()BaseServer.address_familyBaseServer.RequestHandlerClassBaseServer.server_addressBaseServer.socketBaseServer.allow_reuse_addressBaseServer.request_queue_sizeBaseServer.socket_typeBaseServer.timeoutBaseServer.finish_request()BaseServer.get_request()BaseServer.handle_error()BaseServer.handle_timeout()BaseServer.process_request()BaseServer.server_activate()BaseServer.server_bind()BaseServer.verify_request()
- Request Handler Objects
- Examples
http.server— HTTP serversHTTPServerThreadingHTTPServerBaseHTTPRequestHandlerBaseHTTPRequestHandler.client_addressBaseHTTPRequestHandler.serverBaseHTTPRequestHandler.close_connectionBaseHTTPRequestHandler.requestlineBaseHTTPRequestHandler.commandBaseHTTPRequestHandler.pathBaseHTTPRequestHandler.request_versionBaseHTTPRequestHandler.headersBaseHTTPRequestHandler.rfileBaseHTTPRequestHandler.wfileBaseHTTPRequestHandler.server_versionBaseHTTPRequestHandler.sys_versionBaseHTTPRequestHandler.error_message_formatBaseHTTPRequestHandler.error_content_typeBaseHTTPRequestHandler.protocol_versionBaseHTTPRequestHandler.MessageClassBaseHTTPRequestHandler.responsesBaseHTTPRequestHandler.handle()BaseHTTPRequestHandler.handle_one_request()BaseHTTPRequestHandler.handle_expect_100()BaseHTTPRequestHandler.send_error()BaseHTTPRequestHandler.send_response()BaseHTTPRequestHandler.send_header()BaseHTTPRequestHandler.send_response_only()BaseHTTPRequestHandler.end_headers()BaseHTTPRequestHandler.flush_headers()BaseHTTPRequestHandler.log_request()BaseHTTPRequestHandler.log_error()BaseHTTPRequestHandler.log_message()BaseHTTPRequestHandler.version_string()BaseHTTPRequestHandler.date_time_string()BaseHTTPRequestHandler.log_date_time_string()BaseHTTPRequestHandler.address_string()
SimpleHTTPRequestHandlerCGIHTTPRequestHandler- Security Considerations
http.cookies— HTTP state managementhttp.cookiejar— Cookie handling for HTTP clientsLoadErrorCookieJarFileCookieJarCookiePolicyDefaultCookiePolicyCookie- CookieJar and FileCookieJar Objects
CookieJar.add_cookie_header()CookieJar.extract_cookies()CookieJar.set_policy()CookieJar.make_cookies()CookieJar.set_cookie_if_ok()CookieJar.set_cookie()CookieJar.clear()CookieJar.clear_session_cookies()FileCookieJar.save()FileCookieJar.load()FileCookieJar.revert()FileCookieJar.filenameFileCookieJar.delayload
- FileCookieJar subclasses and co-operation with web browsers
- CookiePolicy Objects
- DefaultCookiePolicy Objects
DefaultCookiePolicy.blocked_domains()DefaultCookiePolicy.set_blocked_domains()DefaultCookiePolicy.is_blocked()DefaultCookiePolicy.allowed_domains()DefaultCookiePolicy.set_allowed_domains()DefaultCookiePolicy.is_not_allowed()DefaultCookiePolicy.rfc2109_as_netscapeDefaultCookiePolicy.strict_domainDefaultCookiePolicy.strict_rfc2965_unverifiableDefaultCookiePolicy.strict_ns_unverifiableDefaultCookiePolicy.strict_ns_domainDefaultCookiePolicy.strict_ns_set_initial_dollarDefaultCookiePolicy.strict_ns_set_pathDefaultCookiePolicy.DomainStrictNoDotsDefaultCookiePolicy.DomainStrictNonDomainDefaultCookiePolicy.DomainRFC2965MatchDefaultCookiePolicy.DomainLiberalDefaultCookiePolicy.DomainStrict
- Cookie Objects
Cookie.versionCookie.nameCookie.valueCookie.portCookie.pathCookie.secureCookie.expiresCookie.discardCookie.commentCookie.comment_urlCookie.rfc2109Cookie.port_specifiedCookie.domain_specifiedCookie.domain_initial_dotCookie.has_nonstandard_attr()Cookie.get_nonstandard_attr()Cookie.set_nonstandard_attr()Cookie.is_expired()
- Examples
xmlrpc— XMLRPC server and client modulesxmlrpc.client— XML-RPC client accessxmlrpc.server— Basic XML-RPC serversipaddress— IPv4/IPv6 manipulation library- Convenience factory functions
- IP Addresses
- Address objects
IPv4AddressIPv4Address.versionIPv4Address.max_prefixlenIPv4Address.compressedIPv4Address.explodedIPv4Address.packedIPv4Address.reverse_pointerIPv4Address.is_multicastIPv4Address.is_privateIPv4Address.is_globalIPv4Address.is_unspecifiedIPv4Address.is_reservedIPv4Address.is_loopbackIPv4Address.is_link_local
IPv4Address.__format__()IPv6AddressIPv6Address.compressedIPv6Address.explodedIPv6Address.packedIPv6Address.reverse_pointerIPv6Address.versionIPv6Address.max_prefixlenIPv6Address.is_multicastIPv6Address.is_privateIPv6Address.is_globalIPv6Address.is_unspecifiedIPv6Address.is_reservedIPv6Address.is_loopbackIPv6Address.is_link_localIPv6Address.is_site_localIPv6Address.ipv4_mappedIPv6Address.scope_idIPv6Address.sixtofourIPv6Address.teredo
IPv6Address.__format__()
- Conversion to Strings and Integers
- Operators
- Address objects
- IP Network definitions
- Prefix, net mask and host mask
- Network objects
IPv4NetworkIPv4Network.versionIPv4Network.max_prefixlenIPv4Network.is_multicastIPv4Network.is_privateIPv4Network.is_unspecifiedIPv4Network.is_reservedIPv4Network.is_loopbackIPv4Network.is_link_localIPv4Network.network_addressIPv4Network.broadcast_addressIPv4Network.hostmaskIPv4Network.netmaskIPv4Network.with_prefixlenIPv4Network.compressedIPv4Network.explodedIPv4Network.with_netmaskIPv4Network.with_hostmaskIPv4Network.num_addressesIPv4Network.prefixlenIPv4Network.hosts()IPv4Network.overlaps()IPv4Network.address_exclude()IPv4Network.subnets()IPv4Network.supernet()IPv4Network.subnet_of()IPv4Network.supernet_of()IPv4Network.compare_networks()
IPv6NetworkIPv6Network.versionIPv6Network.max_prefixlenIPv6Network.is_multicastIPv6Network.is_privateIPv6Network.is_unspecifiedIPv6Network.is_reservedIPv6Network.is_loopbackIPv6Network.is_link_localIPv6Network.network_addressIPv6Network.broadcast_addressIPv6Network.hostmaskIPv6Network.netmaskIPv6Network.with_prefixlenIPv6Network.compressedIPv6Network.explodedIPv6Network.with_netmaskIPv6Network.with_hostmaskIPv6Network.num_addressesIPv6Network.prefixlenIPv6Network.hosts()IPv6Network.overlaps()IPv6Network.address_exclude()IPv6Network.subnets()IPv6Network.supernet()IPv6Network.subnet_of()IPv6Network.supernet_of()IPv6Network.compare_networks()IPv6Network.is_site_local
- Operators
- Interface objects
- Other Module Level Functions
- Custom Exceptions
- Multimedia Services
wave— Read and write WAV filesopen()Error- Wave_read Objects
Wave_read.close()Wave_read.getnchannels()Wave_read.getsampwidth()Wave_read.getframerate()Wave_read.getnframes()Wave_read.getcomptype()Wave_read.getcompname()Wave_read.getparams()Wave_read.readframes()Wave_read.rewind()Wave_read.getmarkers()Wave_read.getmark()Wave_read.setpos()Wave_read.tell()
- Wave_write Objects
colorsys— Conversions between color systems
- Internationalization
gettext— Multilingual internationalization services- GNU gettext API
- Class-based API
find()translation()install()- The
NullTranslationsclassNullTranslationsNullTranslations._parse()NullTranslations.add_fallback()NullTranslations.gettext()NullTranslations.ngettext()NullTranslations.pgettext()NullTranslations.npgettext()NullTranslations.lgettext()NullTranslations.lngettext()NullTranslations.info()NullTranslations.charset()NullTranslations.output_charset()NullTranslations.set_output_charset()NullTranslations.install()
- The
GNUTranslationsclass - Solaris message catalog support
- The Catalog constructor
- Internationalizing your programs and modules
- Acknowledgements
locale— Internationalization servicesErrorsetlocale()localeconv()nl_langinfo()getdefaultlocale()getlocale()getpreferredencoding()normalize()resetlocale()strcoll()strxfrm()format_string()format()currency()str()delocalize()atof()atoi()LC_CTYPELC_COLLATELC_TIMELC_MONETARYLC_MESSAGESLC_NUMERICLC_ALLCHAR_MAX- Background, details, hints, tips and caveats
- For extension writers and programs that embed Python
- Access to message catalogs
- Program Frameworks
turtle— Turtle graphics- Introduction
- Overview of available Turtle and Screen methods
- Methods of RawTurtle/Turtle and corresponding functions
- Methods of TurtleScreen/Screen and corresponding functions
- Public classes
- Help and configuration
turtledemo— Demo scripts- Changes since Python 2.6
- Changes since Python 3.0
cmd— Support for line-oriented command interpretersshlex— Simple lexical analysissplit()join()quote()shlex- shlex Objects
shlex.get_token()shlex.push_token()shlex.read_token()shlex.sourcehook()shlex.push_source()shlex.pop_source()shlex.error_leader()shlex.commentersshlex.wordcharsshlex.whitespaceshlex.escapeshlex.quotesshlex.escapedquotesshlex.whitespace_splitshlex.infileshlex.instreamshlex.sourceshlex.debugshlex.linenoshlex.tokenshlex.eofshlex.punctuation_chars
- Parsing Rules
- Improved Compatibility with Shells
- Graphical User Interfaces with Tk
tkinter— Python interface to Tcl/Tktkinter.colorchooser— Color choosing dialogtkinter.font— Tkinter font wrapper- Tkinter Dialogs
tkinter.simpledialog— Standard Tkinter input dialogstkinter.filedialog— File selection dialogs- Native Load/Save Dialogs
askopenfile()askopenfiles()asksaveasfile()askopenfilename()askopenfilenames()asksaveasfilename()askdirectory()OpenSaveAsDirectoryFileDialogFileDialog.cancel_command()FileDialog.dirs_double_event()FileDialog.dirs_select_event()FileDialog.files_double_event()FileDialog.files_select_event()FileDialog.filter_command()FileDialog.get_filter()FileDialog.get_selection()FileDialog.go()FileDialog.ok_event()FileDialog.quit()FileDialog.set_filter()FileDialog.set_selection()
LoadFileDialogSaveFileDialog
- Native Load/Save Dialogs
tkinter.commondialog— Dialog window templates
tkinter.messagebox— Tkinter message promptstkinter.scrolledtext— Scrolled Text Widgettkinter.dnd— Drag and drop supporttkinter.ttk— Tk themed widgets- Using Ttk
- Ttk Widgets
- Widget
- Combobox
- Spinbox
- Notebook
- Progressbar
- Separator
- Sizegrip
- Treeview
- Options
- Item Options
- Tag Options
- Column Identifiers
- Virtual Events
- ttk.Treeview
TreeviewTreeview.bbox()Treeview.get_children()Treeview.set_children()Treeview.column()Treeview.delete()Treeview.detach()Treeview.exists()Treeview.focus()Treeview.heading()Treeview.identify()Treeview.identify_row()Treeview.identify_column()Treeview.identify_region()Treeview.identify_element()Treeview.index()Treeview.insert()Treeview.item()Treeview.move()Treeview.next()Treeview.parent()Treeview.prev()Treeview.reattach()Treeview.see()Treeview.selection()Treeview.selection_set()Treeview.selection_add()Treeview.selection_remove()Treeview.selection_toggle()Treeview.set()Treeview.tag_bind()Treeview.tag_configure()Treeview.tag_has()Treeview.xview()Treeview.yview()
- Ttk Styling
tkinter.tix— Extension widgets for Tk- IDLE
- Development Tools
typing— Support for type hints- Relevant PEPs
- Type aliases
- NewType
- Callable
- Generics
- User-defined generic types
- The
Anytype - Nominal vs structural subtyping
- Module contents
- Special typing primitives
- Generic concrete collections
- Abstract Base Classes
- Protocols
- Functions and decorators
- Introspection helpers
- Constant
pydoc— Documentation generator and online help system- Python Development Mode
- Effects of the Python Development Mode
- ResourceWarning Example
- Bad file descriptor error example
doctest— Test interactive Python examples- Simple Usage: Checking Examples in Docstrings
- Simple Usage: Checking Examples in a Text File
- How It Works
- Basic API
- Unittest API
- Advanced API
- Debugging
- Soapbox
unittest— Unit testing framework- Basic example
- Command-Line Interface
- Test Discovery
- Organizing test code
- Re-using old test code
- Skipping tests and expected failures
- Distinguishing test iterations using subtests
- Classes and functions
- Test cases
TestCaseTestCase.setUp()TestCase.tearDown()TestCase.setUpClass()TestCase.tearDownClass()TestCase.run()TestCase.skipTest()TestCase.subTest()TestCase.debug()TestCase.assertEqual()TestCase.assertNotEqual()TestCase.assertTrue()TestCase.assertFalse()TestCase.assertIs()TestCase.assertIsNot()TestCase.assertIsNone()TestCase.assertIsNotNone()TestCase.assertIn()TestCase.assertNotIn()TestCase.assertIsInstance()TestCase.assertNotIsInstance()TestCase.assertRaises()TestCase.assertRaisesRegex()TestCase.assertWarns()TestCase.assertWarnsRegex()TestCase.assertLogs()TestCase.assertAlmostEqual()TestCase.assertNotAlmostEqual()TestCase.assertGreater()TestCase.assertGreaterEqual()TestCase.assertLess()TestCase.assertLessEqual()TestCase.assertRegex()TestCase.assertNotRegex()TestCase.assertCountEqual()TestCase.addTypeEqualityFunc()TestCase.assertMultiLineEqual()TestCase.assertSequenceEqual()TestCase.assertListEqual()TestCase.assertTupleEqual()TestCase.assertSetEqual()TestCase.assertDictEqual()TestCase.fail()TestCase.failureExceptionTestCase.longMessageTestCase.maxDiffTestCase.countTestCases()TestCase.defaultTestResult()TestCase.id()TestCase.shortDescription()TestCase.addCleanup()TestCase.doCleanups()TestCase.addClassCleanup()TestCase.doClassCleanups()
IsolatedAsyncioTestCaseFunctionTestCase- Deprecated aliases
- Grouping tests
- Loading and running tests
TestLoaderTestLoader.errorsTestLoader.loadTestsFromTestCase()TestLoader.loadTestsFromModule()TestLoader.loadTestsFromName()TestLoader.loadTestsFromNames()TestLoader.getTestCaseNames()TestLoader.discover()TestLoader.testMethodPrefixTestLoader.sortTestMethodsUsingTestLoader.suiteClassTestLoader.testNamePatterns
TestResultTestResult.errorsTestResult.failuresTestResult.skippedTestResult.expectedFailuresTestResult.unexpectedSuccessesTestResult.shouldStopTestResult.testsRunTestResult.bufferTestResult.failfastTestResult.tb_localsTestResult.wasSuccessful()TestResult.stop()TestResult.startTest()TestResult.stopTest()TestResult.startTestRun()TestResult.stopTestRun()TestResult.addError()TestResult.addFailure()TestResult.addSuccess()TestResult.addSkip()TestResult.addExpectedFailure()TestResult.addUnexpectedSuccess()TestResult.addSubTest()
TextTestResultdefaultTestLoaderTextTestRunnermain()- load_tests Protocol
- Test cases
- Class and Module Fixtures
- Signal Handling
unittest.mock— mock object library- Quick Guide
- The Mock Class
MockMock.assert_called()Mock.assert_called_once()Mock.assert_called_with()Mock.assert_called_once_with()Mock.assert_any_call()Mock.assert_has_calls()Mock.assert_not_called()Mock.reset_mock()Mock.mock_add_spec()Mock.attach_mock()Mock.configure_mock()Mock.__dir__()Mock._get_child_mock()Mock.calledMock.call_countMock.return_valueMock.side_effectMock.call_argsMock.call_args_listMock.method_callsMock.mock_callsMock.__class__
NonCallableMockPropertyMockAsyncMockAsyncMock.assert_awaited()AsyncMock.assert_awaited_once()AsyncMock.assert_awaited_with()AsyncMock.assert_awaited_once_with()AsyncMock.assert_any_await()AsyncMock.assert_has_awaits()AsyncMock.assert_not_awaited()AsyncMock.reset_mock()AsyncMock.await_countAsyncMock.await_argsAsyncMock.await_args_list
- Calling
- Deleting Attributes
- Mock names and the name attribute
- Attaching Mocks as Attributes
- The patchers
- MagicMock and magic method support
- Helpers
unittest.mock— getting started- Using Mock
- Mock Patching Methods
- Mock for Method Calls on an Object
- Mocking Classes
- Naming your mocks
- Tracking all Calls
- Setting Return Values and Attributes
- Raising exceptions with mocks
- Side effect functions and iterables
- Mocking asynchronous iterators
- Mocking asynchronous context manager
- Creating a Mock from an Existing Object
- Patch Decorators
- Further Examples
- Mocking chained calls
- Partial mocking
- Mocking a Generator Method
- Applying the same patch to every test method
- Mocking Unbound Methods
- Checking multiple calls with mock
- Coping with mutable arguments
- Nesting Patches
- Mocking a dictionary with MagicMock
- Mock subclasses and their attributes
- Mocking imports with patch.dict
- Tracking order of calls and less verbose call assertions
- More complex argument matching
- Using Mock
- 2to3 - Automated Python 2 to 3 code translation
test— Regression tests package for Pythontest.support— Utilities for the Python test suiteTestFailedResourceDeniedverboseis_jythonis_androidunix_shellFS_NONASCIITESTFNTESTFN_UNICODETESTFN_ENCODINGTESTFN_UNENCODABLETESTFN_UNDECODABLETESTFN_NONASCIILOOPBACK_TIMEOUTINTERNET_TIMEOUTSHORT_TIMEOUTLONG_TIMEOUTSAVEDCWDPGOPIPE_MAX_SIZESOCK_MAX_SIZETEST_SUPPORT_DIRTEST_HOME_DIRTEST_DATA_DIRMAX_Py_ssize_tmax_memusereal_max_memuseMISSING_C_DOCSTRINGSHAVE_DOCSTRINGSTEST_HTTP_URLALWAYS_EQNEVER_EQLARGESTSMALLESTforget()unload()unlink()rmdir()rmtree()make_legacy_pyc()is_resource_enabled()python_is_optimized()with_pymalloc()requires()system_must_validate_cert()sortdict()findfile()create_empty_file()fd_count()match_test()set_match_tests()run_unittest()run_doctest()setswitchinterval()check_impl_detail()check_warnings()check_no_resource_warning()set_memlimit()record_original_stdout()get_original_stdout()args_from_interpreter_flags()optim_args_from_interpreter_flags()captured_stdin()captured_stdout()captured_stderr()temp_dir()change_cwd()temp_cwd()temp_umask()disable_faulthandler()gc_collect()disable_gc()swap_attr()swap_item()print_warning()wait_process()wait_threads_exit()start_threads()calcobjsize()calcvobjsize()checksizeof()can_symlink()can_xattr()skip_unless_symlink()skip_unless_xattr()anticipate_failure()run_with_locale()run_with_tz()requires_freebsd_version()requires_linux_version()requires_mac_version()requires_IEEE_754()requires_zlib()requires_gzip()requires_bz2()requires_lzma()requires_resource()requires_docstrings()cpython_only()impl_detail()no_tracing()refcount_test()reap_threads()bigmemtest()bigaddrspacetest()make_bad_fd()check_syntax_error()check_syntax_warning()open_urlresource()import_module()import_fresh_module()modules_setup()modules_cleanup()threading_setup()threading_cleanup()join_thread()reap_children()get_attribute()catch_threading_exception()catch_unraisable_exception()load_package_tests()fs_is_case_insensitive()detect_api_mismatch()patch()run_in_subinterp()check_free_after_iterating()missing_compiler_executable()check__all__()adjust_int_max_str_digits()TransientResourceEnvironmentVarGuardEnvironmentVarGuard.set()EnvironmentVarGuard.unset()SuppressCrashReportCleanImportDirsOnSysPathSaveSignalsMatcherWarningsRecorderBasicTestRunnerFakePath
test.support.socket_helper— Utilities for socket teststest.support.script_helper— Utilities for the Python execution teststest.support.bytecode_helper— Support tools for testing correct bytecode generation
- Debugging and Profiling
- Audit events table
bdb— Debugger frameworkBdbQuitBreakpointBdbBdb.canonic()Bdb.reset()Bdb.trace_dispatch()Bdb.dispatch_line()Bdb.dispatch_call()Bdb.dispatch_return()Bdb.dispatch_exception()Bdb.stop_here()Bdb.break_here()Bdb.break_anywhere()Bdb.user_call()Bdb.user_line()Bdb.user_return()Bdb.user_exception()Bdb.do_clear()Bdb.set_step()Bdb.set_next()Bdb.set_return()Bdb.set_until()Bdb.set_trace()Bdb.set_continue()Bdb.set_quit()Bdb.set_break()Bdb.clear_break()Bdb.clear_bpbynumber()Bdb.clear_all_file_breaks()Bdb.clear_all_breaks()Bdb.get_bpbynumber()Bdb.get_break()Bdb.get_breaks()Bdb.get_file_breaks()Bdb.get_all_breaks()Bdb.get_stack()Bdb.format_stack_entry()Bdb.run()Bdb.runeval()Bdb.runctx()Bdb.runcall()
checkfuncname()effective()set_trace()
faulthandler— Dump the Python tracebackpdb— The Python Debugger- The Python Profilers
timeit— Measure execution time of small code snippetstrace— Trace or track Python statement executiontracemalloc— Trace memory allocations
- Software Packaging and Distribution
- Python Runtime Services
sys— System-specific parameters and functionsabiflagsaddaudithook()argvaudit()base_exec_prefixbase_prefixbyteorderbuiltin_module_namescall_tracing()copyright_clear_type_cache()_current_frames()breakpointhook()_debugmallocstats()dllhandledisplayhook()dont_write_bytecodepycache_prefixexcepthook()__breakpointhook____displayhook____excepthook____unraisablehook__exc_info()exec_prefixexecutableexit()flagsfloat_infofloat_repr_stylegetallocatedblocks()getandroidapilevel()getdefaultencoding()getdlopenflags()getfilesystemencoding()getfilesystemencodeerrors()get_int_max_str_digits()getrefcount()getrecursionlimit()getsizeof()getswitchinterval()_getframe()getprofile()gettrace()getwindowsversion()get_asyncgen_hooks()get_coroutine_origin_tracking_depth()hash_infohexversionimplementationint_info__interactivehook__intern()is_finalizing()last_typelast_valuelast_tracebackmaxsizemaxunicodemeta_pathmodulespathpath_hookspath_importer_cacheplatformplatlibdirprefixps1ps2setdlopenflags()set_int_max_str_digits()setprofile()setrecursionlimit()setswitchinterval()settrace()set_asyncgen_hooks()set_coroutine_origin_tracking_depth()_enablelegacywindowsfsencoding()stdinstdoutstderr__stdin____stdout____stderr__thread_infotracebacklimitunraisablehook()versionapi_versionversion_infowarnoptionswinver_xoptions
sysconfig— Provide access to Python’s configuration informationbuiltins— Built-in objects__main__— Top-level script environmentwarnings— Warning controldataclasses— Data Classescontextlib— Utilities forwith-statement contextsabc— Abstract Base Classesatexit— Exit handlerstraceback— Print or retrieve a stack tracebackprint_tb()print_exception()print_exc()print_last()print_stack()extract_tb()extract_stack()format_list()format_exception_only()format_exception()format_exc()format_tb()format_stack()clear_frames()walk_stack()walk_tb()TracebackExceptionObjectsTracebackExceptionTracebackException.__cause__TracebackException.__context__TracebackException.__suppress_context__TracebackException.stackTracebackException.exc_typeTracebackException.filenameTracebackException.linenoTracebackException.textTracebackException.offsetTracebackException.msgTracebackException.from_exception()TracebackException.format()TracebackException.format_exception_only()
StackSummaryObjectsFrameSummaryObjects- Traceback Examples
__future__— Future statement definitionsgc— Garbage Collector interfaceenable()disable()isenabled()collect()set_debug()get_debug()get_objects()get_stats()set_threshold()get_count()get_threshold()get_referrers()get_referents()is_tracked()is_finalized()freeze()unfreeze()get_freeze_count()garbagecallbacksDEBUG_STATSDEBUG_COLLECTABLEDEBUG_UNCOLLECTABLEDEBUG_SAVEALLDEBUG_LEAK
inspect— Inspect live objects- Types and members
getmembers()getmodulename()ismodule()isclass()ismethod()isfunction()isgeneratorfunction()isgenerator()iscoroutinefunction()iscoroutine()isawaitable()isasyncgenfunction()isasyncgen()istraceback()isframe()iscode()isbuiltin()isroutine()isabstract()ismethoddescriptor()isdatadescriptor()isgetsetdescriptor()ismemberdescriptor()
- Retrieving source code
- Introspecting callables with the Signature object
- Classes and functions
- The interpreter stack
- Fetching attributes statically
- Current State of Generators and Coroutines
- Code Objects Bit Flags
- Command Line Interface
- Types and members
site— Site-specific configuration hook
- Custom Python Interpreters
- Importing Modules
zipimport— Import modules from Zip archivespkgutil— Package extension utilitymodulefinder— Find modules used by a scriptrunpy— Locating and executing Python modulesimportlib— The implementation ofimport- Introduction
- Functions
importlib.abc– Abstract base classes related to importimportlib.resources– Resourcesimportlib.machinery– Importers and path hooksimportlib.util– Utility code for importers- Examples
- Using
importlib.metadata
- Python Language Services
parser— Access Python parse treesast— Abstract Syntax Trees- Abstract Grammar
- Node classes
AST- Literals
- Variables
- Expressions
- Statements
- Control flow
- Function and class definitions
- Async and await
astHelpers- Compiler Flags
- Command-Line Usage
symtable— Access to the compiler’s symbol tablessymbol— Constants used with Python parse treestoken— Constants used with Python parse treestok_nameISTERMINAL()ISNONTERMINAL()ISEOF()ENDMARKERNAMENUMBERSTRINGNEWLINEINDENTDEDENTLPARRPARLSQBRSQBCOLONCOMMASEMIPLUSMINUSSTARSLASHVBARAMPERLESSGREATEREQUALDOTPERCENTLBRACERBRACEEQEQUALNOTEQUALLESSEQUALGREATEREQUALTILDECIRCUMFLEXLEFTSHIFTRIGHTSHIFTDOUBLESTARPLUSEQUALMINEQUALSTAREQUALSLASHEQUALPERCENTEQUALAMPEREQUALVBAREQUALCIRCUMFLEXEQUALLEFTSHIFTEQUALRIGHTSHIFTEQUALDOUBLESTAREQUALDOUBLESLASHDOUBLESLASHEQUALATATEQUALRARROWELLIPSISCOLONEQUALOPAWAITASYNCTYPE_IGNORETYPE_COMMENTERRORTOKENN_TOKENSNT_OFFSETCOMMENTNLENCODING
keyword— Testing for Python keywordstokenize— Tokenizer for Python sourcetabnanny— Detection of ambiguous indentationpyclbr— Python module browser supportpy_compile— Compile Python source filescompileall— Byte-compile Python librariesdis— Disassembler for Python bytecodepickletools— Tools for pickle developers
- Miscellaneous Services
formatter— Generic output formatting- The Formatter Interface
AS_ISformatter.writerformatter.end_paragraph()formatter.add_line_break()formatter.add_hor_rule()formatter.add_flowing_data()formatter.add_literal_data()formatter.add_label_data()formatter.flush_softspace()formatter.push_alignment()formatter.pop_alignment()formatter.push_font()formatter.pop_font()formatter.push_margin()formatter.pop_margin()formatter.push_style()formatter.pop_style()formatter.set_spacing()formatter.assert_line_data()
- Formatter Implementations
- The Writer Interface
- Writer Implementations
- The Formatter Interface
- MS Windows Specific Services
msvcrt— Useful routines from the MS VC++ runtimewinreg— Windows registry access- Functions
CloseKey()ConnectRegistry()CreateKey()CreateKeyEx()DeleteKey()DeleteKeyEx()DeleteValue()EnumKey()EnumValue()ExpandEnvironmentStrings()FlushKey()LoadKey()OpenKey()OpenKeyEx()QueryInfoKey()QueryValue()QueryValueEx()SaveKey()SetValue()SetValueEx()DisableReflectionKey()EnableReflectionKey()QueryReflectionKey()
- Constants
- Registry Handle Objects
- Functions
winsound— Sound-playing interface for Windows
- Unix Specific Services
posix— The most common POSIX system callspwd— The password databasegrp— The group databasetermios— POSIX style tty controltty— Terminal control functionspty— Pseudo-terminal utilitiesfcntl— Thefcntlandioctlsystem callsresource— Resource usage informationerror- Resource Limits
RLIM_INFINITYgetrlimit()setrlimit()prlimit()RLIMIT_CORERLIMIT_CPURLIMIT_FSIZERLIMIT_DATARLIMIT_STACKRLIMIT_RSSRLIMIT_NPROCRLIMIT_NOFILERLIMIT_OFILERLIMIT_MEMLOCKRLIMIT_VMEMRLIMIT_ASRLIMIT_MSGQUEUERLIMIT_NICERLIMIT_RTPRIORLIMIT_RTTIMERLIMIT_SIGPENDINGRLIMIT_SBSIZERLIMIT_SWAPRLIMIT_NPTS
- Resource Usage
syslog— Unix syslog library routines
- Superseded Modules
aifc— Read and write AIFF and AIFC filesopen()aifc.getnchannels()aifc.getsampwidth()aifc.getframerate()aifc.getnframes()aifc.getcomptype()aifc.getcompname()aifc.getparams()aifc.getmarkers()aifc.getmark()aifc.readframes()aifc.rewind()aifc.setpos()aifc.tell()aifc.close()aifc.aiff()aifc.aifc()aifc.setnchannels()aifc.setsampwidth()aifc.setframerate()aifc.setnframes()aifc.setcomptype()aifc.setparams()aifc.setmark()aifc.writeframes()aifc.writeframesraw()
asynchat— Asynchronous socket command/response handlerasyncore— Asynchronous socket handlerloop()dispatcherdispatcher.handle_read()dispatcher.handle_write()dispatcher.handle_expt()dispatcher.handle_connect()dispatcher.handle_close()dispatcher.handle_error()dispatcher.handle_accept()dispatcher.handle_accepted()dispatcher.readable()dispatcher.writable()dispatcher.create_socket()dispatcher.connect()dispatcher.send()dispatcher.recv()dispatcher.listen()dispatcher.bind()dispatcher.accept()dispatcher.close()
dispatcher_with_sendfile_dispatcherfile_wrapper- asyncore Example basic HTTP client
- asyncore Example basic echo server
audioop— Manipulate raw audio datacgi— Common Gateway Interface supportcgitb— Traceback manager for CGI scriptschunk— Read IFF chunked datacrypt— Function to check Unix passwordsimghdr— Determine the type of an imageimp— Access the import internalsmailcap— Mailcap file handlingmsilib— Read and write Microsoft Installer filesnis— Interface to Sun’s NIS (Yellow Pages)nntplib— NNTP protocol clientNNTPNNTP_SSLNNTPErrorNNTPReplyErrorNNTPTemporaryErrorNNTPPermanentErrorNNTPProtocolErrorNNTPDataError- NNTP Objects
- Attributes
- Methods
NNTP.quit()NNTP.getwelcome()NNTP.getcapabilities()NNTP.login()NNTP.starttls()NNTP.newgroups()NNTP.newnews()NNTP.list()NNTP.descriptions()NNTP.description()NNTP.group()NNTP.over()NNTP.help()NNTP.stat()NNTP.next()NNTP.last()NNTP.article()NNTP.head()NNTP.body()NNTP.post()NNTP.ihave()NNTP.date()NNTP.slave()NNTP.set_debuglevel()NNTP.xhdr()NNTP.xover()
- Utility functions
optparse— Parser for command line options- Background
- Tutorial
- Reference Guide
- Option Callbacks
- Defining a callback option
- How callbacks are called
- Raising errors in a callback
- Callback example 1: trivial callback
- Callback example 2: check option order
- Callback example 3: check option order (generalized)
- Callback example 4: check arbitrary condition
- Callback example 5: fixed arguments
- Callback example 6: variable arguments
- Extending
optparse
ossaudiodev— Access to OSS-compatible audio devicesOSSAudioErroropen()openmixer()- Audio Device Objects
oss_audio_device.close()oss_audio_device.fileno()oss_audio_device.read()oss_audio_device.write()oss_audio_device.writeall()oss_audio_device.nonblock()oss_audio_device.getfmts()oss_audio_device.setfmt()oss_audio_device.channels()oss_audio_device.speed()oss_audio_device.sync()oss_audio_device.reset()oss_audio_device.post()oss_audio_device.setparameters()oss_audio_device.bufsize()oss_audio_device.obufcount()oss_audio_device.obuffree()oss_audio_device.closedoss_audio_device.nameoss_audio_device.mode
- Mixer Device Objects
pipes— Interface to shell pipelinessmtpd— SMTP Serversndhdr— Determine type of sound filespwd— The shadow password databasesunau— Read and write Sun AU filesopen()ErrorAUDIO_FILE_MAGICAUDIO_FILE_ENCODING_MULAW_8AUDIO_FILE_ENCODING_LINEAR_8AUDIO_FILE_ENCODING_LINEAR_16AUDIO_FILE_ENCODING_LINEAR_24AUDIO_FILE_ENCODING_LINEAR_32AUDIO_FILE_ENCODING_ALAW_8AUDIO_FILE_ENCODING_FLOATAUDIO_FILE_ENCODING_DOUBLEAUDIO_FILE_ENCODING_ADPCM_G721AUDIO_FILE_ENCODING_ADPCM_G722AUDIO_FILE_ENCODING_ADPCM_G723_3AUDIO_FILE_ENCODING_ADPCM_G723_5- AU_read Objects
- AU_write Objects
telnetlib— Telnet clientTelnet- Telnet Objects
Telnet.read_until()Telnet.read_all()Telnet.read_some()Telnet.read_very_eager()Telnet.read_eager()Telnet.read_lazy()Telnet.read_very_lazy()Telnet.read_sb_data()Telnet.open()Telnet.msg()Telnet.set_debuglevel()Telnet.close()Telnet.get_socket()Telnet.fileno()Telnet.write()Telnet.interact()Telnet.mt_interact()Telnet.expect()Telnet.set_option_negotiation_callback()
- Telnet Example
uu— Encode and decode uuencode filesxdrlib— Encode and decode XDR dataPackerUnpacker- Packer Objects
- Unpacker Objects
Unpacker.reset()Unpacker.get_position()Unpacker.set_position()Unpacker.get_buffer()Unpacker.done()Unpacker.unpack_float()Unpacker.unpack_double()Unpacker.unpack_fstring()Unpacker.unpack_fopaque()Unpacker.unpack_string()Unpacker.unpack_opaque()Unpacker.unpack_bytes()Unpacker.unpack_list()Unpacker.unpack_farray()Unpacker.unpack_array()
- Exceptions
- Security Considerations
- Extending and Embedding the Python Interpreter
- Recommended third party tools
- Creating extensions without third party tools
- 1. Extending Python with C or C++
- 1.1. A Simple Example
- 1.2. Intermezzo: Errors and Exceptions
- 1.3. Back to the Example
- 1.4. The Module’s Method Table and Initialization Function
- 1.5. Compilation and Linkage
- 1.6. Calling Python Functions from C
- 1.7. Extracting Parameters in Extension Functions
- 1.8. Keyword Parameters for Extension Functions
- 1.9. Building Arbitrary Values
- 1.10. Reference Counts
- 1.11. Writing Extensions in C++
- 1.12. Providing a C API for an Extension Module
- 2. Defining Extension Types: Tutorial
- 3. Defining Extension Types: Assorted Topics
- 4. Building C and C++ Extensions
- 5. Building C and C++ Extensions on Windows
- 1. Extending Python with C or C++
- Embedding the CPython runtime in a larger application
- Python/C API Reference Manual
- Introduction
- Stable Application Binary Interface
- The Very High Level Layer
- Reference Counting
- Exception Handling
- Utilities
- Abstract Objects Layer
- Concrete Objects Layer
- Fundamental Objects
- Numeric Objects
- Sequence Objects
- Container Objects
- Function Objects
- Other Objects
- Initialization, Finalization, and Threads
- Before Python Initialization
- Global configuration variables
- Initializing and finalizing the interpreter
- Process-wide parameters
- Thread State and the Global Interpreter Lock
- Sub-interpreter support
- Asynchronous Notifications
- Profiling and Tracing
- Advanced Debugger Support
- Thread Local Storage Support
- Python Initialization Configuration
- Memory Management
- Object Implementation Support
- Allocating Objects on the Heap
- Common Object Structures
- Type Objects
- Quick Reference
- PyTypeObject Definition
- PyObject Slots
- PyVarObject Slots
- PyTypeObject Slots
Py_TPFLAGS_HEAPTYPEPy_TPFLAGS_BASETYPEPy_TPFLAGS_READYPy_TPFLAGS_READYINGPy_TPFLAGS_HAVE_GCPy_TPFLAGS_DEFAULTPy_TPFLAGS_METHOD_DESCRIPTORPy_TPFLAGS_LONG_SUBCLASSPy_TPFLAGS_LIST_SUBCLASSPy_TPFLAGS_TUPLE_SUBCLASSPy_TPFLAGS_BYTES_SUBCLASSPy_TPFLAGS_UNICODE_SUBCLASSPy_TPFLAGS_DICT_SUBCLASSPy_TPFLAGS_BASE_EXC_SUBCLASSPy_TPFLAGS_TYPE_SUBCLASSPy_TPFLAGS_HAVE_FINALIZEPy_TPFLAGS_HAVE_VECTORCALL
- Heap Types
- Number Object Structures
- Mapping Object Structures
- Sequence Object Structures
- Buffer Object Structures
- Async Object Structures
- Slot Type typedefs
- Examples
- Supporting Cyclic Garbage Collection
- API and ABI Versioning
- Distributing Python Modules
- Installing Python Modules
- Python HOWTOs
- Porting Python 2 Code to Python 3
- The Short Explanation
- Details
- Drop support for Python 2.6 and older
- Make sure you specify the proper version support in your
setup.pyfile - Have good test coverage
- Learn the differences between Python 2 & 3
- Update your code
- Prevent compatibility regressions
- Check which dependencies block your transition
- Update your
setup.pyfile to denote Python 3 compatibility - Use continuous integration to stay compatible
- Consider using optional static type checking
- Porting Extension Modules to Python 3
- Curses Programming with Python
- Descriptor HowTo Guide
- Functional Programming HOWTO
- Logging HOWTO
- Logging Cookbook
- Using logging in multiple modules
- Logging from multiple threads
- Multiple handlers and formatters
- Logging to multiple destinations
- Configuration server example
- Dealing with handlers that block
- Sending and receiving logging events across a network
- Adding contextual information to your logging output
- Logging to a single file from multiple processes
- Using file rotation
- Use of alternative formatting styles
- Customizing
LogRecord - Subclassing QueueHandler - a ZeroMQ example
- Subclassing QueueListener - a ZeroMQ example
- An example dictionary-based configuration
- Using a rotator and namer to customize log rotation processing
- A more elaborate multiprocessing example
- Inserting a BOM into messages sent to a SysLogHandler
- Implementing structured logging
- Customizing handlers with
dictConfig() - Using particular formatting styles throughout your application
- Configuring filters with
dictConfig() - Customized exception formatting
- Speaking logging messages
- Buffering logging messages and outputting them conditionally
- Formatting times using UTC (GMT) via configuration
- Using a context manager for selective logging
- A CLI application starter template
- A Qt GUI for logging
- Patterns to avoid
- Regular Expression HOWTO
- Socket Programming HOWTO
- Sorting HOW TO
- Unicode HOWTO
- HOWTO Fetch Internet Resources Using The urllib Package
- Argparse Tutorial
- An introduction to the ipaddress module
- Argument Clinic How-To
- The Goals Of Argument Clinic
- Basic Concepts And Usage
- Converting Your First Function
- Advanced Topics
- Symbolic default values
- Renaming the C functions and variables generated by Argument Clinic
- Converting functions using PyArg_UnpackTuple
- Optional Groups
- Using real Argument Clinic converters, instead of “legacy converters”
- Py_buffer
- Advanced converters
- Parameter default values
- The
NULLdefault value - Expressions specified as default values
- Using a return converter
- Cloning existing functions
- Calling Python code
- Using a “self converter”
- Writing a custom converter
- Writing a custom return converter
- METH_O and METH_NOARGS
- tp_new and tp_init functions
- Changing and redirecting Clinic’s output
- The #ifdef trick
- Using Argument Clinic in Python files
- Instrumenting CPython with DTrace and SystemTap
- Porting Python 2 Code to Python 3
- Python Frequently Asked Questions
- General Python FAQ
- Programming FAQ
- Design and History FAQ
- Why does Python use indentation for grouping of statements?
- Why am I getting strange results with simple arithmetic operations?
- Why are floating-point calculations so inaccurate?
- Why are Python strings immutable?
- Why must ‘self’ be used explicitly in method definitions and calls?
- Why can’t I use an assignment in an expression?
- Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))?
- Why is join() a string method instead of a list or tuple method?
- How fast are exceptions?
- Why isn’t there a switch or case statement in Python?
- Can’t you emulate threads in the interpreter instead of relying on an OS-specific thread implementation?
- Why can’t lambda expressions contain statements?
- Can Python be compiled to machine code, C or some other language?
- How does Python manage memory?
- Why doesn’t CPython use a more traditional garbage collection scheme?
- Why isn’t all memory freed when CPython exits?
- Why are there separate tuple and list data types?
- How are lists implemented in CPython?
- How are dictionaries implemented in CPython?
- Why must dictionary keys be immutable?
- Why doesn’t list.sort() return the sorted list?
- How do you specify and enforce an interface spec in Python?
- Why is there no goto?
- Why can’t raw strings (r-strings) end with a backslash?
- Why doesn’t Python have a “with” statement for attribute assignments?
- Why don’t generators support the with statement?
- Why are colons required for the if/while/def/class statements?
- Why does Python allow commas at the end of lists and tuples?
- Library and Extension FAQ
- Extending/Embedding FAQ
- Can I create my own functions in C?
- Can I create my own functions in C++?
- Writing C is hard; are there any alternatives?
- How can I execute arbitrary Python statements from C?
- How can I evaluate an arbitrary Python expression from C?
- How do I extract C values from a Python object?
- How do I use Py_BuildValue() to create a tuple of arbitrary length?
- How do I call an object’s method from C?
- How do I catch the output from PyErr_Print() (or anything that prints to stdout/stderr)?
- How do I access a module written in Python from C?
- How do I interface to C++ objects from Python?
- I added a module using the Setup file and the make fails; why?
- How do I debug an extension?
- I want to compile a Python module on my Linux system, but some files are missing. Why?
- How do I tell “incomplete input” from “invalid input”?
- How do I find undefined g++ symbols __builtin_new or __pure_virtual?
- Can I create an object class with some methods implemented in C and others in Python (e.g. through inheritance)?
- Python on Windows FAQ
- How do I run a Python program under Windows?
- How do I make Python scripts executable?
- Why does Python sometimes take so long to start?
- How do I make an executable from a Python script?
- Is a
*.pydfile the same as a DLL? - How can I embed Python into a Windows application?
- How do I keep editors from inserting tabs into my Python source?
- How do I check for a keypress without blocking?
- Graphic User Interface FAQ
- “Why is Python Installed on my Computer?” FAQ
- Glossary
- About these documents
- Dealing with Bugs
- Copyright
- History and License