Merge branch 'main' into windows-socket-sendfile

This commit is contained in:
Erlend E. Aasland 2024-01-06 22:24:15 +01:00 committed by GitHub
commit a4ce9dfa36
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
879 changed files with 42102 additions and 25872 deletions

View file

@ -6,7 +6,7 @@ ENV WASI_SDK_VERSION=20
ENV WASI_SDK_PATH=/opt/wasi-sdk
ENV WASMTIME_HOME=/opt/wasmtime
ENV WASMTIME_VERSION=9.0.1
ENV WASMTIME_VERSION=14.0.4
ENV WASMTIME_CPU_ARCH=x86_64
RUN dnf -y --nodocs --setopt=install_weak_deps=False install /usr/bin/{blurb,clang,curl,git,ln,tar,xz} 'dnf-command(builddep)' && \

3
.gitattributes vendored
View file

@ -76,6 +76,7 @@ Include/internal/pycore_ast_state.h generated
Include/internal/pycore_opcode.h generated
Include/internal/pycore_opcode_metadata.h generated
Include/internal/pycore_*_generated.h generated
Include/internal/pycore_uop_ids.h generated
Include/opcode.h generated
Include/opcode_ids.h generated
Include/token.h generated
@ -84,6 +85,7 @@ Lib/keyword.py generated
Lib/test/levenshtein_examples.json generated
Lib/test/test_stable_abi_ctypes.py generated
Lib/token.py generated
Misc/sbom.spdx.json generated
Objects/typeslots.inc generated
PC/python3dll.c generated
Parser/parser.c generated
@ -92,7 +94,6 @@ Programs/test_frozenmain.h generated
Python/Python-ast.c generated
Python/executor_cases.c.h generated
Python/generated_cases.c.h generated
Python/abstract_interp_cases.c.h generated
Python/opcode_targets.h generated
Python/stdlib_module_names.h generated
Tools/peg_generator/pegen/grammar_parser.py generated

12
.github/CODEOWNERS vendored
View file

@ -40,6 +40,7 @@ Lib/test/test_patma.py @brandtbucher
Lib/test/test_peepholer.py @brandtbucher
Lib/test/test_type_*.py @JelleZijlstra
Lib/test/test_capi/test_misc.py @markshannon @gvanrossum
Tools/c-analyzer/ @ericsnowcurrently
# Exceptions
Lib/traceback.py @iritkatriel
@ -156,6 +157,8 @@ Doc/c-api/stable.rst @encukou
**/*dataclasses* @ericvsmith
**/*ensurepip* @pfmoore @pradyunsg
**/*idlelib* @terryjreedy
**/*typing* @JelleZijlstra @AlexWaygood
@ -188,5 +191,14 @@ Doc/c-api/stable.rst @encukou
/Lib/test/test_clinic.py @erlend-aasland @AlexWaygood
Doc/howto/clinic.rst @erlend-aasland
# Subinterpreters
Lib/test/support/interpreters/ @ericsnowcurrently
Modules/_xx*interp*module.c @ericsnowcurrently
Lib/test/test_interpreters/ @ericsnowcurrently
# WebAssembly
/Tools/wasm/ @brettcannon
# SBOM
/Misc/sbom.spdx.json @sethmlarson
/Tools/build/generate_sbom.py @sethmlarson

View file

@ -19,7 +19,7 @@ jobs:
permissions:
issues: write
steps:
- uses: actions/github-script@v6
- uses: actions/github-script@v7
with:
# language=JavaScript
script: |

View file

@ -128,7 +128,7 @@ jobs:
if: needs.check_source.outputs.run_tests == 'true'
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v4
- uses: actions/setup-python@v5
with:
python-version: '3.x'
- name: Restore config.cache
@ -187,13 +187,13 @@ jobs:
if: needs.check_source.outputs.run_tests == 'true'
uses: ./.github/workflows/reusable-windows.yml
build_windows_free_threaded:
name: 'Windows (free-threaded)'
build_windows_free_threading:
name: 'Windows (free-threading)'
needs: check_source
if: needs.check_source.outputs.run_tests == 'true' && contains(github.event.pull_request.labels.*.name, 'topic-free-threaded')
if: needs.check_source.outputs.run_tests == 'true'
uses: ./.github/workflows/reusable-windows.yml
with:
free-threaded: true
free-threading: true
build_macos:
name: 'macOS'
@ -203,14 +203,14 @@ jobs:
with:
config_hash: ${{ needs.check_source.outputs.config_hash }}
build_macos_free_threaded:
name: 'macOS (free-threaded)'
build_macos_free_threading:
name: 'macOS (free-threading)'
needs: check_source
if: needs.check_source.outputs.run_tests == 'true' && contains(github.event.pull_request.labels.*.name, 'topic-free-threaded')
if: needs.check_source.outputs.run_tests == 'true'
uses: ./.github/workflows/reusable-macos.yml
with:
config_hash: ${{ needs.check_source.outputs.config_hash }}
free-threaded: true
free-threading: true
build_ubuntu:
name: 'Ubuntu'
@ -225,10 +225,10 @@ jobs:
--with-pydebug \
--with-openssl=$OPENSSL_DIR
build_ubuntu_free_threaded:
name: 'Ubuntu (free-threaded)'
build_ubuntu_free_threading:
name: 'Ubuntu (free-threading)'
needs: check_source
if: needs.check_source.outputs.run_tests == 'true' && contains(github.event.pull_request.labels.*.name, 'topic-free-threaded')
if: needs.check_source.outputs.run_tests == 'true'
uses: ./.github/workflows/reusable-ubuntu.yml
with:
config_hash: ${{ needs.check_source.outputs.config_hash }}
@ -395,7 +395,7 @@ jobs:
-x test_subprocess \
-x test_signal \
-x test_sysconfig
- uses: actions/upload-artifact@v3
- uses: actions/upload-artifact@v4
if: always()
with:
name: hypothesis-example-db
@ -483,14 +483,14 @@ jobs:
output-sarif: true
sanitizer: ${{ matrix.sanitizer }}
- name: Upload crash
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
if: failure() && steps.build.outcome == 'success'
with:
name: ${{ matrix.sanitizer }}-artifacts
path: ./out/artifacts
- name: Upload SARIF
if: always() && steps.build.outcome == 'success'
uses: github/codeql-action/upload-sarif@v2
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: cifuzz-sarif/results.sarif
checkout_path: cifuzz-sarif
@ -504,12 +504,12 @@ jobs:
- check-docs
- check_generated_files
- build_macos
- build_macos_free_threaded
- build_macos_free_threading
- build_ubuntu
- build_ubuntu_free_threaded
- build_ubuntu_free_threading
- build_ubuntu_ssltests
- build_windows
- build_windows_free_threaded
- build_windows_free_threading
- test_hypothesis
- build_asan
- cifuzz
@ -521,10 +521,7 @@ jobs:
uses: re-actors/alls-green@05ac9388f0aebcb5727afa17fcccfecd6f8ec5fe
with:
allowed-failures: >-
build_macos_free_threaded,
build_ubuntu_free_threaded,
build_ubuntu_ssltests,
build_windows_free_threaded,
cifuzz,
test_hypothesis,
allowed-skips: >-
@ -540,12 +537,12 @@ jobs:
&& '
check_generated_files,
build_macos,
build_macos_free_threaded,
build_macos_free_threading,
build_ubuntu,
build_ubuntu_free_threaded,
build_ubuntu_free_threading,
build_ubuntu_ssltests,
build_windows,
build_windows_free_threaded,
build_windows_free_threading,
build_asan,
'
|| ''

View file

@ -20,7 +20,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v4
- uses: actions/setup-python@v5
with:
python-version: "3.x"
- uses: pre-commit/action@v3.0.0

View file

@ -8,6 +8,8 @@ on:
pull_request:
paths:
- ".github/workflows/mypy.yml"
- "Lib/test/libregrtest/**"
- "Tools/build/generate_sbom.py"
- "Tools/cases_generator/**"
- "Tools/clinic/**"
- "Tools/peg_generator/**"
@ -32,6 +34,8 @@ jobs:
strategy:
matrix:
target: [
"Lib/test/libregrtest",
"Tools/build/",
"Tools/cases_generator",
"Tools/clinic",
"Tools/peg_generator",
@ -42,7 +46,7 @@ jobs:
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v4
- uses: actions/setup-python@v5
with:
python-version: "3.11"
cache: pip

View file

@ -18,7 +18,7 @@ jobs:
node-version: 20
- run: npm install mailgun.js form-data
- name: Send notification
uses: actions/github-script@v6
uses: actions/github-script@v7
env:
MAILGUN_API_KEY: ${{ secrets.MAILGUN_PYTHON_ORG_MAILGUN_KEY }}
with:

View file

@ -21,6 +21,7 @@ apt-get -yq install \
libssl-dev \
lzma \
lzma-dev \
strace \
tk-dev \
uuid-dev \
xvfb \

View file

@ -41,7 +41,7 @@ jobs:
git fetch origin ${{ env.refspec_base }} --shallow-since="${DATE}" \
--no-tags --prune --no-recurse-submodules
- name: 'Set up Python'
uses: actions/setup-python@v4
uses: actions/setup-python@v5
with:
python-version: '3'
cache: 'pip'
@ -72,7 +72,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: 'Set up Python'
uses: actions/setup-python@v4
uses: actions/setup-python@v5
with:
python-version: '3.11' # known to work with Sphinx 4.2
cache: 'pip'

View file

@ -4,7 +4,7 @@ on:
config_hash:
required: true
type: string
free-threaded:
free-threading:
required: false
type: boolean
default: false
@ -35,7 +35,7 @@ jobs:
./configure \
--config-cache \
--with-pydebug \
${{ inputs.free-threaded && '--disable-gil' || '' }} \
${{ inputs.free-threading && '--disable-gil' || '' }} \
--prefix=/opt/python-dev \
--with-openssl="$(brew --prefix openssl@3.0)"
- name: Build CPython

View file

@ -1,7 +1,7 @@
on:
workflow_call:
inputs:
free-threaded:
free-threading:
required: false
type: boolean
default: false
@ -16,7 +16,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: Build CPython
run: .\PCbuild\build.bat -e -d -p Win32 ${{ inputs.free-threaded && '--disable-gil' || '' }}
run: .\PCbuild\build.bat -e -d -v -p Win32 ${{ inputs.free-threading && '--disable-gil' || '' }}
- name: Display build info
run: .\python.bat -m test.pythoninfo
- name: Tests
@ -33,7 +33,7 @@ jobs:
- name: Register MSVC problem matcher
run: echo "::add-matcher::.github/problem-matchers/msvc.json"
- name: Build CPython
run: .\PCbuild\build.bat -e -d -p x64 ${{ inputs.free-threaded && '--disable-gil' || '' }}
run: .\PCbuild\build.bat -e -d -v -p x64 ${{ inputs.free-threading && '--disable-gil' || '' }}
- name: Display build info
run: .\python.bat -m test.pythoninfo
- name: Tests
@ -50,4 +50,4 @@ jobs:
- name: Register MSVC problem matcher
run: echo "::add-matcher::.github/problem-matchers/msvc.json"
- name: Build CPython
run: .\PCbuild\build.bat -e -d -p arm64 ${{ inputs.free-threaded && '--disable-gil' || '' }}
run: .\PCbuild\build.bat -e -d -v -p arm64 ${{ inputs.free-threading && '--disable-gil' || '' }}

View file

@ -16,7 +16,7 @@ jobs:
steps:
- name: "Check PRs"
uses: actions/stale@v8
uses: actions/stale@v9
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
stale-pr-message: 'This PR is stale because it has been open for 30 days with no activity.'

View file

@ -26,7 +26,7 @@ jobs:
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v4
- uses: actions/setup-python@v5
with:
python-version: '3'
- name: Compare checksum of bundled wheels to the ones published on PyPI

1
.gitignore vendored
View file

@ -125,6 +125,7 @@ Tools/unicode/data/
/config.status.lineno
# hendrikmuhs/ccache-action@v1
/.ccache
/cross-build/
/platform
/profile-clean-stamp
/profile-run-stamp

View file

@ -1,6 +1,6 @@
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.2
rev: v0.1.7
hooks:
- id: ruff
name: Run Ruff on Lib/test/
@ -24,7 +24,7 @@ repos:
types_or: [c, inc, python, rst]
- repo: https://github.com/sphinx-contrib/sphinx-lint
rev: v0.8.1
rev: v0.9.1
hooks:
- id: sphinx-lint
args: [--enable=default-role]

View file

@ -19,8 +19,12 @@ SPHINXERRORHANDLING = -W
PAPEROPT_a4 = -D latex_elements.papersize=a4paper
PAPEROPT_letter = -D latex_elements.papersize=letterpaper
ALLSPHINXOPTS = -b $(BUILDER) -d build/doctrees $(PAPEROPT_$(PAPER)) -j $(JOBS) \
$(SPHINXOPTS) $(SPHINXERRORHANDLING) . build/$(BUILDER) $(SOURCES)
ALLSPHINXOPTS = -b $(BUILDER) \
-d build/doctrees \
-j $(JOBS) \
$(PAPEROPT_$(PAPER)) \
$(SPHINXOPTS) $(SPHINXERRORHANDLING) \
. build/$(BUILDER) $(SOURCES)
.PHONY: help
help:
@ -142,7 +146,7 @@ htmlview: html
.PHONY: htmllive
htmllive: SPHINXBUILD = $(VENVDIR)/bin/sphinx-autobuild
htmllive: SPHINXOPTS = --re-ignore="/venv/"
htmllive: SPHINXOPTS = --re-ignore="/venv/" --open-browser --delay 0
htmllive: html
.PHONY: clean

View file

@ -413,7 +413,7 @@ API Functions
than a variable number of arguments.
.. c:function:: int PyArg_ParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], ...)
.. c:function:: int PyArg_ParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char * const *keywords, ...)
Parse the parameters of a function that takes both positional and keyword
parameters into local variables.
@ -424,15 +424,24 @@ API Functions
Returns true on success; on failure, it returns false and raises the
appropriate exception.
.. note::
The *keywords* parameter declaration is :c:expr:`char * const *` in C and
:c:expr:`const char * const *` in C++.
This can be overridden with the :c:macro:`PY_CXX_CONST` macro.
.. versionchanged:: 3.6
Added support for :ref:`positional-only parameters
<positional-only_parameter>`.
.. versionchanged:: 3.13
The *keywords* parameter has now type :c:expr:`char * const *` in C and
:c:expr:`const char * const *` in C++, instead of :c:expr:`char **`.
Added support for non-ASCII keyword parameter names.
.. c:function:: int PyArg_VaParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], va_list vargs)
.. c:function:: int PyArg_VaParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char * const *keywords, va_list vargs)
Identical to :c:func:`PyArg_ParseTupleAndKeywords`, except that it accepts a
va_list rather than a variable number of arguments.
@ -505,6 +514,19 @@ API Functions
PyArg_ParseTuple(args, "O|O:ref", &object, &callback)
.. c:macro:: PY_CXX_CONST
The value to be inserted, if any, before :c:expr:`char * const *`
in the *keywords* parameter declaration of
:c:func:`PyArg_ParseTupleAndKeywords` and
:c:func:`PyArg_VaParseTupleAndKeywords`.
Default empty for C and ``const`` for C++
(:c:expr:`const char * const *`).
To override, define it to the desired value before including
:file:`Python.h`.
.. versionadded:: 3.13
---------------
Building values

View file

@ -440,7 +440,7 @@ Querying the error indicator
.. c:function:: PyObject *PyErr_GetRaisedException(void)
Return the exception currently being raised, clearing the error indicator at
the same time.
the same time. Return ``NULL`` if the error indicator is not set.
This function is used by code that needs to catch exceptions,
or code that needs to save and restore the error indicator temporarily.
@ -541,7 +541,8 @@ Querying the error indicator
.. note::
This function *does not* implicitly set the ``__traceback__``
This function *does not* implicitly set the
:attr:`~BaseException.__traceback__`
attribute on the exception value. If setting the traceback
appropriately is desired, the following additional snippet is needed::
@ -753,7 +754,8 @@ Exception Objects
.. c:function:: PyObject* PyException_GetTraceback(PyObject *ex)
Return the traceback associated with the exception as a new reference, as
accessible from Python through :attr:`__traceback__`. If there is no
accessible from Python through the :attr:`~BaseException.__traceback__`
attribute. If there is no
traceback associated, this returns ``NULL``.
@ -767,8 +769,8 @@ Exception Objects
Return the context (another exception instance during whose handling *ex* was
raised) associated with the exception as a new reference, as accessible from
Python through :attr:`__context__`. If there is no context associated, this
returns ``NULL``.
Python through the :attr:`~BaseException.__context__` attribute.
If there is no context associated, this returns ``NULL``.
.. c:function:: void PyException_SetContext(PyObject *ex, PyObject *ctx)
@ -782,7 +784,8 @@ Exception Objects
Return the cause (either an exception instance, or ``None``,
set by ``raise ... from ...``) associated with the exception as a new
reference, as accessible from Python through :attr:`__cause__`.
reference, as accessible from Python through the
:attr:`~BaseException.__cause__` attribute.
.. c:function:: void PyException_SetCause(PyObject *ex, PyObject *cause)
@ -791,7 +794,8 @@ Exception Objects
it. There is no type check to make sure that *cause* is either an exception
instance or ``None``. This steals a reference to *cause*.
:attr:`__suppress_context__` is implicitly set to ``True`` by this function.
The :attr:`~BaseException.__suppress_context__` attribute is implicitly set
to ``True`` by this function.
.. c:function:: PyObject* PyException_GetArgs(PyObject *ex)

View file

@ -50,7 +50,7 @@ See also :ref:`Reflection <reflection>`.
.. c:function:: PyObject* PyFrame_GetBuiltins(PyFrameObject *frame)
Get the *frame*'s ``f_builtins`` attribute.
Get the *frame*'s :attr:`~frame.f_builtins` attribute.
Return a :term:`strong reference`. The result cannot be ``NULL``.
@ -81,7 +81,7 @@ See also :ref:`Reflection <reflection>`.
.. c:function:: PyObject* PyFrame_GetGlobals(PyFrameObject *frame)
Get the *frame*'s ``f_globals`` attribute.
Get the *frame*'s :attr:`~frame.f_globals` attribute.
Return a :term:`strong reference`. The result cannot be ``NULL``.
@ -90,7 +90,7 @@ See also :ref:`Reflection <reflection>`.
.. c:function:: int PyFrame_GetLasti(PyFrameObject *frame)
Get the *frame*'s ``f_lasti`` attribute.
Get the *frame*'s :attr:`~frame.f_lasti` attribute.
Returns -1 if ``frame.f_lasti`` is ``None``.
@ -120,7 +120,7 @@ See also :ref:`Reflection <reflection>`.
.. c:function:: PyObject* PyFrame_GetLocals(PyFrameObject *frame)
Get the *frame*'s ``f_locals`` attribute (:class:`dict`).
Get the *frame*'s :attr:`~frame.f_locals` attribute (:class:`dict`).
Return a :term:`strong reference`.

View file

@ -34,18 +34,20 @@ There are a few functions specific to Python functions.
Return a new function object associated with the code object *code*. *globals*
must be a dictionary with the global variables accessible to the function.
The function's docstring and name are retrieved from the code object. *__module__*
The function's docstring and name are retrieved from the code object.
:attr:`~function.__module__`
is retrieved from *globals*. The argument defaults, annotations and closure are
set to ``NULL``. *__qualname__* is set to the same value as the code object's
``co_qualname`` field.
set to ``NULL``. :attr:`~function.__qualname__` is set to the same value as
the code object's :attr:`~codeobject.co_qualname` field.
.. c:function:: PyObject* PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname)
As :c:func:`PyFunction_New`, but also allows setting the function object's
``__qualname__`` attribute. *qualname* should be a unicode object or ``NULL``;
if ``NULL``, the ``__qualname__`` attribute is set to the same value as the
code object's ``co_qualname`` field.
:attr:`~function.__qualname__` attribute.
*qualname* should be a unicode object or ``NULL``;
if ``NULL``, the :attr:`!__qualname__` attribute is set to the same value as
the code object's :attr:`~codeobject.co_qualname` field.
.. versionadded:: 3.3
@ -62,11 +64,12 @@ There are a few functions specific to Python functions.
.. c:function:: PyObject* PyFunction_GetModule(PyObject *op)
Return a :term:`borrowed reference` to the *__module__* attribute of the
function object *op*. It can be *NULL*.
Return a :term:`borrowed reference` to the :attr:`~function.__module__`
attribute of the :ref:`function object <user-defined-funcs>` *op*.
It can be *NULL*.
This is normally a string containing the module name, but can be set to any
other object by Python code.
This is normally a :class:`string <str>` containing the module name,
but can be set to any other object by Python code.
.. c:function:: PyObject* PyFunction_GetDefaults(PyObject *op)

View file

@ -45,4 +45,17 @@ See also the :c:member:`PyTypeObject.tp_hash` member.
Get the hash function definition.
.. seealso::
:pep:`456` "Secure and interchangeable hash algorithm".
.. versionadded:: 3.4
.. c:function:: Py_hash_t Py_HashPointer(const void *ptr)
Hash a pointer value: process the pointer value as an integer (cast it to
``uintptr_t`` internally). The pointer is not dereferenced.
The function cannot fail: it cannot return ``-1``.
.. versionadded:: 3.13

View file

@ -154,7 +154,7 @@ Importing Modules
:class:`~importlib.machinery.SourceFileLoader` otherwise.
The module's :attr:`__file__` attribute will be set to the code object's
:attr:`!co_filename`. If applicable, :attr:`__cached__` will also
:attr:`~codeobject.co_filename`. If applicable, :attr:`__cached__` will also
be set.
This function will reload the module if it was already imported. See

View file

@ -1662,7 +1662,8 @@ Python-level trace functions in previous versions.
The value passed as the *what* parameter to a :c:type:`Py_tracefunc` function
(but not a profiling function) when a line-number event is being reported.
It may be disabled for a frame by setting :attr:`f_trace_lines` to *0* on that frame.
It may be disabled for a frame by setting :attr:`~frame.f_trace_lines` to
*0* on that frame.
.. c:var:: int PyTrace_RETURN
@ -1694,7 +1695,7 @@ Python-level trace functions in previous versions.
The value for the *what* parameter to :c:type:`Py_tracefunc` functions (but not
profiling functions) when a new opcode is about to be executed. This event is
not emitted by default: it must be explicitly requested by setting
:attr:`f_trace_opcodes` to *1* on the frame.
:attr:`~frame.f_trace_opcodes` to *1* on the frame.
.. c:function:: void PyEval_SetProfile(Py_tracefunc func, PyObject *obj)

View file

@ -34,6 +34,9 @@ of Python objects.
Set the object *o* reference counter to *refcnt*.
On :ref:`Python build with Free Threading <free-threading-build>`, if
*refcnt* is larger than ``UINT32_MAX``, the object is made :term:`immortal`.
This function has no effect on :term:`immortal` objects.
.. versionadded:: 3.9

View file

@ -147,7 +147,7 @@ subtypes but not for instances of :class:`frozenset` or its subtypes.
Return ``1`` if found and removed, ``0`` if not found (no action taken), and ``-1`` if an
error is encountered. Does not raise :exc:`KeyError` for missing keys. Raise a
:exc:`TypeError` if the *key* is unhashable. Unlike the Python :meth:`~set.discard`
:exc:`TypeError` if the *key* is unhashable. Unlike the Python :meth:`~frozenset.discard`
method, this function does not automatically convert unhashable sets into
temporary frozensets. Raise :exc:`SystemError` if *set* is not an
instance of :class:`set` or its subtype.

View file

@ -419,15 +419,15 @@ Accessing attributes of extension types
The string should be static, no copy is made of it.
.. c:member:: Py_ssize_t offset
The offset in bytes that the member is located on the types object struct.
.. c:member:: int type
The type of the member in the C struct.
See :ref:`PyMemberDef-types` for the possible values.
.. c:member:: Py_ssize_t offset
The offset in bytes that the member is located on the types object struct.
.. c:member:: int flags
Zero or more of the :ref:`PyMemberDef-flags`, combined using bitwise OR.
@ -592,7 +592,7 @@ Macro name C type Python type
(*): Zero-terminated, UTF8-encoded C string.
With :c:macro:`!Py_T_STRING` the C representation is a pointer;
with :c:macro:`!Py_T_STRING_INLINE` the string is stored directly
with :c:macro:`!Py_T_STRING_INPLACE` the string is stored directly
in the structure.
(**): String of length 1. Only ASCII is accepted.

View file

@ -343,13 +343,13 @@ slot typedefs
| | :c:type:`PyTypeObject` * | |
| | :c:type:`Py_ssize_t` | |
+-----------------------------+-----------------------------+----------------------+
| :c:type:`destructor` | void * | void |
| :c:type:`destructor` | :c:type:`PyObject` * | void |
+-----------------------------+-----------------------------+----------------------+
| :c:type:`freefunc` | void * | void |
+-----------------------------+-----------------------------+----------------------+
| :c:type:`traverseproc` | .. line-block:: | int |
| | | |
| | void * | |
| | :c:type:`PyObject` * | |
| | :c:type:`visitproc` | |
| | void * | |
+-----------------------------+-----------------------------+----------------------+
@ -426,7 +426,7 @@ slot typedefs
| | :c:type:`PyObject` * | |
| | :c:type:`Py_buffer` * | |
+-----------------------------+-----------------------------+----------------------+
| :c:type:`inquiry` | void * | int |
| :c:type:`inquiry` | :c:type:`PyObject` * | int |
+-----------------------------+-----------------------------+----------------------+
| :c:type:`unaryfunc` | .. line-block:: | :c:type:`PyObject` * |
| | | |

View file

@ -75,19 +75,19 @@ Python:
The following APIs are C macros and static inlined functions for fast checks and
access to internal read-only data of Unicode objects:
.. c:function:: int PyUnicode_Check(PyObject *o)
.. c:function:: int PyUnicode_Check(PyObject *obj)
Return true if the object *o* is a Unicode object or an instance of a Unicode
Return true if the object *obj* is a Unicode object or an instance of a Unicode
subtype. This function always succeeds.
.. c:function:: int PyUnicode_CheckExact(PyObject *o)
.. c:function:: int PyUnicode_CheckExact(PyObject *obj)
Return true if the object *o* is a Unicode object, but not an instance of a
Return true if the object *obj* is a Unicode object, but not an instance of a
subtype. This function always succeeds.
.. c:function:: int PyUnicode_READY(PyObject *o)
.. c:function:: int PyUnicode_READY(PyObject *unicode)
Returns ``0``. This API is kept only for backward compatibility.
@ -97,17 +97,17 @@ access to internal read-only data of Unicode objects:
This API does nothing since Python 3.12.
.. c:function:: Py_ssize_t PyUnicode_GET_LENGTH(PyObject *o)
.. c:function:: Py_ssize_t PyUnicode_GET_LENGTH(PyObject *unicode)
Return the length of the Unicode string, in code points. *o* has to be a
Return the length of the Unicode string, in code points. *unicode* has to be a
Unicode object in the "canonical" representation (not checked).
.. versionadded:: 3.3
.. c:function:: Py_UCS1* PyUnicode_1BYTE_DATA(PyObject *o)
Py_UCS2* PyUnicode_2BYTE_DATA(PyObject *o)
Py_UCS4* PyUnicode_4BYTE_DATA(PyObject *o)
.. c:function:: Py_UCS1* PyUnicode_1BYTE_DATA(PyObject *unicode)
Py_UCS2* PyUnicode_2BYTE_DATA(PyObject *unicode)
Py_UCS4* PyUnicode_4BYTE_DATA(PyObject *unicode)
Return a pointer to the canonical representation cast to UCS1, UCS2 or UCS4
integer types for direct character access. No checks are performed if the
@ -129,18 +129,18 @@ access to internal read-only data of Unicode objects:
``PyUnicode_WCHAR_KIND`` has been removed.
.. c:function:: int PyUnicode_KIND(PyObject *o)
.. c:function:: int PyUnicode_KIND(PyObject *unicode)
Return one of the PyUnicode kind constants (see above) that indicate how many
bytes per character this Unicode object uses to store its data. *o* has to
bytes per character this Unicode object uses to store its data. *unicode* has to
be a Unicode object in the "canonical" representation (not checked).
.. versionadded:: 3.3
.. c:function:: void* PyUnicode_DATA(PyObject *o)
.. c:function:: void* PyUnicode_DATA(PyObject *unicode)
Return a void pointer to the raw Unicode buffer. *o* has to be a Unicode
Return a void pointer to the raw Unicode buffer. *unicode* has to be a Unicode
object in the "canonical" representation (not checked).
.. versionadded:: 3.3
@ -168,25 +168,25 @@ access to internal read-only data of Unicode objects:
.. versionadded:: 3.3
.. c:function:: Py_UCS4 PyUnicode_READ_CHAR(PyObject *o, Py_ssize_t index)
.. c:function:: Py_UCS4 PyUnicode_READ_CHAR(PyObject *unicode, Py_ssize_t index)
Read a character from a Unicode object *o*, which must be in the "canonical"
Read a character from a Unicode object *unicode*, which must be in the "canonical"
representation. This is less efficient than :c:func:`PyUnicode_READ` if you
do multiple consecutive reads.
.. versionadded:: 3.3
.. c:function:: Py_UCS4 PyUnicode_MAX_CHAR_VALUE(PyObject *o)
.. c:function:: Py_UCS4 PyUnicode_MAX_CHAR_VALUE(PyObject *unicode)
Return the maximum code point that is suitable for creating another string
based on *o*, which must be in the "canonical" representation. This is
based on *unicode*, which must be in the "canonical" representation. This is
always an approximation but more efficient than iterating over the string.
.. versionadded:: 3.3
.. c:function:: int PyUnicode_IsIdentifier(PyObject *o)
.. c:function:: int PyUnicode_IsIdentifier(PyObject *unicode)
Return ``1`` if the string is a valid identifier according to the language
definition, section :ref:`identifiers`. Return ``0`` otherwise.
@ -358,9 +358,9 @@ APIs:
.. versionadded:: 3.3
.. c:function:: PyObject* PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
.. c:function:: PyObject* PyUnicode_FromStringAndSize(const char *str, Py_ssize_t size)
Create a Unicode object from the char buffer *u*. The bytes will be
Create a Unicode object from the char buffer *str*. The bytes will be
interpreted as being UTF-8 encoded. The buffer is copied into the new
object.
The return value might be a shared object, i.e. modification of the data is
@ -369,16 +369,16 @@ APIs:
This function raises :exc:`SystemError` when:
* *size* < 0,
* *u* is ``NULL`` and *size* > 0
* *str* is ``NULL`` and *size* > 0
.. versionchanged:: 3.12
*u* == ``NULL`` with *size* > 0 is not allowed anymore.
*str* == ``NULL`` with *size* > 0 is not allowed anymore.
.. c:function:: PyObject *PyUnicode_FromString(const char *u)
.. c:function:: PyObject *PyUnicode_FromString(const char *str)
Create a Unicode object from a UTF-8 encoded null-terminated char buffer
*u*.
*str*.
.. c:function:: PyObject* PyUnicode_FromFormat(const char *format, ...)
@ -646,29 +646,29 @@ APIs:
.. versionadded:: 3.3
.. c:function:: PyObject* PyUnicode_Substring(PyObject *str, Py_ssize_t start, \
.. c:function:: PyObject* PyUnicode_Substring(PyObject *unicode, Py_ssize_t start, \
Py_ssize_t end)
Return a substring of *str*, from character index *start* (included) to
Return a substring of *unicode*, from character index *start* (included) to
character index *end* (excluded). Negative indices are not supported.
.. versionadded:: 3.3
.. c:function:: Py_UCS4* PyUnicode_AsUCS4(PyObject *u, Py_UCS4 *buffer, \
.. c:function:: Py_UCS4* PyUnicode_AsUCS4(PyObject *unicode, Py_UCS4 *buffer, \
Py_ssize_t buflen, int copy_null)
Copy the string *u* into a UCS4 buffer, including a null character, if
Copy the string *unicode* into a UCS4 buffer, including a null character, if
*copy_null* is set. Returns ``NULL`` and sets an exception on error (in
particular, a :exc:`SystemError` if *buflen* is smaller than the length of
*u*). *buffer* is returned on success.
*unicode*). *buffer* is returned on success.
.. versionadded:: 3.3
.. c:function:: Py_UCS4* PyUnicode_AsUCS4Copy(PyObject *u)
.. c:function:: Py_UCS4* PyUnicode_AsUCS4Copy(PyObject *unicode)
Copy the string *u* into a new UCS4 buffer that is allocated using
Copy the string *unicode* into a new UCS4 buffer that is allocated using
:c:func:`PyMem_Malloc`. If this fails, ``NULL`` is returned with a
:exc:`MemoryError` set. The returned buffer always has an extra
null code point appended.
@ -683,7 +683,7 @@ The current locale encoding can be used to decode text from the operating
system.
.. c:function:: PyObject* PyUnicode_DecodeLocaleAndSize(const char *str, \
Py_ssize_t len, \
Py_ssize_t length, \
const char *errors)
Decode a string from UTF-8 on Android and VxWorks, or from the current
@ -788,7 +788,7 @@ conversion function:
Accepts a :term:`path-like object`.
.. c:function:: PyObject* PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
.. c:function:: PyObject* PyUnicode_DecodeFSDefaultAndSize(const char *str, Py_ssize_t size)
Decode a string from the :term:`filesystem encoding and error handler`.
@ -804,7 +804,7 @@ conversion function:
handler>` is now used.
.. c:function:: PyObject* PyUnicode_DecodeFSDefault(const char *s)
.. c:function:: PyObject* PyUnicode_DecodeFSDefault(const char *str)
Decode a null-terminated string from the :term:`filesystem encoding and
error handler`.
@ -841,17 +841,17 @@ wchar_t Support
:c:type:`wchar_t` support for platforms which support it:
.. c:function:: PyObject* PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
.. c:function:: PyObject* PyUnicode_FromWideChar(const wchar_t *wstr, Py_ssize_t size)
Create a Unicode object from the :c:type:`wchar_t` buffer *w* of the given *size*.
Create a Unicode object from the :c:type:`wchar_t` buffer *wstr* of the given *size*.
Passing ``-1`` as the *size* indicates that the function must itself compute the length,
using wcslen.
using :c:func:`!wcslen`.
Return ``NULL`` on failure.
.. c:function:: Py_ssize_t PyUnicode_AsWideChar(PyObject *unicode, wchar_t *w, Py_ssize_t size)
.. c:function:: Py_ssize_t PyUnicode_AsWideChar(PyObject *unicode, wchar_t *wstr, Py_ssize_t size)
Copy the Unicode object contents into the :c:type:`wchar_t` buffer *w*. At most
Copy the Unicode object contents into the :c:type:`wchar_t` buffer *wstr*. At most
*size* :c:type:`wchar_t` characters are copied (excluding a possibly trailing
null termination character). Return the number of :c:type:`wchar_t` characters
copied or ``-1`` in case of an error. Note that the resulting :c:expr:`wchar_t*`
@ -915,10 +915,10 @@ Generic Codecs
These are the generic codec APIs:
.. c:function:: PyObject* PyUnicode_Decode(const char *s, Py_ssize_t size, \
.. c:function:: PyObject* PyUnicode_Decode(const char *str, Py_ssize_t size, \
const char *encoding, const char *errors)
Create a Unicode object by decoding *size* bytes of the encoded string *s*.
Create a Unicode object by decoding *size* bytes of the encoded string *str*.
*encoding* and *errors* have the same meaning as the parameters of the same name
in the :func:`str` built-in function. The codec to be used is looked up
using the Python codec registry. Return ``NULL`` if an exception was raised by
@ -941,13 +941,13 @@ UTF-8 Codecs
These are the UTF-8 codec APIs:
.. c:function:: PyObject* PyUnicode_DecodeUTF8(const char *s, Py_ssize_t size, const char *errors)
.. c:function:: PyObject* PyUnicode_DecodeUTF8(const char *str, Py_ssize_t size, const char *errors)
Create a Unicode object by decoding *size* bytes of the UTF-8 encoded string
*s*. Return ``NULL`` if an exception was raised by the codec.
*str*. Return ``NULL`` if an exception was raised by the codec.
.. c:function:: PyObject* PyUnicode_DecodeUTF8Stateful(const char *s, Py_ssize_t size, \
.. c:function:: PyObject* PyUnicode_DecodeUTF8Stateful(const char *str, Py_ssize_t size, \
const char *errors, Py_ssize_t *consumed)
If *consumed* is ``NULL``, behave like :c:func:`PyUnicode_DecodeUTF8`. If
@ -1004,7 +1004,7 @@ UTF-32 Codecs
These are the UTF-32 codec APIs:
.. c:function:: PyObject* PyUnicode_DecodeUTF32(const char *s, Py_ssize_t size, \
.. c:function:: PyObject* PyUnicode_DecodeUTF32(const char *str, Py_ssize_t size, \
const char *errors, int *byteorder)
Decode *size* bytes from a UTF-32 encoded buffer string and return the
@ -1031,7 +1031,7 @@ These are the UTF-32 codec APIs:
Return ``NULL`` if an exception was raised by the codec.
.. c:function:: PyObject* PyUnicode_DecodeUTF32Stateful(const char *s, Py_ssize_t size, \
.. c:function:: PyObject* PyUnicode_DecodeUTF32Stateful(const char *str, Py_ssize_t size, \
const char *errors, int *byteorder, Py_ssize_t *consumed)
If *consumed* is ``NULL``, behave like :c:func:`PyUnicode_DecodeUTF32`. If
@ -1054,7 +1054,7 @@ UTF-16 Codecs
These are the UTF-16 codec APIs:
.. c:function:: PyObject* PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, \
.. c:function:: PyObject* PyUnicode_DecodeUTF16(const char *str, Py_ssize_t size, \
const char *errors, int *byteorder)
Decode *size* bytes from a UTF-16 encoded buffer string and return the
@ -1082,7 +1082,7 @@ These are the UTF-16 codec APIs:
Return ``NULL`` if an exception was raised by the codec.
.. c:function:: PyObject* PyUnicode_DecodeUTF16Stateful(const char *s, Py_ssize_t size, \
.. c:function:: PyObject* PyUnicode_DecodeUTF16Stateful(const char *str, Py_ssize_t size, \
const char *errors, int *byteorder, Py_ssize_t *consumed)
If *consumed* is ``NULL``, behave like :c:func:`PyUnicode_DecodeUTF16`. If
@ -1105,13 +1105,13 @@ UTF-7 Codecs
These are the UTF-7 codec APIs:
.. c:function:: PyObject* PyUnicode_DecodeUTF7(const char *s, Py_ssize_t size, const char *errors)
.. c:function:: PyObject* PyUnicode_DecodeUTF7(const char *str, Py_ssize_t size, const char *errors)
Create a Unicode object by decoding *size* bytes of the UTF-7 encoded string
*s*. Return ``NULL`` if an exception was raised by the codec.
*str*. Return ``NULL`` if an exception was raised by the codec.
.. c:function:: PyObject* PyUnicode_DecodeUTF7Stateful(const char *s, Py_ssize_t size, \
.. c:function:: PyObject* PyUnicode_DecodeUTF7Stateful(const char *str, Py_ssize_t size, \
const char *errors, Py_ssize_t *consumed)
If *consumed* is ``NULL``, behave like :c:func:`PyUnicode_DecodeUTF7`. If
@ -1126,11 +1126,11 @@ Unicode-Escape Codecs
These are the "Unicode Escape" codec APIs:
.. c:function:: PyObject* PyUnicode_DecodeUnicodeEscape(const char *s, \
.. c:function:: PyObject* PyUnicode_DecodeUnicodeEscape(const char *str, \
Py_ssize_t size, const char *errors)
Create a Unicode object by decoding *size* bytes of the Unicode-Escape encoded
string *s*. Return ``NULL`` if an exception was raised by the codec.
string *str*. Return ``NULL`` if an exception was raised by the codec.
.. c:function:: PyObject* PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
@ -1146,11 +1146,11 @@ Raw-Unicode-Escape Codecs
These are the "Raw Unicode Escape" codec APIs:
.. c:function:: PyObject* PyUnicode_DecodeRawUnicodeEscape(const char *s, \
.. c:function:: PyObject* PyUnicode_DecodeRawUnicodeEscape(const char *str, \
Py_ssize_t size, const char *errors)
Create a Unicode object by decoding *size* bytes of the Raw-Unicode-Escape
encoded string *s*. Return ``NULL`` if an exception was raised by the codec.
encoded string *str*. Return ``NULL`` if an exception was raised by the codec.
.. c:function:: PyObject* PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
@ -1167,10 +1167,10 @@ These are the Latin-1 codec APIs: Latin-1 corresponds to the first 256 Unicode
ordinals and only these are accepted by the codecs during encoding.
.. c:function:: PyObject* PyUnicode_DecodeLatin1(const char *s, Py_ssize_t size, const char *errors)
.. c:function:: PyObject* PyUnicode_DecodeLatin1(const char *str, Py_ssize_t size, const char *errors)
Create a Unicode object by decoding *size* bytes of the Latin-1 encoded string
*s*. Return ``NULL`` if an exception was raised by the codec.
*str*. Return ``NULL`` if an exception was raised by the codec.
.. c:function:: PyObject* PyUnicode_AsLatin1String(PyObject *unicode)
@ -1187,10 +1187,10 @@ These are the ASCII codec APIs. Only 7-bit ASCII data is accepted. All other
codes generate errors.
.. c:function:: PyObject* PyUnicode_DecodeASCII(const char *s, Py_ssize_t size, const char *errors)
.. c:function:: PyObject* PyUnicode_DecodeASCII(const char *str, Py_ssize_t size, const char *errors)
Create a Unicode object by decoding *size* bytes of the ASCII encoded string
*s*. Return ``NULL`` if an exception was raised by the codec.
*str*. Return ``NULL`` if an exception was raised by the codec.
.. c:function:: PyObject* PyUnicode_AsASCIIString(PyObject *unicode)
@ -1211,10 +1211,10 @@ decode characters. The mapping objects provided must support the
These are the mapping codec APIs:
.. c:function:: PyObject* PyUnicode_DecodeCharmap(const char *data, Py_ssize_t size, \
.. c:function:: PyObject* PyUnicode_DecodeCharmap(const char *str, Py_ssize_t length, \
PyObject *mapping, const char *errors)
Create a Unicode object by decoding *size* bytes of the encoded string *s*
Create a Unicode object by decoding *size* bytes of the encoded string *str*
using the given *mapping* object. Return ``NULL`` if an exception was raised
by the codec.
@ -1241,7 +1241,7 @@ These are the mapping codec APIs:
The following codec API is special in that maps Unicode to Unicode.
.. c:function:: PyObject* PyUnicode_Translate(PyObject *str, PyObject *table, const char *errors)
.. c:function:: PyObject* PyUnicode_Translate(PyObject *unicode, PyObject *table, const char *errors)
Translate a string by applying a character mapping table to it and return the
resulting Unicode object. Return ``NULL`` if an exception was raised by the
@ -1266,13 +1266,13 @@ use the Win32 MBCS converters to implement the conversions. Note that MBCS (or
DBCS) is a class of encodings, not just one. The target encoding is defined by
the user settings on the machine running the codec.
.. c:function:: PyObject* PyUnicode_DecodeMBCS(const char *s, Py_ssize_t size, const char *errors)
.. c:function:: PyObject* PyUnicode_DecodeMBCS(const char *str, Py_ssize_t size, const char *errors)
Create a Unicode object by decoding *size* bytes of the MBCS encoded string *s*.
Create a Unicode object by decoding *size* bytes of the MBCS encoded string *str*.
Return ``NULL`` if an exception was raised by the codec.
.. c:function:: PyObject* PyUnicode_DecodeMBCSStateful(const char *s, Py_ssize_t size, \
.. c:function:: PyObject* PyUnicode_DecodeMBCSStateful(const char *str, Py_ssize_t size, \
const char *errors, Py_ssize_t *consumed)
If *consumed* is ``NULL``, behave like :c:func:`PyUnicode_DecodeMBCS`. If
@ -1318,7 +1318,7 @@ They all return ``NULL`` or ``-1`` if an exception occurs.
Concat two strings giving a new Unicode string.
.. c:function:: PyObject* PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
.. c:function:: PyObject* PyUnicode_Split(PyObject *unicode, PyObject *sep, Py_ssize_t maxsplit)
Split a string giving a list of Unicode strings. If *sep* is ``NULL``, splitting
will be done at all whitespace substrings. Otherwise, splits occur at the given
@ -1326,10 +1326,10 @@ They all return ``NULL`` or ``-1`` if an exception occurs.
set. Separators are not included in the resulting list.
.. c:function:: PyObject* PyUnicode_Splitlines(PyObject *s, int keepend)
.. c:function:: PyObject* PyUnicode_Splitlines(PyObject *unicode, int keepends)
Split a Unicode string at line breaks, returning a list of Unicode strings.
CRLF is considered to be one line break. If *keepend* is ``0``, the line break
CRLF is considered to be one line break. If *keepends* is ``0``, the Line break
characters are not included in the resulting strings.
@ -1339,28 +1339,28 @@ They all return ``NULL`` or ``-1`` if an exception occurs.
Unicode string.
.. c:function:: Py_ssize_t PyUnicode_Tailmatch(PyObject *str, PyObject *substr, \
.. c:function:: Py_ssize_t PyUnicode_Tailmatch(PyObject *unicode, PyObject *substr, \
Py_ssize_t start, Py_ssize_t end, int direction)
Return ``1`` if *substr* matches ``str[start:end]`` at the given tail end
Return ``1`` if *substr* matches ``unicode[start:end]`` at the given tail end
(*direction* == ``-1`` means to do a prefix match, *direction* == ``1`` a suffix match),
``0`` otherwise. Return ``-1`` if an error occurred.
.. c:function:: Py_ssize_t PyUnicode_Find(PyObject *str, PyObject *substr, \
.. c:function:: Py_ssize_t PyUnicode_Find(PyObject *unicode, PyObject *substr, \
Py_ssize_t start, Py_ssize_t end, int direction)
Return the first position of *substr* in ``str[start:end]`` using the given
Return the first position of *substr* in ``unicode[start:end]`` using the given
*direction* (*direction* == ``1`` means to do a forward search, *direction* == ``-1`` a
backward search). The return value is the index of the first match; a value of
``-1`` indicates that no match was found, and ``-2`` indicates that an error
occurred and an exception has been set.
.. c:function:: Py_ssize_t PyUnicode_FindChar(PyObject *str, Py_UCS4 ch, \
.. c:function:: Py_ssize_t PyUnicode_FindChar(PyObject *unicode, Py_UCS4 ch, \
Py_ssize_t start, Py_ssize_t end, int direction)
Return the first position of the character *ch* in ``str[start:end]`` using
Return the first position of the character *ch* in ``unicode[start:end]`` using
the given *direction* (*direction* == ``1`` means to do a forward search,
*direction* == ``-1`` a backward search). The return value is the index of the
first match; a value of ``-1`` indicates that no match was found, and ``-2``
@ -1369,20 +1369,20 @@ They all return ``NULL`` or ``-1`` if an exception occurs.
.. versionadded:: 3.3
.. versionchanged:: 3.7
*start* and *end* are now adjusted to behave like ``str[start:end]``.
*start* and *end* are now adjusted to behave like ``unicode[start:end]``.
.. c:function:: Py_ssize_t PyUnicode_Count(PyObject *str, PyObject *substr, \
.. c:function:: Py_ssize_t PyUnicode_Count(PyObject *unicode, PyObject *substr, \
Py_ssize_t start, Py_ssize_t end)
Return the number of non-overlapping occurrences of *substr* in
``str[start:end]``. Return ``-1`` if an error occurred.
``unicode[start:end]``. Return ``-1`` if an error occurred.
.. c:function:: PyObject* PyUnicode_Replace(PyObject *str, PyObject *substr, \
.. c:function:: PyObject* PyUnicode_Replace(PyObject *unicode, PyObject *substr, \
PyObject *replstr, Py_ssize_t maxcount)
Replace at most *maxcount* occurrences of *substr* in *str* with *replstr* and
Replace at most *maxcount* occurrences of *substr* in *unicode* with *replstr* and
return the resulting Unicode object. *maxcount* == ``-1`` means replace all
occurrences.
@ -1418,9 +1418,9 @@ They all return ``NULL`` or ``-1`` if an exception occurs.
.. versionadded:: 3.13
.. c:function:: int PyUnicode_CompareWithASCIIString(PyObject *uni, const char *string)
.. c:function:: int PyUnicode_CompareWithASCIIString(PyObject *unicode, const char *string)
Compare a Unicode object, *uni*, with *string* and return ``-1``, ``0``, ``1`` for less
Compare a Unicode object, *unicode*, with *string* and return ``-1``, ``0``, ``1`` for less
than, equal, and greater than, respectively. It is best to pass only
ASCII-encoded strings, but the function interprets the input string as
ISO-8859-1 if it contains non-ASCII characters.
@ -1428,7 +1428,7 @@ They all return ``NULL`` or ``-1`` if an exception occurs.
This function does not raise exceptions.
.. c:function:: PyObject* PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
.. c:function:: PyObject* PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Rich compare two Unicode strings and return one of the following:
@ -1446,29 +1446,29 @@ They all return ``NULL`` or ``-1`` if an exception occurs.
``format % args``.
.. c:function:: int PyUnicode_Contains(PyObject *container, PyObject *element)
.. c:function:: int PyUnicode_Contains(PyObject *unicode, PyObject *substr)
Check whether *element* is contained in *container* and return true or false
Check whether *substr* is contained in *unicode* and return true or false
accordingly.
*element* has to coerce to a one element Unicode string. ``-1`` is returned
*substr* has to coerce to a one element Unicode string. ``-1`` is returned
if there was an error.
.. c:function:: void PyUnicode_InternInPlace(PyObject **string)
.. c:function:: void PyUnicode_InternInPlace(PyObject **p_unicode)
Intern the argument *\*string* in place. The argument must be the address of a
Intern the argument :c:expr:`*p_unicode` in place. The argument must be the address of a
pointer variable pointing to a Python Unicode string object. If there is an
existing interned string that is the same as *\*string*, it sets *\*string* to
existing interned string that is the same as :c:expr:`*p_unicode`, it sets :c:expr:`*p_unicode` to
it (releasing the reference to the old string object and creating a new
:term:`strong reference` to the interned string object), otherwise it leaves
*\*string* alone and interns it (creating a new :term:`strong reference`).
:c:expr:`*p_unicode` alone and interns it (creating a new :term:`strong reference`).
(Clarification: even though there is a lot of talk about references, think
of this function as reference-neutral; you own the object after the call
if and only if you owned it before the call.)
.. c:function:: PyObject* PyUnicode_InternFromString(const char *v)
.. c:function:: PyObject* PyUnicode_InternFromString(const char *str)
A combination of :c:func:`PyUnicode_FromString` and
:c:func:`PyUnicode_InternInPlace`, returning either a new Unicode string

View file

@ -24,7 +24,13 @@
'sphinx.ext.doctest',
]
# Skip if downstream redistributors haven't installed it
# Skip if downstream redistributors haven't installed them
try:
import notfound.extension
except ImportError:
pass
else:
extensions.append('notfound.extension')
try:
import sphinxext.opengraph
except ImportError:
@ -157,6 +163,13 @@
('envvar', 'USER'),
('envvar', 'USERNAME'),
('envvar', 'USERPROFILE'),
# Deprecated function that was never documented:
('py:func', 'getargspec'),
('py:func', 'inspect.getargspec'),
# Undocumented modules that users shouldn't have to worry about
# (implementation details of `os.path`):
('py:mod', 'ntpath'),
('py:mod', 'posixpath'),
]
# Temporary undocumented names.
@ -232,6 +245,12 @@
# be resolved, as the method is currently undocumented. For context, see
# https://github.com/python/cpython/pull/103289.
('py:meth', '_SubParsersAction.add_parser'),
# Attributes/methods/etc. that definitely should be documented better,
# but are deferred for now:
('py:attr', '__annotations__'),
('py:meth', '__missing__'),
('py:attr', '__wrapped__'),
('py:meth', 'index'), # list.index, tuple.index, etc.
]
# gh-106948: Copy standard C types declared in the "c:type" domain to the

View file

@ -1589,6 +1589,13 @@ PyObject_Call:PyObject*:callable_object:0:
PyObject_Call:PyObject*:args:0:
PyObject_Call:PyObject*:kw:0:
PyObject_CallNoArgs:PyObject*::+1:
PyObject_CallNoArgs:PyObject*:callable_object:0:
PyObject_CallOneArg:PyObject*::+1:
PyObject_CallOneArg:PyObject*:callable_object:0:
PyObject_CallOneArg:PyObject*:arg:0:
PyObject_CallFunction:PyObject*::+1:
PyObject_CallFunction:PyObject*:callable_object:0:
PyObject_CallFunction:const char*:format::

View file

@ -735,7 +735,7 @@ Keyword Parameters for Extension Functions
The :c:func:`PyArg_ParseTupleAndKeywords` function is declared as follows::
int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict,
const char *format, char *kwlist[], ...);
const char *format, char * const *kwlist, ...);
The *arg* and *format* parameters are identical to those of the
:c:func:`PyArg_ParseTuple` function. The *kwdict* parameter is the dictionary of

View file

@ -296,7 +296,7 @@ An interesting advantage of using the :c:member:`~PyTypeObject.tp_members` table
descriptors that are used at runtime is that any attribute defined this way can
have an associated doc string simply by providing the text in the table. An
application can use the introspection API to retrieve the descriptor from the
class object, and get the doc string using its :attr:`__doc__` attribute.
class object, and get the doc string using its :attr:`!__doc__` attribute.
As with the :c:member:`~PyTypeObject.tp_methods` table, a sentinel entry with a :c:member:`~PyMethodDef.ml_name` value
of ``NULL`` is required.

View file

@ -151,9 +151,9 @@ Glossary
A :term:`file object` able to read and write
:term:`bytes-like objects <bytes-like object>`.
Examples of binary files are files opened in binary mode (``'rb'``,
``'wb'`` or ``'rb+'``), :data:`sys.stdin.buffer`,
:data:`sys.stdout.buffer`, and instances of :class:`io.BytesIO` and
:class:`gzip.GzipFile`.
``'wb'`` or ``'rb+'``), :data:`sys.stdin.buffer <sys.stdin>`,
:data:`sys.stdout.buffer <sys.stdout>`, and instances of
:class:`io.BytesIO` and :class:`gzip.GzipFile`.
See also :term:`text file` for a file object able to read and write
:class:`str` objects.
@ -304,8 +304,9 @@ Glossary
:ref:`class definitions <class>` for more about decorators.
descriptor
Any object which defines the methods :meth:`__get__`, :meth:`__set__`, or
:meth:`__delete__`. When a class attribute is a descriptor, its special
Any object which defines the methods :meth:`~object.__get__`,
:meth:`~object.__set__`, or :meth:`~object.__delete__`.
When a class attribute is a descriptor, its special
binding behavior is triggered upon attribute lookup. Normally, using
*a.b* to get, set or delete an attribute looks up the object named *b* in
the class dictionary for *a*, but if *b* is a descriptor, the respective
@ -319,7 +320,8 @@ Glossary
dictionary
An associative array, where arbitrary keys are mapped to values. The
keys can be any object with :meth:`__hash__` and :meth:`__eq__` methods.
keys can be any object with :meth:`~object.__hash__` and
:meth:`~object.__eq__` methods.
Called a hash in Perl.
dictionary comprehension
@ -383,7 +385,7 @@ Glossary
file object
An object exposing a file-oriented API (with methods such as
:meth:`read()` or :meth:`write()`) to an underlying resource. Depending
:meth:`!read` or :meth:`!write`) to an underlying resource. Depending
on the way it was created, a file object can mediate access to a real
on-disk file or to another type of storage or communication device
(for example standard input/output, in-memory buffers, sockets, pipes,
@ -502,7 +504,7 @@ Glossary
.. index:: single: generator expression
generator expression
An expression that returns an iterator. It looks like a normal expression
An :term:`expression` that returns an :term:`iterator`. It looks like a normal expression
followed by a :keyword:`!for` clause defining a loop variable, range,
and an optional :keyword:`!if` clause. The combined expression
generates values for an enclosing function::
@ -559,8 +561,9 @@ Glossary
hashable
An object is *hashable* if it has a hash value which never changes during
its lifetime (it needs a :meth:`__hash__` method), and can be compared to
other objects (it needs an :meth:`__eq__` method). Hashable objects which
its lifetime (it needs a :meth:`~object.__hash__` method), and can be
compared to other objects (it needs an :meth:`~object.__eq__` method).
Hashable objects which
compare equal must have the same hash value.
Hashability makes an object usable as a dictionary key and a set member,
@ -646,7 +649,8 @@ Glossary
iterables include all sequence types (such as :class:`list`, :class:`str`,
and :class:`tuple`) and some non-sequence types like :class:`dict`,
:term:`file objects <file object>`, and objects of any classes you define
with an :meth:`__iter__` method or with a :meth:`~object.__getitem__` method
with an :meth:`~iterator.__iter__` method or with a
:meth:`~object.__getitem__` method
that implements :term:`sequence` semantics.
Iterables can be
@ -655,7 +659,7 @@ Glossary
as an argument to the built-in function :func:`iter`, it returns an
iterator for the object. This iterator is good for one pass over the set
of values. When using iterables, it is usually not necessary to call
:func:`iter` or deal with iterator objects yourself. The ``for``
:func:`iter` or deal with iterator objects yourself. The :keyword:`for`
statement does that automatically for you, creating a temporary unnamed
variable to hold the iterator for the duration of the loop. See also
:term:`iterator`, :term:`sequence`, and :term:`generator`.
@ -666,8 +670,8 @@ Glossary
:func:`next`) return successive items in the stream. When no more data
are available a :exc:`StopIteration` exception is raised instead. At this
point, the iterator object is exhausted and any further calls to its
:meth:`__next__` method just raise :exc:`StopIteration` again. Iterators
are required to have an :meth:`__iter__` method that returns the iterator
:meth:`!__next__` method just raise :exc:`StopIteration` again. Iterators
are required to have an :meth:`~iterator.__iter__` method that returns the iterator
object itself so every iterator is also iterable and may be used in most
places where other iterables are accepted. One notable exception is code
which attempts multiple iteration passes. A container object (such as a
@ -681,7 +685,7 @@ Glossary
.. impl-detail::
CPython does not consistently apply the requirement that an iterator
define :meth:`__iter__`.
define :meth:`~iterator.__iter__`.
key function
A key function or collation function is a callable that returns a value
@ -875,7 +879,8 @@ Glossary
Old name for the flavor of classes now used for all class objects. In
earlier Python versions, only new-style classes could use Python's newer,
versatile features like :attr:`~object.__slots__`, descriptors,
properties, :meth:`__getattribute__`, class methods, and static methods.
properties, :meth:`~object.__getattribute__`, class methods, and static
methods.
object
Any data with state (attributes or value) and defined behavior
@ -955,7 +960,7 @@ Glossary
finders implement.
path entry hook
A callable on the :data:`sys.path_hook` list which returns a :term:`path
A callable on the :data:`sys.path_hooks` list which returns a :term:`path
entry finder` if it knows how to find modules on a specific :term:`path
entry`.
@ -1089,18 +1094,18 @@ Glossary
sequence
An :term:`iterable` which supports efficient element access using integer
indices via the :meth:`~object.__getitem__` special method and defines a
:meth:`__len__` method that returns the length of the sequence.
:meth:`~object.__len__` method that returns the length of the sequence.
Some built-in sequence types are :class:`list`, :class:`str`,
:class:`tuple`, and :class:`bytes`. Note that :class:`dict` also
supports :meth:`~object.__getitem__` and :meth:`__len__`, but is considered a
supports :meth:`~object.__getitem__` and :meth:`!__len__`, but is considered a
mapping rather than a sequence because the lookups use arbitrary
:term:`immutable` keys rather than integers.
The :class:`collections.abc.Sequence` abstract base class
defines a much richer interface that goes beyond just
:meth:`~object.__getitem__` and :meth:`__len__`, adding :meth:`count`,
:meth:`index`, :meth:`__contains__`, and
:meth:`__reversed__`. Types that implement this expanded
:meth:`~object.__getitem__` and :meth:`~object.__len__`, adding
:meth:`count`, :meth:`index`, :meth:`~object.__contains__`, and
:meth:`~object.__reversed__`. Types that implement this expanded
interface can be registered explicitly using
:func:`~abc.ABCMeta.register`.

View file

@ -153,7 +153,8 @@ on an arbitrary object ``o``:
unwrap it by accessing either ``o.__wrapped__`` or ``o.func`` as
appropriate, until you have found the root unwrapped function.
* If ``o`` is a callable (but not a class), use
``o.__globals__`` as the globals when calling :func:`eval`.
:attr:`o.__globals__ <function.__globals__>` as the globals when calling
:func:`eval`.
However, not all string values used as annotations can
be successfully turned into Python values by :func:`eval`.

View file

@ -521,11 +521,11 @@ everyday Python programs.
Descriptor protocol
-------------------
``descr.__get__(self, obj, type=None) -> value``
``descr.__get__(self, obj, type=None)``
``descr.__set__(self, obj, value) -> None``
``descr.__set__(self, obj, value)``
``descr.__delete__(self, obj) -> None``
``descr.__delete__(self, obj)``
That is all there is to it. Define any of these methods and an object is
considered a descriptor and can override default behavior upon being looked up
@ -1013,17 +1013,23 @@ here is a pure Python equivalent:
if obj is None:
return self
if self.fget is None:
raise AttributeError(f"property '{self._name}' has no getter")
raise AttributeError(
f'property {self._name!r} of {type(obj).__name__!r} object has no getter'
)
return self.fget(obj)
def __set__(self, obj, value):
if self.fset is None:
raise AttributeError(f"property '{self._name}' has no setter")
raise AttributeError(
f'property {self._name!r} of {type(obj).__name__!r} object has no setter'
)
self.fset(obj, value)
def __delete__(self, obj):
if self.fdel is None:
raise AttributeError(f"property '{self._name}' has no deleter")
raise AttributeError(
f'property {self._name!r} of {type(obj).__name__!r} object has no deleter'
)
self.fdel(obj)
def getter(self, fget):
@ -1054,6 +1060,11 @@ here is a pure Python equivalent:
def delx(self):
del self.__x
x = Property(getx, setx, delx, "I'm the 'x' property.")
no_getter = Property(None, setx, delx, "I'm the 'x' property.")
no_setter = Property(getx, None, delx, "I'm the 'x' property.")
no_deleter = Property(getx, setx, None, "I'm the 'x' property.")
no_doc = Property(getx, setx, delx, None)
# Now do it again but use the decorator style
@ -1092,6 +1103,32 @@ here is a pure Python equivalent:
>>> hasattr(ccc, 'x')
False
>>> cc = CC()
>>> cc.x = 33
>>> try:
... cc.no_getter
... except AttributeError as e:
... e.args[0]
...
"property 'no_getter' of 'CC' object has no getter"
>>> try:
... cc.no_setter = 33
... except AttributeError as e:
... e.args[0]
...
"property 'no_setter' of 'CC' object has no setter"
>>> try:
... del cc.no_deleter
... except AttributeError as e:
... e.args[0]
...
"property 'no_deleter' of 'CC' object has no deleter"
>>> CC.no_doc.__doc__ is None
True
The :func:`property` builtin helps whenever a user interface has granted
attribute access and then subsequent changes require the intervention of a
method.
@ -1305,7 +1342,8 @@ Using the non-data descriptor protocol, a pure Python version of
The :func:`functools.update_wrapper` call adds a ``__wrapped__`` attribute
that refers to the underlying function. Also it carries forward
the attributes necessary to make the wrapper look like the wrapped
function: ``__name__``, ``__qualname__``, ``__doc__``, and ``__annotations__``.
function: :attr:`~function.__name__`, :attr:`~function.__qualname__`,
:attr:`~function.__doc__`, and :attr:`~function.__annotations__`.
.. testcode::
:hide:
@ -1485,8 +1523,9 @@ Using the non-data descriptor protocol, a pure Python version of
The :func:`functools.update_wrapper` call in ``ClassMethod`` adds a
``__wrapped__`` attribute that refers to the underlying function. Also
it carries forward the attributes necessary to make the wrapper look
like the wrapped function: ``__name__``, ``__qualname__``, ``__doc__``,
and ``__annotations__``.
like the wrapped function: :attr:`~function.__name__`,
:attr:`~function.__qualname__`, :attr:`~function.__doc__`,
and :attr:`~function.__annotations__`.
Member objects and __slots__

View file

@ -868,7 +868,7 @@ Others
While :class:`IntEnum` is part of the :mod:`enum` module, it would be very
simple to implement independently::
class IntEnum(int, Enum):
class IntEnum(int, ReprEnum): # or Enum instead of ReprEnum
pass
This demonstrates how similar derived enumerations can be defined; for example
@ -876,8 +876,8 @@ a :class:`FloatEnum` that mixes in :class:`float` instead of :class:`int`.
Some rules:
1. When subclassing :class:`Enum`, mix-in types must appear before
:class:`Enum` itself in the sequence of bases, as in the :class:`IntEnum`
1. When subclassing :class:`Enum`, mix-in types must appear before the
:class:`Enum` class itself in the sequence of bases, as in the :class:`IntEnum`
example above.
2. Mix-in types must be subclassable. For example, :class:`bool` and
:class:`range` are not subclassable and will throw an error during Enum
@ -961,30 +961,34 @@ all the members are created it is no longer used.
Supported ``_sunder_`` names
""""""""""""""""""""""""""""
- ``_name_`` -- name of the member
- ``_value_`` -- value of the member; can be set / modified in ``__new__``
- :attr:`~Enum._name_` -- name of the member
- :attr:`~Enum._value_` -- value of the member; can be set in ``__new__``
- :meth:`~Enum._missing_` -- a lookup function used when a value is not found;
may be overridden
- :attr:`~Enum._ignore_` -- a list of names, either as a :class:`list` or a
:class:`str`, that will not be transformed into members, and will be removed
from the final class
- :meth:`~Enum._generate_next_value_` -- used to get an appropriate value for
an enum member; may be overridden
- :meth:`~Enum._add_alias_` -- adds a new name as an alias to an existing
member.
- :meth:`~Enum._add_value_alias_` -- adds a new value as an alias to an
existing member. See `MultiValueEnum`_ for an example.
- ``_missing_`` -- a lookup function used when a value is not found; may be
overridden
- ``_ignore_`` -- a list of names, either as a :class:`list` or a :class:`str`,
that will not be transformed into members, and will be removed from the final
class
- ``_order_`` -- used in Python 2/3 code to ensure member order is consistent
(class attribute, removed during class creation)
- ``_generate_next_value_`` -- used by the `Functional API`_ and by
:class:`auto` to get an appropriate value for an enum member; may be
overridden
.. note::
.. note::
For standard :class:`Enum` classes the next value chosen is the highest
value seen incremented by one.
For standard :class:`Enum` classes the next value chosen is the last value seen
incremented by one.
For :class:`Flag` classes the next value chosen will be the next highest
power-of-two.
For :class:`Flag` classes the next value chosen will be the next highest
power-of-two, regardless of the last value seen.
.. versionchanged:: 3.13
Prior versions would use the last seen value instead of the highest value.
.. versionadded:: 3.6 ``_missing_``, ``_order_``, ``_generate_next_value_``
.. versionadded:: 3.7 ``_ignore_``
.. versionadded:: 3.13 ``_add_alias_``, ``_add_value_alias_``
To help keep Python 2 / Python 3 code in sync an :attr:`_order_` attribute can
be provided. It will be checked against the actual order of the enumeration
@ -1439,7 +1443,6 @@ alias::
Traceback (most recent call last):
...
ValueError: aliases not allowed in DuplicateFreeEnum: 'GRENE' --> 'GREEN'
Error calling __set_name__ on '_proto_member' instance 'GRENE' in 'Color'
.. note::
@ -1448,6 +1451,29 @@ alias::
disallowing aliases, the :func:`unique` decorator can be used instead.
MultiValueEnum
^^^^^^^^^^^^^^^^^
Supports having more than one value per member::
>>> class MultiValueEnum(Enum):
... def __new__(cls, value, *values):
... self = object.__new__(cls)
... self._value_ = value
... for v in values:
... self._add_value_alias_(v)
... return self
...
>>> class DType(MultiValueEnum):
... float32 = 'f', 8
... double64 = 'd', 9
...
>>> DType('f')
<DType.float32: 'f'>
>>> DType(9)
<DType.double64: 'd'>
Planet
^^^^^^

View file

@ -337,7 +337,7 @@ That is, heap types should:
- Have the :c:macro:`Py_TPFLAGS_HAVE_GC` flag.
- Define a traverse function using ``Py_tp_traverse``, which
visits the type (e.g. using :c:expr:`Py_VISIT(Py_TYPE(self))`).
visits the type (e.g. using ``Py_VISIT(Py_TYPE(self))``).
Please refer to the the documentation of
:c:macro:`Py_TPFLAGS_HAVE_GC` and :c:member:`~PyTypeObject.tp_traverse`
@ -482,7 +482,7 @@ The largest roadblock is getting *the class a method was defined in*, or
that method's "defining class" for short. The defining class can have a
reference to the module it is part of.
Do not confuse the defining class with :c:expr:`Py_TYPE(self)`. If the method
Do not confuse the defining class with ``Py_TYPE(self)``. If the method
is called on a *subclass* of your type, ``Py_TYPE(self)`` will refer to
that subclass, which may be defined in different module than yours.

View file

@ -332,10 +332,10 @@ Suppose you configure logging with the following JSON:
}
}
This configuration does *almost* what we want, except that ``sys.stdout`` would
show messages of severity ``ERROR`` and above as well as ``INFO`` and
``WARNING`` messages. To prevent this, we can set up a filter which excludes
those messages and add it to the relevant handler. This can be configured by
This configuration does *almost* what we want, except that ``sys.stdout`` would show messages
of severity ``ERROR`` and only events of this severity and higher will be tracked
as well as ``INFO`` and ``WARNING`` messages. To prevent this, we can set up a filter which
excludes those messages and add it to the relevant handler. This can be configured by
adding a ``filters`` section parallel to ``formatters`` and ``handlers``:
.. code-block:: json

View file

@ -89,9 +89,8 @@ described below (in increasing order of severity):
| | itself may be unable to continue running. |
+--------------+---------------------------------------------+
The default level is ``WARNING``, which means that only events of this level
and above will be tracked, unless the logging package is configured to do
otherwise.
The default level is ``WARNING``, which means that only events of this severity and higher
will be tracked, unless the logging package is configured to do otherwise.
Events that are tracked can be handled in different ways. The simplest way of
handling tracked events is to print them to the console. Another common way

View file

@ -21,7 +21,7 @@ The :mod:`collections` module has some concrete classes that derive from
ABCs; these can, of course, be further derived. In addition, the
:mod:`collections.abc` submodule has some ABCs that can be used to test whether
a class or instance provides a particular interface, for example, if it is
:term:`hashable` or if it is a mapping.
:term:`hashable` or if it is a :term:`mapping`.
This module provides the metaclass :class:`ABCMeta` for defining ABCs and
@ -30,7 +30,7 @@ a helper class :class:`ABC` to alternatively define ABCs through inheritance:
.. class:: ABC
A helper class that has :class:`ABCMeta` as its metaclass. With this class,
an abstract base class can be created by simply deriving from :class:`ABC`
an abstract base class can be created by simply deriving from :class:`!ABC`
avoiding sometimes confusing metaclass usage, for example::
from abc import ABC
@ -38,11 +38,11 @@ a helper class :class:`ABC` to alternatively define ABCs through inheritance:
class MyABC(ABC):
pass
Note that the type of :class:`ABC` is still :class:`ABCMeta`, therefore
inheriting from :class:`ABC` requires the usual precautions regarding
Note that the type of :class:`!ABC` is still :class:`ABCMeta`, therefore
inheriting from :class:`!ABC` requires the usual precautions regarding
metaclass usage, as multiple inheritance may lead to metaclass conflicts.
One may also define an abstract base class by passing the metaclass
keyword and using :class:`ABCMeta` directly, for example::
keyword and using :class:`!ABCMeta` directly, for example::
from abc import ABCMeta
@ -65,7 +65,7 @@ a helper class :class:`ABC` to alternatively define ABCs through inheritance:
implementations defined by the registering ABC be callable (not even via
:func:`super`). [#]_
Classes created with a metaclass of :class:`ABCMeta` have the following method:
Classes created with a metaclass of :class:`!ABCMeta` have the following method:
.. method:: register(subclass)
@ -86,7 +86,7 @@ a helper class :class:`ABC` to alternatively define ABCs through inheritance:
Returns the registered subclass, to allow usage as a class decorator.
.. versionchanged:: 3.4
To detect calls to :meth:`register`, you can use the
To detect calls to :meth:`!register`, you can use the
:func:`get_cache_token` function.
You can also override this method in an abstract base class:
@ -96,10 +96,10 @@ a helper class :class:`ABC` to alternatively define ABCs through inheritance:
(Must be defined as a class method.)
Check whether *subclass* is considered a subclass of this ABC. This means
that you can customize the behavior of ``issubclass`` further without the
that you can customize the behavior of :func:`issubclass` further without the
need to call :meth:`register` on every class you want to consider a
subclass of the ABC. (This class method is called from the
:meth:`__subclasscheck__` method of the ABC.)
:meth:`~class.__subclasscheck__` method of the ABC.)
This method should return ``True``, ``False`` or ``NotImplemented``. If
it returns ``True``, the *subclass* is considered a subclass of this ABC.
@ -142,7 +142,7 @@ a helper class :class:`ABC` to alternatively define ABCs through inheritance:
The ABC ``MyIterable`` defines the standard iterable method,
:meth:`~iterator.__iter__`, as an abstract method. The implementation given
here can still be called from subclasses. The :meth:`get_iterator` method
here can still be called from subclasses. The :meth:`!get_iterator` method
is also part of the ``MyIterable`` abstract base class, but it does not have
to be overridden in non-abstract derived classes.
@ -153,14 +153,14 @@ a helper class :class:`ABC` to alternatively define ABCs through inheritance:
Finally, the last line makes ``Foo`` a virtual subclass of ``MyIterable``,
even though it does not define an :meth:`~iterator.__iter__` method (it uses
the old-style iterable protocol, defined in terms of :meth:`__len__` and
the old-style iterable protocol, defined in terms of :meth:`~object.__len__` and
:meth:`~object.__getitem__`). Note that this will not make ``get_iterator``
available as a method of ``Foo``, so it is provided separately.
The :mod:`abc` module also provides the following decorator:
The :mod:`!abc` module also provides the following decorator:
.. decorator:: abstractmethod
@ -168,19 +168,19 @@ The :mod:`abc` module also provides the following decorator:
Using this decorator requires that the class's metaclass is :class:`ABCMeta`
or is derived from it. A class that has a metaclass derived from
:class:`ABCMeta` cannot be instantiated unless all of its abstract methods
:class:`!ABCMeta` cannot be instantiated unless all of its abstract methods
and properties are overridden. The abstract methods can be called using any
of the normal 'super' call mechanisms. :func:`abstractmethod` may be used
of the normal 'super' call mechanisms. :func:`!abstractmethod` may be used
to declare abstract methods for properties and descriptors.
Dynamically adding abstract methods to a class, or attempting to modify the
abstraction status of a method or class once it is created, are only
supported using the :func:`update_abstractmethods` function. The
:func:`abstractmethod` only affects subclasses derived using regular
inheritance; "virtual subclasses" registered with the ABC's :meth:`register`
method are not affected.
:func:`!abstractmethod` only affects subclasses derived using regular
inheritance; "virtual subclasses" registered with the ABC's
:meth:`~ABCMeta.register` method are not affected.
When :func:`abstractmethod` is applied in combination with other method
When :func:`!abstractmethod` is applied in combination with other method
descriptors, it should be applied as the innermost decorator, as shown in
the following usage examples::
@ -216,7 +216,7 @@ The :mod:`abc` module also provides the following decorator:
In order to correctly interoperate with the abstract base class machinery,
the descriptor must identify itself as abstract using
:attr:`__isabstractmethod__`. In general, this attribute should be ``True``
:attr:`!__isabstractmethod__`. In general, this attribute should be ``True``
if any of the methods used to compose the descriptor are abstract. For
example, Python's built-in :class:`property` does the equivalent of::
@ -236,7 +236,7 @@ The :mod:`abc` module also provides the following decorator:
super-call in a framework that uses cooperative
multiple-inheritance.
The :mod:`abc` module also supports the following legacy decorators:
The :mod:`!abc` module also supports the following legacy decorators:
.. decorator:: abstractclassmethod
@ -323,7 +323,7 @@ The :mod:`abc` module also supports the following legacy decorators:
...
The :mod:`abc` module also provides the following functions:
The :mod:`!abc` module also provides the following functions:
.. function:: get_cache_token()

View file

@ -45,7 +45,7 @@ Node classes
This is the base of all AST node classes. The actual node classes are
derived from the :file:`Parser/Python.asdl` file, which is reproduced
:ref:`above <abstract-grammar>`. They are defined in the :mod:`_ast` C
:ref:`above <abstract-grammar>`. They are defined in the :mod:`!_ast` C
module and re-exported in :mod:`ast`.
There is one class defined for each left-hand side symbol in the abstract
@ -128,14 +128,14 @@ Node classes
.. deprecated:: 3.8
Old classes :class:`ast.Num`, :class:`ast.Str`, :class:`ast.Bytes`,
:class:`ast.NameConstant` and :class:`ast.Ellipsis` are still available,
Old classes :class:`!ast.Num`, :class:`!ast.Str`, :class:`!ast.Bytes`,
:class:`!ast.NameConstant` and :class:`!ast.Ellipsis` are still available,
but they will be removed in future Python releases. In the meantime,
instantiating them will return an instance of a different class.
.. deprecated:: 3.9
Old classes :class:`ast.Index` and :class:`ast.ExtSlice` are still
Old classes :class:`!ast.Index` and :class:`!ast.ExtSlice` are still
available, but they will be removed in future Python releases.
In the meantime, instantiating them will return an instance of
a different class.
@ -1935,8 +1935,7 @@ Function and class definitions
.. class:: arg(arg, annotation, type_comment)
A single argument in a list. ``arg`` is a raw string of the argument
name, ``annotation`` is its annotation, such as a :class:`Str` or
:class:`Name` node.
name; ``annotation`` is its annotation, such as a :class:`Name` node.
.. attribute:: type_comment
@ -2210,7 +2209,7 @@ and classes for traversing abstract syntax trees:
Added ``type_comments``, ``mode='func_type'`` and ``feature_version``.
.. versionchanged:: 3.13
The minimum supported version for feature_version is now (3,7)
The minimum supported version for ``feature_version`` is now ``(3, 7)``.
The ``optimize`` argument was added.
@ -2286,8 +2285,8 @@ and classes for traversing abstract syntax trees:
.. function:: get_source_segment(source, node, *, padded=False)
Get source code segment of the *source* that generated *node*.
If some location information (:attr:`lineno`, :attr:`end_lineno`,
:attr:`col_offset`, or :attr:`end_col_offset`) is missing, return ``None``.
If some location information (:attr:`~ast.AST.lineno`, :attr:`~ast.AST.end_lineno`,
:attr:`~ast.AST.col_offset`, or :attr:`~ast.AST.end_col_offset`) is missing, return ``None``.
If *padded* is ``True``, the first line of a multi-line statement will
be padded with spaces to match its original position.
@ -2298,7 +2297,7 @@ and classes for traversing abstract syntax trees:
.. function:: fix_missing_locations(node)
When you compile a node tree with :func:`compile`, the compiler expects
:attr:`lineno` and :attr:`col_offset` attributes for every node that supports
:attr:`~ast.AST.lineno` and :attr:`~ast.AST.col_offset` attributes for every node that supports
them. This is rather tedious to fill in for generated nodes, so this helper
adds these attributes recursively where not already set, by setting them to
the values of the parent node. It works recursively starting at *node*.
@ -2313,8 +2312,8 @@ and classes for traversing abstract syntax trees:
.. function:: copy_location(new_node, old_node)
Copy source location (:attr:`lineno`, :attr:`col_offset`, :attr:`end_lineno`,
and :attr:`end_col_offset`) from *old_node* to *new_node* if possible,
Copy source location (:attr:`~ast.AST.lineno`, :attr:`~ast.AST.col_offset`, :attr:`~ast.AST.end_lineno`,
and :attr:`~ast.AST.end_col_offset`) from *old_node* to *new_node* if possible,
and return *new_node*.
@ -2360,14 +2359,18 @@ and classes for traversing abstract syntax trees:
visited unless the visitor calls :meth:`generic_visit` or visits them
itself.
.. method:: visit_Constant(node)
Handles all constant nodes.
Don't use the :class:`NodeVisitor` if you want to apply changes to nodes
during traversal. For this a special visitor exists
(:class:`NodeTransformer`) that allows modifications.
.. deprecated:: 3.8
Methods :meth:`visit_Num`, :meth:`visit_Str`, :meth:`visit_Bytes`,
:meth:`visit_NameConstant` and :meth:`visit_Ellipsis` are deprecated
Methods :meth:`!visit_Num`, :meth:`!visit_Str`, :meth:`!visit_Bytes`,
:meth:`!visit_NameConstant` and :meth:`!visit_Ellipsis` are deprecated
now and will not be called in future Python versions. Add the
:meth:`visit_Constant` method to handle all constant nodes.
@ -2396,7 +2399,7 @@ and classes for traversing abstract syntax trees:
)
Keep in mind that if the node you're operating on has child nodes you must
either transform the child nodes yourself or call the :meth:`generic_visit`
either transform the child nodes yourself or call the :meth:`~ast.NodeVisitor.generic_visit`
method for the node first.
For nodes that were part of a collection of statements (that applies to all
@ -2405,7 +2408,7 @@ and classes for traversing abstract syntax trees:
If :class:`NodeTransformer` introduces new nodes (that weren't part of
original tree) without giving them location information (such as
:attr:`lineno`), :func:`fix_missing_locations` should be called with
:attr:`~ast.AST.lineno`), :func:`fix_missing_locations` should be called with
the new sub-tree to recalculate the location information::
tree = ast.parse('foo', mode='eval')
@ -2457,6 +2460,13 @@ effects on the compilation of a program:
Generates and returns an abstract syntax tree instead of returning a
compiled code object.
.. data:: PyCF_OPTIMIZED_AST
The returned AST is optimized according to the *optimize* argument
in :func:`compile` or :func:`ast.parse`.
.. versionadded:: 3.13
.. data:: PyCF_TYPE_COMMENTS
Enables support for :pep:`484` and :pep:`526` style type comments

View file

@ -671,6 +671,7 @@ Creating network servers
flags=socket.AI_PASSIVE, \
sock=None, backlog=100, ssl=None, \
reuse_address=None, reuse_port=None, \
keep_alive=None, \
ssl_handshake_timeout=None, \
ssl_shutdown_timeout=None, \
start_serving=True)
@ -735,6 +736,13 @@ Creating network servers
set this flag when being created. This option is not supported on
Windows.
* *keep_alive* set to ``True`` keeps connections active by enabling the
periodic transmission of messages.
.. versionchanged:: 3.13
Added the *keep_alive* parameter.
* *ssl_handshake_timeout* is (for a TLS server) the time in seconds to wait
for the TLS handshake to complete before aborting the connection.
``60.0`` seconds if ``None`` (default).

View file

@ -204,6 +204,10 @@ StreamReader
directly; use :func:`open_connection` and :func:`start_server`
instead.
.. method:: feed_eof()
Acknowledge the EOF.
.. coroutinemethod:: read(n=-1)
Read up to *n* bytes from the stream.

View file

@ -294,7 +294,7 @@ The :mod:`bdb` module also defines two classes:
.. method:: set_quit()
Set the :attr:`quitting` attribute to ``True``. This raises :exc:`BdbQuit` in
the next call to one of the :meth:`dispatch_\*` methods.
the next call to one of the :meth:`!dispatch_\*` methods.
Derived classes and clients can call the following methods to manipulate

View file

@ -19,9 +19,9 @@ linear searches or frequent resorting.
The module is called :mod:`bisect` because it uses a basic bisection
algorithm to do its work. Unlike other bisection tools that search for a
specific value, the functions in this module are designed to locate an
insertion point. Accordingly, the functions never call an :meth:`__eq__`
insertion point. Accordingly, the functions never call an :meth:`~object.__eq__`
method to determine whether a value has been found. Instead, the
functions only call the :meth:`__lt__` method and will return an insertion
functions only call the :meth:`~object.__lt__` method and will return an insertion
point between values in an array.
.. _bisect functions:
@ -73,7 +73,7 @@ The following functions are provided:
Insert *x* in *a* in sorted order.
This function first runs :py:func:`~bisect.bisect_left` to locate an insertion point.
Next, it runs the :meth:`insert` method on *a* to insert *x* at the
Next, it runs the :meth:`!insert` method on *a* to insert *x* at the
appropriate position to maintain sort order.
To support inserting records in a table, the *key* function (if any) is
@ -93,7 +93,7 @@ The following functions are provided:
entries of *x*.
This function first runs :py:func:`~bisect.bisect_right` to locate an insertion point.
Next, it runs the :meth:`insert` method on *a* to insert *x* at the
Next, it runs the :meth:`!insert` method on *a* to insert *x* at the
appropriate position to maintain sort order.
To support inserting records in a table, the *key* function (if any) is

View file

@ -196,6 +196,13 @@ interpreted as prescribed by the ISO 8601 standard. Year 0 is 1 BC, year -1 is
output (defaulting to the system default encoding).
.. method:: formatmonthname(theyear, themonth, withyear=True)
Return a month name as an HTML table row. If *withyear* is true the year
will be included in the row, otherwise just the month name will be
used.
:class:`!HTMLCalendar` has the following attributes you can override to
customize the CSS classes used by the calendar:
@ -289,7 +296,7 @@ interpreted as prescribed by the ISO 8601 standard. Year 0 is 1 BC, year -1 is
.. note::
The constructor, :meth:`formatweekday` and :meth:`formatmonthname` methods
The constructor, :meth:`!formatweekday` and :meth:`!formatmonthname` methods
of these two classes temporarily change the ``LC_TIME`` locale to the given
*locale*. Because the current locale is a process-wide setting, they are
not thread-safe.
@ -358,7 +365,7 @@ For simple text calendars this module provides the following functions.
.. function:: month(theyear, themonth, w=0, l=0)
Returns a month's calendar in a multi-line string using the :meth:`formatmonth`
Returns a month's calendar in a multi-line string using the :meth:`~TextCalendar.formatmonth`
of the :class:`TextCalendar` class.
@ -370,7 +377,7 @@ For simple text calendars this module provides the following functions.
.. function:: calendar(year, w=2, l=1, c=6, m=3)
Returns a 3-column calendar for an entire year as a multi-line string using
the :meth:`formatyear` of the :class:`TextCalendar` class.
the :meth:`~TextCalendar.formatyear` of the :class:`TextCalendar` class.
.. function:: timegm(tuple)

View file

@ -26,6 +26,13 @@ interface.
key; it defaults to :kbd:`Tab`. If *completekey* is not :const:`None` and
:mod:`readline` is available, command completion is done automatically.
The default, ``'tab'``, is treated specially, so that it refers to the
:kbd:`Tab` key on every :data:`readline.backend`.
Specifically, if :data:`readline.backend` is ``editline``,
``Cmd`` will use ``'^I'`` instead of ``'tab'``.
Note that other values are not treated this way, and might only work
with a specific backend.
The optional arguments *stdin* and *stdout* specify the input and output file
objects that the Cmd instance or subclass instance will use for input and
output. If not specified, they will default to :data:`sys.stdin` and
@ -35,6 +42,9 @@ interface.
:attr:`use_rawinput` attribute to ``False``, otherwise *stdin* will be
ignored.
.. versionchanged:: 3.13
``completekey='tab'`` is replaced by ``'^I'`` for ``editline``.
.. _cmd-objects:
@ -66,29 +76,32 @@ A :class:`Cmd` instance has the following methods:
single: ! (exclamation); in a command interpreter
An interpreter instance will recognize a command name ``foo`` if and only if it
has a method :meth:`do_foo`. As a special case, a line beginning with the
has a method :meth:`!do_foo`. As a special case, a line beginning with the
character ``'?'`` is dispatched to the method :meth:`do_help`. As another
special case, a line beginning with the character ``'!'`` is dispatched to the
method :meth:`do_shell` (if such a method is defined).
method :meth:`!do_shell` (if such a method is defined).
This method will return when the :meth:`postcmd` method returns a true value.
The *stop* argument to :meth:`postcmd` is the return value from the command's
corresponding :meth:`do_\*` method.
corresponding :meth:`!do_\*` method.
If completion is enabled, completing commands will be done automatically, and
completing of commands args is done by calling :meth:`complete_foo` with
completing of commands args is done by calling :meth:`!complete_foo` with
arguments *text*, *line*, *begidx*, and *endidx*. *text* is the string prefix
we are attempting to match: all returned matches must begin with it. *line* is
the current input line with leading whitespace removed, *begidx* and *endidx*
are the beginning and ending indexes of the prefix text, which could be used to
provide different completion depending upon which position the argument is in.
All subclasses of :class:`Cmd` inherit a predefined :meth:`do_help`. This
.. method:: Cmd.do_help(arg)
All subclasses of :class:`Cmd` inherit a predefined :meth:`!do_help`. This
method, called with an argument ``'bar'``, invokes the corresponding method
:meth:`help_bar`, and if that is not present, prints the docstring of
:meth:`do_bar`, if available. With no argument, :meth:`do_help` lists all
:meth:`!help_bar`, and if that is not present, prints the docstring of
:meth:`!do_bar`, if available. With no argument, :meth:`!do_help` lists all
available help topics (that is, all commands with corresponding
:meth:`help_\*` methods or commands that have docstrings), and also lists any
:meth:`!help_\*` methods or commands that have docstrings), and also lists any
undocumented commands.
@ -98,7 +111,7 @@ A :class:`Cmd` instance has the following methods:
This may be overridden, but should not normally need to be; see the
:meth:`precmd` and :meth:`postcmd` methods for useful execution hooks. The
return value is a flag indicating whether interpretation of commands by the
interpreter should stop. If there is a :meth:`do_\*` method for the command
interpreter should stop. If there is a :meth:`!do_\*` method for the command
*str*, the return value of that method is returned, otherwise the return value
from the :meth:`default` method is returned.
@ -118,7 +131,7 @@ A :class:`Cmd` instance has the following methods:
.. method:: Cmd.completedefault(text, line, begidx, endidx)
Method called to complete an input line when no command-specific
:meth:`complete_\*` method is available. By default, it returns an empty list.
:meth:`!complete_\*` method is available. By default, it returns an empty list.
.. method:: Cmd.columnize(list, displaywidth=80)
@ -199,14 +212,14 @@ Instances of :class:`Cmd` subclasses have some public instance variables:
.. attribute:: Cmd.misc_header
The header to issue if the help output has a section for miscellaneous help
topics (that is, there are :meth:`help_\*` methods without corresponding
:meth:`do_\*` methods).
topics (that is, there are :meth:`!help_\*` methods without corresponding
:meth:`!do_\*` methods).
.. attribute:: Cmd.undoc_header
The header to issue if the help output has a section for undocumented commands
(that is, there are :meth:`do_\*` methods without corresponding :meth:`help_\*`
(that is, there are :meth:`!do_\*` methods without corresponding :meth:`!help_\*`
methods).
@ -219,8 +232,8 @@ Instances of :class:`Cmd` subclasses have some public instance variables:
.. attribute:: Cmd.use_rawinput
A flag, defaulting to true. If true, :meth:`cmdloop` uses :func:`input` to
display a prompt and read the next command; if false, :meth:`sys.stdout.write`
and :meth:`sys.stdin.readline` are used. (This means that by importing
display a prompt and read the next command; if false, :data:`sys.stdout.write() <sys.stdout>`
and :data:`sys.stdin.readline() <sys.stdin>` are used. (This means that by importing
:mod:`readline`, on systems that support it, the interpreter will automatically
support :program:`Emacs`\ -like line editing and command-history keystrokes.)
@ -239,14 +252,14 @@ This section presents a simple example of how to build a shell around a few of
the commands in the :mod:`turtle` module.
Basic turtle commands such as :meth:`~turtle.forward` are added to a
:class:`Cmd` subclass with method named :meth:`do_forward`. The argument is
:class:`Cmd` subclass with method named :meth:`!do_forward`. The argument is
converted to a number and dispatched to the turtle module. The docstring is
used in the help utility provided by the shell.
The example also includes a basic record and playback facility implemented with
the :meth:`~Cmd.precmd` method which is responsible for converting the input to
lowercase and writing the commands to a file. The :meth:`do_playback` method
reads the file and adds the recorded commands to the :attr:`cmdqueue` for
lowercase and writing the commands to a file. The :meth:`!do_playback` method
reads the file and adds the recorded commands to the :attr:`~Cmd.cmdqueue` for
immediate playback::
import cmd, sys

View file

@ -22,7 +22,7 @@
This module provides :term:`abstract base classes <abstract base class>` that
can be used to test whether a class provides a particular interface; for
example, whether it is :term:`hashable` or whether it is a mapping.
example, whether it is :term:`hashable` or whether it is a :term:`mapping`.
An :func:`issubclass` or :func:`isinstance` test for an interface works in one
of three ways.
@ -73,7 +73,7 @@ of the API:
>>> isinstance(D(), Sequence)
True
In this example, class :class:`D` does not need to define
In this example, class :class:`!D` does not need to define
``__contains__``, ``__iter__``, and ``__reversed__`` because the
:ref:`in-operator <comparisons>`, the :term:`iteration <iterable>`
logic, and the :func:`reversed` function automatically fall back to
@ -87,7 +87,7 @@ the required methods (unless those methods have been set to
class E:
def __iter__(self): ...
def __next__(next): ...
def __next__(self): ...
.. doctest::
@ -183,14 +183,14 @@ ABC Inherits from Abstract Methods Mi
.. rubric:: Footnotes
.. [1] These ABCs override :meth:`object.__subclasshook__` to support
.. [1] These ABCs override :meth:`~abc.ABCMeta.__subclasshook__` to support
testing an interface by verifying the required methods are present
and have not been set to :const:`None`. This only works for simple
interfaces. More complex interfaces require registration or direct
subclassing.
.. [2] Checking ``isinstance(obj, Iterable)`` detects classes that are
registered as :class:`Iterable` or that have an :meth:`__iter__`
registered as :class:`Iterable` or that have an :meth:`~container.__iter__`
method, but it does not detect classes that iterate with the
:meth:`~object.__getitem__` method. The only reliable way to determine
whether an object is :term:`iterable` is to call ``iter(obj)``.
@ -202,26 +202,27 @@ Collections Abstract Base Classes -- Detailed Descriptions
.. class:: Container
ABC for classes that provide the :meth:`__contains__` method.
ABC for classes that provide the :meth:`~object.__contains__` method.
.. class:: Hashable
ABC for classes that provide the :meth:`__hash__` method.
ABC for classes that provide the :meth:`~object.__hash__` method.
.. class:: Sized
ABC for classes that provide the :meth:`__len__` method.
ABC for classes that provide the :meth:`~object.__len__` method.
.. class:: Callable
ABC for classes that provide the :meth:`__call__` method.
ABC for classes that provide the :meth:`~object.__call__` method.
.. class:: Iterable
ABC for classes that provide the :meth:`__iter__` method.
ABC for classes that provide the :meth:`~container.__iter__` method.
Checking ``isinstance(obj, Iterable)`` detects classes that are registered
as :class:`Iterable` or that have an :meth:`__iter__` method, but it does
as :class:`Iterable` or that have an :meth:`~container.__iter__` method,
but it does
not detect classes that iterate with the :meth:`~object.__getitem__` method.
The only reliable way to determine whether an object is :term:`iterable`
is to call ``iter(obj)``.
@ -240,17 +241,17 @@ Collections Abstract Base Classes -- Detailed Descriptions
.. class:: Reversible
ABC for iterable classes that also provide the :meth:`__reversed__`
ABC for iterable classes that also provide the :meth:`~object.__reversed__`
method.
.. versionadded:: 3.6
.. class:: Generator
ABC for generator classes that implement the protocol defined in
:pep:`342` that extends iterators with the :meth:`~generator.send`,
ABC for :term:`generator` classes that implement the protocol defined in
:pep:`342` that extends :term:`iterators <iterator>` with the
:meth:`~generator.send`,
:meth:`~generator.throw` and :meth:`~generator.close` methods.
See also the definition of :term:`generator`.
.. versionadded:: 3.5
@ -261,7 +262,7 @@ Collections Abstract Base Classes -- Detailed Descriptions
ABCs for read-only and mutable :term:`sequences <sequence>`.
Implementation note: Some of the mixin methods, such as
:meth:`__iter__`, :meth:`__reversed__` and :meth:`index`, make
:meth:`~container.__iter__`, :meth:`~object.__reversed__` and :meth:`index`, make
repeated calls to the underlying :meth:`~object.__getitem__` method.
Consequently, if :meth:`~object.__getitem__` is implemented with constant
access speed, the mixin methods will have linear performance;
@ -282,7 +283,7 @@ Collections Abstract Base Classes -- Detailed Descriptions
.. class:: Set
MutableSet
ABCs for read-only and mutable sets.
ABCs for read-only and mutable :ref:`sets <types-set>`.
.. class:: Mapping
MutableMapping
@ -299,16 +300,16 @@ Collections Abstract Base Classes -- Detailed Descriptions
.. class:: Awaitable
ABC for :term:`awaitable` objects, which can be used in :keyword:`await`
expressions. Custom implementations must provide the :meth:`__await__`
method.
expressions. Custom implementations must provide the
:meth:`~object.__await__` method.
:term:`Coroutine <coroutine>` objects and instances of the
:class:`~collections.abc.Coroutine` ABC are all instances of this ABC.
.. note::
In CPython, generator-based coroutines (generators decorated with
:func:`types.coroutine`) are
*awaitables*, even though they do not have an :meth:`__await__` method.
In CPython, generator-based coroutines (:term:`generators <generator>`
decorated with :func:`@types.coroutine <types.coroutine>`) are
*awaitables*, even though they do not have an :meth:`~object.__await__` method.
Using ``isinstance(gencoro, Awaitable)`` for them will return ``False``.
Use :func:`inspect.isawaitable` to detect them.
@ -316,17 +317,17 @@ Collections Abstract Base Classes -- Detailed Descriptions
.. class:: Coroutine
ABC for coroutine compatible classes. These implement the
ABC for :term:`coroutine` compatible classes. These implement the
following methods, defined in :ref:`coroutine-objects`:
:meth:`~coroutine.send`, :meth:`~coroutine.throw`, and
:meth:`~coroutine.close`. Custom implementations must also implement
:meth:`__await__`. All :class:`Coroutine` instances are also instances of
:class:`Awaitable`. See also the definition of :term:`coroutine`.
:meth:`~object.__await__`. All :class:`Coroutine` instances are also
instances of :class:`Awaitable`.
.. note::
In CPython, generator-based coroutines (generators decorated with
:func:`types.coroutine`) are
*awaitables*, even though they do not have an :meth:`__await__` method.
In CPython, generator-based coroutines (:term:`generators <generator>`
decorated with :func:`@types.coroutine <types.coroutine>`) are
*awaitables*, even though they do not have an :meth:`~object.__await__` method.
Using ``isinstance(gencoro, Coroutine)`` for them will return ``False``.
Use :func:`inspect.isawaitable` to detect them.
@ -334,7 +335,7 @@ Collections Abstract Base Classes -- Detailed Descriptions
.. class:: AsyncIterable
ABC for classes that provide ``__aiter__`` method. See also the
ABC for classes that provide an ``__aiter__`` method. See also the
definition of :term:`asynchronous iterable`.
.. versionadded:: 3.5
@ -348,7 +349,7 @@ Collections Abstract Base Classes -- Detailed Descriptions
.. class:: AsyncGenerator
ABC for asynchronous generator classes that implement the protocol
ABC for :term:`asynchronous generator` classes that implement the protocol
defined in :pep:`525` and :pep:`492`.
.. versionadded:: 3.6
@ -373,9 +374,9 @@ particular functionality, for example::
Several of the ABCs are also useful as mixins that make it easier to develop
classes supporting container APIs. For example, to write a class supporting
the full :class:`Set` API, it is only necessary to supply the three underlying
abstract methods: :meth:`__contains__`, :meth:`__iter__`, and :meth:`__len__`.
The ABC supplies the remaining methods such as :meth:`__and__` and
:meth:`isdisjoint`::
abstract methods: :meth:`~object.__contains__`, :meth:`~container.__iter__`, and
:meth:`~object.__len__`. The ABC supplies the remaining methods such as
:meth:`!__and__` and :meth:`~frozenset.isdisjoint`::
class ListBasedSet(collections.abc.Set):
''' Alternate set implementation favoring space over speed
@ -403,23 +404,24 @@ Notes on using :class:`Set` and :class:`MutableSet` as a mixin:
(1)
Since some set operations create new sets, the default mixin methods need
a way to create new instances from an iterable. The class constructor is
a way to create new instances from an :term:`iterable`. The class constructor is
assumed to have a signature in the form ``ClassName(iterable)``.
That assumption is factored-out to an internal classmethod called
:meth:`_from_iterable` which calls ``cls(iterable)`` to produce a new set.
That assumption is factored-out to an internal :class:`classmethod` called
:meth:`!_from_iterable` which calls ``cls(iterable)`` to produce a new set.
If the :class:`Set` mixin is being used in a class with a different
constructor signature, you will need to override :meth:`_from_iterable`
constructor signature, you will need to override :meth:`!_from_iterable`
with a classmethod or regular method that can construct new instances from
an iterable argument.
(2)
To override the comparisons (presumably for speed, as the
semantics are fixed), redefine :meth:`__le__` and :meth:`__ge__`,
semantics are fixed), redefine :meth:`~object.__le__` and
:meth:`~object.__ge__`,
then the other operations will automatically follow suit.
(3)
The :class:`Set` mixin provides a :meth:`_hash` method to compute a hash value
for the set; however, :meth:`__hash__` is not defined because not all sets
The :class:`Set` mixin provides a :meth:`!_hash` method to compute a hash value
for the set; however, :meth:`~object.__hash__` is not defined because not all sets
are :term:`hashable` or immutable. To add set hashability using mixins,
inherit from both :meth:`Set` and :meth:`Hashable`, then define
``__hash__ = Set._hash``.

View file

@ -981,6 +981,10 @@ field names, the method and attribute names start with an underscore.
Named tuples are also supported by generic function :func:`copy.replace`.
.. versionchanged:: 3.13
Raise :exc:`TypeError` instead of :exc:`ValueError` for invalid
keyword arguments.
.. attribute:: somenamedtuple._fields
Tuple of strings listing the field names. Useful for introspection

View file

@ -208,7 +208,7 @@ converters and customize the provided ones. [1]_
Fallback Values
---------------
As with a dictionary, you can use a section's :meth:`get` method to
As with a dictionary, you can use a section's :meth:`~ConfigParser.get` method to
provide fallback values:
.. doctest::
@ -232,7 +232,7 @@ even if we specify a fallback:
>>> topsecret.get('CompressionLevel', '3')
'9'
One more thing to be aware of is that the parser-level :meth:`get` method
One more thing to be aware of is that the parser-level :meth:`~ConfigParser.get` method
provides a custom, more complex interface, maintained for backwards
compatibility. When using this method, a fallback value can be provided via
the ``fallback`` keyword-only argument:
@ -271,7 +271,7 @@ out. Values can also span multiple lines, as long as they are indented deeper
than the first line of the value. Depending on the parser's mode, blank lines
may be treated as parts of multiline values or ignored.
By default, a valid section name can be any string that does not contain '\\n' or ']'.
By default, a valid section name can be any string that does not contain '\\n'.
To change this, see :attr:`ConfigParser.SECTCRE`.
Configuration files may include comments, prefixed by specific
@ -481,7 +481,7 @@ historical background and it's very likely that you will want to customize some
of the features.
The most common way to change the way a specific config parser works is to use
the :meth:`__init__` options:
the :meth:`!__init__` options:
* *defaults*, default value: ``None``
@ -491,7 +491,7 @@ the :meth:`__init__` options:
the documented default.
Hint: if you want to specify default values for a specific section, use
:meth:`read_dict` before you read the actual file.
:meth:`~ConfigParser.read_dict` before you read the actual file.
* *dict_type*, default value: :class:`dict`
@ -635,8 +635,8 @@ the :meth:`__init__` options:
* *strict*, default value: ``True``
When set to ``True``, the parser will not allow for any section or option
duplicates while reading from a single source (using :meth:`read_file`,
:meth:`read_string` or :meth:`read_dict`). It is recommended to use strict
duplicates while reading from a single source (using :meth:`~ConfigParser.read_file`,
:meth:`~ConfigParser.read_string` or :meth:`~ConfigParser.read_dict`). It is recommended to use strict
parsers in new applications.
.. versionchanged:: 3.2
@ -697,7 +697,7 @@ the :meth:`__init__` options:
desirable, users may define them in a subclass or pass a dictionary where each
key is a name of the converter and each value is a callable implementing said
conversion. For instance, passing ``{'decimal': decimal.Decimal}`` would add
:meth:`getdecimal` on both the parser object and all section proxies. In
:meth:`!getdecimal` on both the parser object and all section proxies. In
other words, it will be possible to write both
``parser_instance.getdecimal('section', 'key', fallback=0)`` and
``parser_instance['section'].getdecimal('key', 0)``.
@ -955,7 +955,7 @@ ConfigParser Objects
When *converters* is given, it should be a dictionary where each key
represents the name of a type converter and each value is a callable
implementing the conversion from string to the desired datatype. Every
converter gets its own corresponding :meth:`get*()` method on the parser
converter gets its own corresponding :meth:`!get*()` method on the parser
object and section proxies.
.. versionchanged:: 3.1
@ -1062,11 +1062,11 @@ ConfigParser Objects
yielding Unicode strings (for example files opened in text mode).
Optional argument *source* specifies the name of the file being read. If
not given and *f* has a :attr:`name` attribute, that is used for
not given and *f* has a :attr:`!name` attribute, that is used for
*source*; the default is ``'<???>'``.
.. versionadded:: 3.2
Replaces :meth:`readfp`.
Replaces :meth:`!readfp`.
.. method:: read_string(string, source='<string>')
@ -1214,7 +1214,7 @@ ConfigParser Objects
.. data:: MAX_INTERPOLATION_DEPTH
The maximum depth for recursive interpolation for :meth:`get` when the *raw*
The maximum depth for recursive interpolation for :meth:`~configparser.ConfigParser.get` when the *raw*
parameter is false. This is relevant only when the default *interpolation*
is used.
@ -1287,13 +1287,13 @@ Exceptions
.. exception:: DuplicateSectionError
Exception raised if :meth:`add_section` is called with the name of a section
Exception raised if :meth:`~ConfigParser.add_section` is called with the name of a section
that is already present or in strict parsers when a section if found more
than once in a single input file, string or dictionary.
.. versionadded:: 3.2
Optional ``source`` and ``lineno`` attributes and arguments to
:meth:`__init__` were added.
:meth:`!__init__` were added.
.. exception:: DuplicateOptionError
@ -1345,9 +1345,9 @@ Exceptions
Exception raised when errors occur attempting to parse a file.
.. versionchanged:: 3.12
The ``filename`` attribute and :meth:`__init__` constructor argument were
removed. They have been available using the name ``source`` since 3.2.
.. versionchanged:: 3.12
The ``filename`` attribute and :meth:`!__init__` constructor argument were
removed. They have been available using the name ``source`` since 3.2.
.. rubric:: Footnotes

View file

@ -106,8 +106,8 @@ Functions and classes provided:
This function is a :term:`decorator` that can be used to define a factory
function for :keyword:`async with` statement asynchronous context managers,
without needing to create a class or separate :meth:`__aenter__` and
:meth:`__aexit__` methods. It must be applied to an :term:`asynchronous
without needing to create a class or separate :meth:`~object.__aenter__` and
:meth:`~object.__aexit__` methods. It must be applied to an :term:`asynchronous
generator` function.
A simple example::
@ -616,12 +616,12 @@ Functions and classes provided:
asynchronous context managers, as well as having coroutines for
cleanup logic.
The :meth:`close` method is not implemented, :meth:`aclose` must be used
The :meth:`~ExitStack.close` method is not implemented; :meth:`aclose` must be used
instead.
.. coroutinemethod:: enter_async_context(cm)
Similar to :meth:`enter_context` but expects an asynchronous context
Similar to :meth:`ExitStack.enter_context` but expects an asynchronous context
manager.
.. versionchanged:: 3.11
@ -630,16 +630,16 @@ Functions and classes provided:
.. method:: push_async_exit(exit)
Similar to :meth:`push` but expects either an asynchronous context manager
Similar to :meth:`ExitStack.push` but expects either an asynchronous context manager
or a coroutine function.
.. method:: push_async_callback(callback, /, *args, **kwds)
Similar to :meth:`callback` but expects a coroutine function.
Similar to :meth:`ExitStack.callback` but expects a coroutine function.
.. coroutinemethod:: aclose()
Similar to :meth:`close` but properly handles awaitables.
Similar to :meth:`ExitStack.close` but properly handles awaitables.
Continuing the example for :func:`asynccontextmanager`::

View file

@ -55,10 +55,11 @@ The :mod:`csv` module defines the following functions:
.. function:: reader(csvfile, dialect='excel', **fmtparams)
Return a reader object which will iterate over lines in the given *csvfile*.
*csvfile* can be any object which supports the :term:`iterator` protocol and returns a
string each time its :meth:`!__next__` method is called --- :term:`file objects
<file object>` and list objects are both suitable. If *csvfile* is a file object,
Return a :ref:`reader object <reader-objects>` that will process
lines from the given *csvfile*. A csvfile must be an iterable of
strings, each in the reader's defined csv format.
A csvfile is most commonly a file-like object or list.
If *csvfile* is a file object,
it should be opened with ``newline=''``. [1]_ An optional
*dialect* parameter can be given which is used to define a set of parameters
specific to a particular CSV dialect. It may be an instance of a subclass of
@ -309,6 +310,8 @@ An example for :class:`Sniffer` use::
# ... process CSV file contents here ...
.. _csv-constants:
The :mod:`csv` module defines the following constants:
.. data:: QUOTE_ALL
@ -432,8 +435,8 @@ Dialects support the following attributes:
.. attribute:: Dialect.quoting
Controls when quotes should be generated by the writer and recognised by the
reader. It can take on any of the :const:`QUOTE_\*` constants (see section
:ref:`csv-contents`) and defaults to :const:`QUOTE_MINIMAL`.
reader. It can take on any of the :ref:`QUOTE_\* constants <csv-constants>`
and defaults to :const:`QUOTE_MINIMAL`.
.. attribute:: Dialect.skipinitialspace
@ -447,6 +450,8 @@ Dialects support the following attributes:
When ``True``, raise exception :exc:`Error` on bad CSV input.
The default is ``False``.
.. _reader-objects:
Reader Objects
--------------

View file

@ -1799,6 +1799,8 @@ Other constructor:
Examples::
.. doctest::
>>> from datetime import time
>>> time.fromisoformat('04:23:01')
datetime.time(4, 23, 1)
@ -1808,7 +1810,7 @@ Other constructor:
datetime.time(4, 23, 1)
>>> time.fromisoformat('04:23:01.000384')
datetime.time(4, 23, 1, 384)
>>> time.fromisoformat('04:23:01,000')
>>> time.fromisoformat('04:23:01,000384')
datetime.time(4, 23, 1, 384)
>>> time.fromisoformat('04:23:01+04:00')
datetime.time(4, 23, 1, tzinfo=datetime.timezone(datetime.timedelta(seconds=14400)))
@ -1985,7 +1987,8 @@ Examples of working with a :class:`.time` object::
American EST and EDT.
Special requirement for pickling: A :class:`tzinfo` subclass must have an
:meth:`__init__` method that can be called with no arguments, otherwise it can be
:meth:`~object.__init__` method that can be called with no arguments,
otherwise it can be
pickled but possibly not unpickled again. This is a technical requirement that
may be relaxed in the future.

View file

@ -272,6 +272,13 @@ This module can be used with the "classic" ndbm interface or the GNU GDBM
compatibility interface. On Unix, the :program:`configure` script will attempt
to locate the appropriate header file to simplify building this module.
.. warning::
The ndbm library shipped as part of macOS has an undocumented limitation on the
size of values, which can result in corrupted database files
when storing values larger than this limit. Reading such corrupted files can
result in a hard crash (segmentation fault).
.. exception:: error
Raised on :mod:`dbm.ndbm`-specific errors, such as I/O errors. :exc:`KeyError` is raised

View file

@ -328,26 +328,32 @@ operation is being performed, so the intermediate analysis object isn't useful:
source line information (if any) is taken directly from the disassembled code
object.
The *show_caches* and *adaptive* parameters work as they do in :func:`dis`.
The *adaptive* parameter works as it does in :func:`dis`.
.. versionadded:: 3.4
.. versionchanged:: 3.11
Added the *show_caches* and *adaptive* parameters.
.. versionchanged:: 3.13
The *show_caches* parameter is deprecated and has no effect. The *cache_info*
field of each instruction is populated regardless of its value.
.. function:: findlinestarts(code)
This generator function uses the ``co_lines`` method
of the code object *code* to find the offsets which are starts of
This generator function uses the :meth:`~codeobject.co_lines` method
of the :ref:`code object <code-objects>` *code* to find the offsets which
are starts of
lines in the source code. They are generated as ``(offset, lineno)`` pairs.
.. versionchanged:: 3.6
Line numbers can be decreasing. Before, they were always increasing.
.. versionchanged:: 3.10
The :pep:`626` ``co_lines`` method is used instead of the ``co_firstlineno``
and ``co_lnotab`` attributes of the code object.
The :pep:`626` :meth:`~codeobject.co_lines` method is used instead of the
:attr:`~codeobject.co_firstlineno` and :attr:`~codeobject.co_lnotab`
attributes of the :ref:`code object <code-objects>`.
.. versionchanged:: 3.13
Line numbers can be ``None`` for bytecode that does not map to source lines.
@ -481,6 +487,14 @@ details of bytecode instructions as :class:`Instruction` instances:
:class:`dis.Positions` object holding the
start and end locations that are covered by this instruction.
.. data::cache_info
Information about the cache entries of this instruction, as
triplets of the form ``(name, size, data)``, where the ``name``
and ``size`` describe the cache format and data is the contents
of the cache. ``cache_info`` is ``None`` if the instruction does not have
caches.
.. versionadded:: 3.4
.. versionchanged:: 3.11
@ -492,8 +506,8 @@ details of bytecode instructions as :class:`Instruction` instances:
Changed field ``starts_line``.
Added fields ``start_offset``, ``cache_offset``, ``end_offset``,
``baseopname``, ``baseopcode``, ``jump_target``, ``oparg``, and
``line_number``.
``baseopname``, ``baseopcode``, ``jump_target``, ``oparg``,
``line_number`` and ``cache_info``.
.. class:: Positions
@ -865,8 +879,8 @@ iterations of the loop.
.. opcode:: RERAISE
Re-raises the exception currently on top of the stack. If oparg is non-zero,
pops an additional value from the stack which is used to set ``f_lasti``
of the current frame.
pops an additional value from the stack which is used to set
:attr:`~frame.f_lasti` of the current frame.
.. versionadded:: 3.9
@ -983,13 +997,13 @@ iterations of the loop.
.. opcode:: STORE_NAME (namei)
Implements ``name = STACK.pop()``. *namei* is the index of *name* in the attribute
:attr:`!co_names` of the :ref:`code object <code-objects>`.
:attr:`~codeobject.co_names` of the :ref:`code object <code-objects>`.
The compiler tries to use :opcode:`STORE_FAST` or :opcode:`STORE_GLOBAL` if possible.
.. opcode:: DELETE_NAME (namei)
Implements ``del name``, where *namei* is the index into :attr:`!co_names`
Implements ``del name``, where *namei* is the index into :attr:`~codeobject.co_names`
attribute of the :ref:`code object <code-objects>`.
@ -1029,7 +1043,7 @@ iterations of the loop.
value = STACK.pop()
obj.name = value
where *namei* is the index of name in :attr:`!co_names` of the
where *namei* is the index of name in :attr:`~codeobject.co_names` of the
:ref:`code object <code-objects>`.
.. opcode:: DELETE_ATTR (namei)
@ -1039,7 +1053,7 @@ iterations of the loop.
obj = STACK.pop()
del obj.name
where *namei* is the index of name into :attr:`!co_names` of the
where *namei* is the index of name into :attr:`~codeobject.co_names` of the
:ref:`code object <code-objects>`.
@ -1201,9 +1215,10 @@ iterations of the loop.
``super(cls, self).method()``, ``super(cls, self).attr``).
It pops three values from the stack (from top of stack down):
- ``self``: the first argument to the current method
- ``cls``: the class within which the current method was defined
- the global ``super``
* ``self``: the first argument to the current method
* ``cls``: the class within which the current method was defined
* the global ``super``
With respect to its argument, it works similarly to :opcode:`LOAD_ATTR`,
except that ``namei`` is shifted left by 2 bits instead of 1.
@ -1402,7 +1417,7 @@ iterations of the loop.
Pushes a reference to the object the cell contains on the stack.
.. versionchanged:: 3.11
``i`` is no longer offset by the length of ``co_varnames``.
``i`` is no longer offset by the length of :attr:`~codeobject.co_varnames`.
.. opcode:: LOAD_FROM_DICT_OR_DEREF (i)
@ -1424,7 +1439,7 @@ iterations of the loop.
storage.
.. versionchanged:: 3.11
``i`` is no longer offset by the length of ``co_varnames``.
``i`` is no longer offset by the length of :attr:`~codeobject.co_varnames`.
.. opcode:: DELETE_DEREF (i)
@ -1435,7 +1450,7 @@ iterations of the loop.
.. versionadded:: 3.2
.. versionchanged:: 3.11
``i`` is no longer offset by the length of ``co_varnames``.
``i`` is no longer offset by the length of :attr:`~codeobject.co_varnames`.
.. opcode:: COPY_FREE_VARS (n)

View file

@ -143,13 +143,13 @@ Simple Usage: Checking Examples in Docstrings
---------------------------------------------
The simplest way to start using doctest (but not necessarily the way you'll
continue to do it) is to end each module :mod:`M` with::
continue to do it) is to end each module :mod:`!M` with::
if __name__ == "__main__":
import doctest
doctest.testmod()
:mod:`doctest` then examines docstrings in module :mod:`M`.
:mod:`!doctest` then examines docstrings in module :mod:`!M`.
Running the module as a script causes the examples in the docstrings to get
executed and verified::
@ -280,7 +280,7 @@ searched. Objects imported into the module are not searched.
In addition, there are cases when you want tests to be part of a module but not part
of the help text, which requires that the tests not be included in the docstring.
Doctest looks for a module-level variable called ``__test__`` and uses it to locate other
tests. If ``M.__test__`` exists and is truthy, it must be a dict, and each
tests. If ``M.__test__`` exists, it must be a dict, and each
entry maps a (string) name to a function object, class object, or string.
Function and class object docstrings found from ``M.__test__`` are searched, and
strings are treated as if they were docstrings. In output, a key ``K`` in
@ -403,10 +403,10 @@ What's the Execution Context?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
By default, each time :mod:`doctest` finds a docstring to test, it uses a
*shallow copy* of :mod:`M`'s globals, so that running tests doesn't change the
module's real globals, and so that one test in :mod:`M` can't leave behind
*shallow copy* of :mod:`!M`'s globals, so that running tests doesn't change the
module's real globals, and so that one test in :mod:`!M` can't leave behind
crumbs that accidentally allow another test to work. This means examples can
freely use any names defined at top-level in :mod:`M`, and names defined earlier
freely use any names defined at top-level in :mod:`!M`, and names defined earlier
in the docstring being run. Examples cannot see names defined in other
docstrings.
@ -944,8 +944,8 @@ and :ref:`doctest-simple-testfile`.
(or module :mod:`__main__` if *m* is not supplied or is ``None``), starting with
``m.__doc__``.
Also test examples reachable from dict ``m.__test__``, if it exists and is not
``None``. ``m.__test__`` maps names (strings) to functions, classes and
Also test examples reachable from dict ``m.__test__``, if it exists.
``m.__test__`` maps names (strings) to functions, classes and
strings; function and class docstrings are searched for examples; strings are
searched directly, as if they were docstrings.
@ -958,7 +958,8 @@ and :ref:`doctest-simple-testfile`.
Optional argument *exclude_empty* defaults to false. If true, objects for which
no doctests are found are excluded from consideration. The default is a backward
compatibility hack, so that code still using :meth:`doctest.master.summarize` in
compatibility hack, so that code still using
:meth:`doctest.master.summarize <DocTestRunner.summarize>` in
conjunction with :func:`testmod` continues to get output for objects with no
tests. The *exclude_empty* argument to the newer :class:`DocTestFinder`
constructor defaults to true.
@ -997,7 +998,7 @@ As your collection of doctest'ed modules grows, you'll want a way to run all
their doctests systematically. :mod:`doctest` provides two functions that can
be used to create :mod:`unittest` test suites from modules and text files
containing doctests. To integrate with :mod:`unittest` test discovery, include
a :func:`load_tests` function in your test module::
a :ref:`load_tests <load_tests-protocol>` function in your test module::
import unittest
import doctest
@ -1111,19 +1112,24 @@ from text files and modules with doctests:
:func:`DocTestSuite` returns an empty :class:`unittest.TestSuite` if *module*
contains no docstrings instead of raising :exc:`ValueError`.
.. exception:: failureException
When doctests which have been converted to unit tests by :func:`DocFileSuite`
or :func:`DocTestSuite` fail, this exception is raised showing the name of
the file containing the test and a (sometimes approximate) line number.
Under the covers, :func:`DocTestSuite` creates a :class:`unittest.TestSuite` out
of :class:`doctest.DocTestCase` instances, and :class:`DocTestCase` is a
subclass of :class:`unittest.TestCase`. :class:`DocTestCase` isn't documented
of :class:`!doctest.DocTestCase` instances, and :class:`!DocTestCase` is a
subclass of :class:`unittest.TestCase`. :class:`!DocTestCase` isn't documented
here (it's an internal detail), but studying its code can answer questions about
the exact details of :mod:`unittest` integration.
Similarly, :func:`DocFileSuite` creates a :class:`unittest.TestSuite` out of
:class:`doctest.DocFileCase` instances, and :class:`DocFileCase` is a subclass
of :class:`DocTestCase`.
:class:`!doctest.DocFileCase` instances, and :class:`!DocFileCase` is a subclass
of :class:`!DocTestCase`.
So both ways of creating a :class:`unittest.TestSuite` run instances of
:class:`DocTestCase`. This is important for a subtle reason: when you run
:class:`!DocTestCase`. This is important for a subtle reason: when you run
:mod:`doctest` functions yourself, you can control the :mod:`doctest` options in
use directly, by passing option flags to :mod:`doctest` functions. However, if
you're writing a :mod:`unittest` framework, :mod:`unittest` ultimately controls
@ -1144,14 +1150,14 @@ reporting flags specific to :mod:`unittest` support, via this function:
section :ref:`doctest-options`. Only "reporting flags" can be used.
This is a module-global setting, and affects all future doctests run by module
:mod:`unittest`: the :meth:`runTest` method of :class:`DocTestCase` looks at
the option flags specified for the test case when the :class:`DocTestCase`
:mod:`unittest`: the :meth:`!runTest` method of :class:`!DocTestCase` looks at
the option flags specified for the test case when the :class:`!DocTestCase`
instance was constructed. If no reporting flags were specified (which is the
typical and expected case), :mod:`doctest`'s :mod:`unittest` reporting flags are
typical and expected case), :mod:`!doctest`'s :mod:`unittest` reporting flags are
:ref:`bitwise ORed <bitwise>` into the option flags, and the option flags
so augmented are passed to the :class:`DocTestRunner` instance created to
run the doctest. If any reporting flags were specified when the
:class:`DocTestCase` instance was constructed, :mod:`doctest`'s
:class:`!DocTestCase` instance was constructed, :mod:`!doctest`'s
:mod:`unittest` reporting flags are ignored.
The value of the :mod:`unittest` reporting flags in effect before the function
@ -1321,7 +1327,8 @@ Example Objects
A dictionary mapping from option flags to ``True`` or ``False``, which is used
to override default options for this example. Any option flags not contained
in this dictionary are left at their default value (as specified by the
:class:`DocTestRunner`'s :attr:`optionflags`). By default, no options are set.
:class:`DocTestRunner`'s :ref:`optionflags <doctest-options>`).
By default, no options are set.
.. _doctest-doctestfinder:
@ -1495,7 +1502,7 @@ DocTestRunner objects
:attr:`failures` and :attr:`skips` attributes. The :meth:`run` and
:meth:`summarize` methods return a :class:`TestResults` instance.
:class:`DocTestParser` defines the following methods:
:class:`DocTestRunner` defines the following methods:
.. method:: report_start(out, test, example)
@ -1560,7 +1567,7 @@ DocTestRunner objects
The output of each example is checked using the :class:`DocTestRunner`'s
output checker, and the results are formatted by the
:meth:`DocTestRunner.report_\*` methods.
:meth:`!DocTestRunner.report_\*` methods.
.. method:: summarize(verbose=None)
@ -1735,12 +1742,12 @@ code under the debugger:
module) of the object with the doctests of interest. The result is a string,
containing the object's docstring converted to a Python script, as described for
:func:`script_from_examples` above. For example, if module :file:`a.py`
contains a top-level function :func:`f`, then ::
contains a top-level function :func:`!f`, then ::
import a, doctest
print(doctest.testsource(a, "a.f"))
prints a script version of function :func:`f`'s docstring, with doctests
prints a script version of function :func:`!f`'s docstring, with doctests
converted to code, and the rest placed in comments.

View file

@ -58,6 +58,15 @@ The following exception classes are defined in the :mod:`email.errors` module:
:class:`~email.mime.nonmultipart.MIMENonMultipart` (e.g.
:class:`~email.mime.image.MIMEImage`).
.. exception:: MessageDefect()
This is the base class for all defects found when parsing email messages.
It is derived from :exc:`ValueError`.
.. exception:: HeaderDefect()
This is the base class for all defects found when parsing email headers.
It is derived from :exc:`MessageDefect`.
Here is the list of the defects that the :class:`~email.parser.FeedParser`
can find while parsing messages. Note that the defects are added to the message

View file

@ -58,13 +58,18 @@ of the new API.
begins with angle brackets, they are stripped off.
.. function:: parseaddr(address)
.. function:: parseaddr(address, *, strict=True)
Parse address -- which should be the value of some address-containing field such
as :mailheader:`To` or :mailheader:`Cc` -- into its constituent *realname* and
*email address* parts. Returns a tuple of that information, unless the parse
fails, in which case a 2-tuple of ``('', '')`` is returned.
If *strict* is true, use a strict parser which rejects malformed inputs.
.. versionchanged:: 3.13
Add *strict* optional parameter and reject malformed inputs by default.
.. function:: formataddr(pair, charset='utf-8')
@ -82,12 +87,15 @@ of the new API.
Added the *charset* option.
.. function:: getaddresses(fieldvalues)
.. function:: getaddresses(fieldvalues, *, strict=True)
This method returns a list of 2-tuples of the form returned by ``parseaddr()``.
*fieldvalues* is a sequence of header field values as might be returned by
:meth:`Message.get_all <email.message.Message.get_all>`. Here's a simple
example that gets all the recipients of a message::
:meth:`Message.get_all <email.message.Message.get_all>`.
If *strict* is true, use a strict parser which rejects malformed inputs.
Here's a simple example that gets all the recipients of a message::
from email.utils import getaddresses
@ -97,6 +105,9 @@ of the new API.
resent_ccs = msg.get_all('resent-cc', [])
all_recipients = getaddresses(tos + ccs + resent_tos + resent_ccs)
.. versionchanged:: 3.13
Add *strict* optional parameter and reject malformed inputs by default.
.. function:: parsedate(date)

View file

@ -235,6 +235,10 @@ Data Types
>>> len(Color)
3
.. attribute:: EnumType.__members__
Returns a mapping of every enum name to its member, including aliases
.. method:: EnumType.__reversed__(cls)
Returns each member in *cls* in reverse definition order::
@ -242,9 +246,19 @@ Data Types
>>> list(reversed(Color))
[<Color.BLUE: 3>, <Color.GREEN: 2>, <Color.RED: 1>]
.. method:: EnumType._add_alias_
Adds a new name as an alias to an existing member. Raises a
:exc:`NameError` if the name is already assigned to a different member.
.. method:: EnumType._add_value_alias_
Adds a new value as an alias to an existing member. Raises a
:exc:`ValueError` if the value is already linked with a different member.
.. versionadded:: 3.11
Before 3.11 ``enum`` used ``EnumMeta`` type, which is kept as an alias.
Before 3.11 ``EnumType`` was called ``EnumMeta``, which is still available as an alias.
.. class:: Enum
@ -323,7 +337,7 @@ Data Types
>>> PowersOfThree.SECOND.value
9
.. method:: Enum.__init_subclass__(cls, **kwds)
.. method:: Enum.__init_subclass__(cls, \**kwds)
A *classmethod* that is used to further configure subsequent subclasses.
By default, does nothing.
@ -549,7 +563,7 @@ Data Types
.. method:: __invert__(self):
Returns all the flags in *type(self)* that are not in self::
Returns all the flags in *type(self)* that are not in *self*::
>>> ~white
<Color: 0>
@ -769,37 +783,41 @@ Supported ``__dunder__`` names
:attr:`~EnumType.__members__` is a read-only ordered mapping of ``member_name``:``member``
items. It is only available on the class.
:meth:`~object.__new__`, if specified, must create and return the enum members; it is
also a very good idea to set the member's :attr:`!_value_` appropriately. Once
all the members are created it is no longer used.
:meth:`~object.__new__`, if specified, must create and return the enum members;
it is also a very good idea to set the member's :attr:`!_value_` appropriately.
Once all the members are created it is no longer used.
Supported ``_sunder_`` names
""""""""""""""""""""""""""""
- ``_name_`` -- name of the member
- ``_value_`` -- value of the member; can be set / modified in ``__new__``
- ``_missing_`` -- a lookup function used when a value is not found; may be
overridden
- ``_ignore_`` -- a list of names, either as a :class:`list` or a :class:`str`,
that will not be transformed into members, and will be removed from the final
class
- ``_order_`` -- used in Python 2/3 code to ensure member order is consistent
(class attribute, removed during class creation)
- ``_generate_next_value_`` -- used to get an appropriate value for an enum
member; may be overridden
- :meth:`~EnumType._add_alias_` -- adds a new name as an alias to an existing
member.
- :meth:`~EnumType._add_value_alias_` -- adds a new value as an alias to an
existing member.
- :attr:`~Enum._name_` -- name of the member
- :attr:`~Enum._value_` -- value of the member; can be set in ``__new__``
- :meth:`~Enum._missing_` -- a lookup function used when a value is not found;
may be overridden
- :attr:`~Enum._ignore_` -- a list of names, either as a :class:`list` or a
:class:`str`, that will not be transformed into members, and will be removed
from the final class
- :attr:`~Enum._order_` -- used in Python 2/3 code to ensure member order is
consistent (class attribute, removed during class creation)
- :meth:`~Enum._generate_next_value_` -- used to get an appropriate value for
an enum member; may be overridden
.. note::
For standard :class:`Enum` classes the next value chosen is the last value seen
incremented by one.
For standard :class:`Enum` classes the next value chosen is the highest
value seen incremented by one.
For :class:`Flag` classes the next value chosen will be the next highest
power-of-two, regardless of the last value seen.
power-of-two.
.. versionadded:: 3.6 ``_missing_``, ``_order_``, ``_generate_next_value_``
.. versionadded:: 3.7 ``_ignore_``
.. versionadded:: 3.13 ``_add_alias_``, ``_add_value_alias_``
---------------

View file

@ -38,36 +38,48 @@ information on defining exceptions is available in the Python Tutorial under
Exception context
-----------------
When raising a new exception while another exception
is already being handled, the new exception's
:attr:`__context__` attribute is automatically set to the handled
exception. An exception may be handled when an :keyword:`except` or
:keyword:`finally` clause, or a :keyword:`with` statement, is used.
.. index:: pair: exception; chaining
__cause__ (exception attribute)
__context__ (exception attribute)
__suppress_context__ (exception attribute)
This implicit exception context can be
supplemented with an explicit cause by using :keyword:`!from` with
:keyword:`raise`::
Three attributes on exception objects provide information about the context in
which the exception was raised:
raise new_exc from original_exc
.. attribute:: BaseException.__context__
BaseException.__cause__
BaseException.__suppress_context__
The expression following :keyword:`from<raise>` must be an exception or ``None``. It
will be set as :attr:`__cause__` on the raised exception. Setting
:attr:`__cause__` also implicitly sets the :attr:`__suppress_context__`
attribute to ``True``, so that using ``raise new_exc from None``
effectively replaces the old exception with the new one for display
purposes (e.g. converting :exc:`KeyError` to :exc:`AttributeError`), while
leaving the old exception available in :attr:`__context__` for introspection
when debugging.
When raising a new exception while another exception
is already being handled, the new exception's
:attr:`!__context__` attribute is automatically set to the handled
exception. An exception may be handled when an :keyword:`except` or
:keyword:`finally` clause, or a :keyword:`with` statement, is used.
The default traceback display code shows these chained exceptions in
addition to the traceback for the exception itself. An explicitly chained
exception in :attr:`__cause__` is always shown when present. An implicitly
chained exception in :attr:`__context__` is shown only if :attr:`__cause__`
is :const:`None` and :attr:`__suppress_context__` is false.
This implicit exception context can be
supplemented with an explicit cause by using :keyword:`!from` with
:keyword:`raise`::
In either case, the exception itself is always shown after any chained
exceptions so that the final line of the traceback always shows the last
exception that was raised.
raise new_exc from original_exc
The expression following :keyword:`from<raise>` must be an exception or ``None``. It
will be set as :attr:`!__cause__` on the raised exception. Setting
:attr:`!__cause__` also implicitly sets the :attr:`!__suppress_context__`
attribute to ``True``, so that using ``raise new_exc from None``
effectively replaces the old exception with the new one for display
purposes (e.g. converting :exc:`KeyError` to :exc:`AttributeError`), while
leaving the old exception available in :attr:`!__context__` for introspection
when debugging.
The default traceback display code shows these chained exceptions in
addition to the traceback for the exception itself. An explicitly chained
exception in :attr:`!__cause__` is always shown when present. An implicitly
chained exception in :attr:`!__context__` is shown only if :attr:`!__cause__`
is :const:`None` and :attr:`!__suppress_context__` is false.
In either case, the exception itself is always shown after any chained
exceptions so that the final line of the traceback always shows the last
exception that was raised.
Inheriting from built-in exceptions
@ -126,6 +138,12 @@ The following exceptions are used mostly as base classes for other exceptions.
tb = sys.exception().__traceback__
raise OtherException(...).with_traceback(tb)
.. attribute:: __traceback__
A writable field that holds the
:ref:`traceback object <traceback-objects>` associated with this
exception. See also: :ref:`raise`.
.. method:: add_note(note)
Add the string ``note`` to the exception's notes which appear in the standard
@ -429,9 +447,11 @@ The following exceptions are the exceptions that are usually raised.
:meth:`~iterator.__next__` method to signal that there are no further
items produced by the iterator.
The exception object has a single attribute :attr:`value`, which is
given as an argument when constructing the exception, and defaults
to :const:`None`.
.. attribute:: StopIteration.value
The exception object has a single attribute :attr:`!value`, which is
given as an argument when constructing the exception, and defaults
to :const:`None`.
When a :term:`generator` or :term:`coroutine` function
returns, a new :exc:`StopIteration` instance is
@ -927,8 +947,10 @@ their subgroups based on the types of the contained exceptions.
true for the exceptions that should be in the subgroup.
The nesting structure of the current exception is preserved in the result,
as are the values of its :attr:`message`, :attr:`__traceback__`,
:attr:`__cause__`, :attr:`__context__` and :attr:`__notes__` fields.
as are the values of its :attr:`message`,
:attr:`~BaseException.__traceback__`, :attr:`~BaseException.__cause__`,
:attr:`~BaseException.__context__` and
:attr:`~BaseException.__notes__` fields.
Empty nested groups are omitted from the result.
The condition is checked for all exceptions in the nested exception group,
@ -954,10 +976,14 @@ their subgroups based on the types of the contained exceptions.
and :meth:`split` return instances of the subclass rather
than :exc:`ExceptionGroup`.
:meth:`subgroup` and :meth:`split` copy the :attr:`__traceback__`,
:attr:`__cause__`, :attr:`__context__` and :attr:`__notes__` fields from
:meth:`subgroup` and :meth:`split` copy the
:attr:`~BaseException.__traceback__`,
:attr:`~BaseException.__cause__`, :attr:`~BaseException.__context__` and
:attr:`~BaseException.__notes__` fields from
the original exception group to the one returned by :meth:`derive`, so
these fields do not need to be updated by :meth:`derive`. ::
these fields do not need to be updated by :meth:`derive`.
.. doctest::
>>> class MyGroup(ExceptionGroup):
... def derive(self, excs):
@ -983,9 +1009,9 @@ their subgroups based on the types of the contained exceptions.
True
Note that :exc:`BaseExceptionGroup` defines :meth:`__new__`, so
Note that :exc:`BaseExceptionGroup` defines :meth:`~object.__new__`, so
subclasses that need a different constructor signature need to
override that rather than :meth:`__init__`. For example, the following
override that rather than :meth:`~object.__init__`. For example, the following
defines an exception group subclass which accepts an exit_code and
and constructs the group's message from it. ::

View file

@ -106,6 +106,10 @@ another rational number, or from a string.
presentation types ``"e"``, ``"E"``, ``"f"``, ``"F"``, ``"g"``, ``"G"``
and ``"%""``.
.. versionchanged:: 3.13
Formatting of :class:`Fraction` instances without a presentation type
now supports fill, alignment, sign handling, minimum width and grouping.
.. attribute:: numerator
Numerator of the Fraction in lowest term.
@ -201,17 +205,36 @@ another rational number, or from a string.
.. method:: __format__(format_spec, /)
Provides support for float-style formatting of :class:`Fraction`
instances via the :meth:`str.format` method, the :func:`format` built-in
function, or :ref:`Formatted string literals <f-strings>`. The
presentation types ``"e"``, ``"E"``, ``"f"``, ``"F"``, ``"g"``, ``"G"``
and ``"%"`` are supported. For these presentation types, formatting for a
:class:`Fraction` object ``x`` follows the rules outlined for
the :class:`float` type in the :ref:`formatspec` section.
Provides support for formatting of :class:`Fraction` instances via the
:meth:`str.format` method, the :func:`format` built-in function, or
:ref:`Formatted string literals <f-strings>`.
If the ``format_spec`` format specification string does not end with one
of the presentation types ``'e'``, ``'E'``, ``'f'``, ``'F'``, ``'g'``,
``'G'`` or ``'%'`` then formatting follows the general rules for fill,
alignment, sign handling, minimum width, and grouping as described in the
:ref:`format specification mini-language <formatspec>`. The "alternate
form" flag ``'#'`` is supported: if present, it forces the output string
to always include an explicit denominator, even when the value being
formatted is an exact integer. The zero-fill flag ``'0'`` is not
supported.
If the ``format_spec`` format specification string ends with one of
the presentation types ``'e'``, ``'E'``, ``'f'``, ``'F'``, ``'g'``,
``'G'`` or ``'%'`` then formatting follows the rules outlined for the
:class:`float` type in the :ref:`formatspec` section.
Here are some examples::
>>> from fractions import Fraction
>>> format(Fraction(103993, 33102), '_')
'103_993/33_102'
>>> format(Fraction(1, 7), '.^+10')
'...+1/7...'
>>> format(Fraction(3, 1), '')
'3'
>>> format(Fraction(3, 1), '#')
'3/1'
>>> format(Fraction(1, 7), '.40g')
'0.1428571428571428571428571428571428571429'
>>> format(Fraction('1234567.855'), '_.2f')

View file

@ -57,7 +57,8 @@ are always available. They are listed here in alphabetical order.
.. function:: abs(x)
Return the absolute value of a number. The argument may be an
integer, a floating point number, or an object implementing :meth:`__abs__`.
integer, a floating point number, or an object implementing
:meth:`~object.__abs__`.
If the argument is a complex number, its magnitude is returned.
@ -235,7 +236,7 @@ are always available. They are listed here in alphabetical order.
:const:`False` if not. If this returns ``True``, it is still possible that a
call fails, but if it is ``False``, calling *object* will never succeed.
Note that classes are callable (calling a class returns a new instance);
instances are callable if their class has a :meth:`__call__` method.
instances are callable if their class has a :meth:`~object.__call__` method.
.. versionadded:: 3.2
This function was first removed in Python 3.0 and then brought back
@ -432,15 +433,18 @@ are always available. They are listed here in alphabetical order.
Without arguments, return the list of names in the current local scope. With an
argument, attempt to return a list of valid attributes for that object.
If the object has a method named :meth:`__dir__`, this method will be called and
If the object has a method named :meth:`~object.__dir__`,
this method will be called and
must return the list of attributes. This allows objects that implement a custom
:func:`__getattr__` or :func:`__getattribute__` function to customize the way
:func:`~object.__getattr__` or :func:`~object.__getattribute__` function
to customize the way
:func:`dir` reports their attributes.
If the object does not provide :meth:`__dir__`, the function tries its best to
gather information from the object's :attr:`~object.__dict__` attribute, if defined, and
If the object does not provide :meth:`~object.__dir__`,
the function tries its best to gather information from the object's
:attr:`~object.__dict__` attribute, if defined, and
from its type object. The resulting list is not necessarily complete and may
be inaccurate when the object has a custom :func:`__getattr__`.
be inaccurate when the object has a custom :func:`~object.__getattr__`.
The default :func:`dir` mechanism behaves differently with different types of
objects, as it attempts to produce the most relevant, rather than complete,
@ -664,7 +668,7 @@ are always available. They are listed here in alphabetical order.
sign: "+" | "-"
infinity: "Infinity" | "inf"
nan: "nan"
digitpart: `digit` (["_"] `digit`)*
digitpart: `!digit` (["_"] `!digit`)*
number: [`digitpart`] "." `digitpart` | `digitpart` ["."]
exponent: ("e" | "E") ["+" | "-"] `digitpart`
floatnumber: number [`exponent`]
@ -727,8 +731,8 @@ are always available. They are listed here in alphabetical order.
A call to ``format(value, format_spec)`` is translated to
``type(value).__format__(value, format_spec)`` which bypasses the instance
dictionary when searching for the value's :meth:`__format__` method. A
:exc:`TypeError` exception is raised if the method search reaches
dictionary when searching for the value's :meth:`~object.__format__` method.
A :exc:`TypeError` exception is raised if the method search reaches
:mod:`object` and the *format_spec* is non-empty, or if either the
*format_spec* or the return value are not strings.
@ -792,9 +796,9 @@ are always available. They are listed here in alphabetical order.
.. note::
For objects with custom :meth:`__hash__` methods, note that :func:`hash`
For objects with custom :meth:`~object.__hash__` methods,
note that :func:`hash`
truncates the return value based on the bit width of the host machine.
See :meth:`__hash__ <object.__hash__>` for details.
.. function:: help()
help(request)
@ -982,7 +986,8 @@ are always available. They are listed here in alphabetical order.
Return an :term:`iterator` object. The first argument is interpreted very
differently depending on the presence of the second argument. Without a
second argument, *object* must be a collection object which supports the
:term:`iterable` protocol (the :meth:`__iter__` method), or it must support
:term:`iterable` protocol (the :meth:`~object.__iter__` method),
or it must support
the sequence protocol (the :meth:`~object.__getitem__` method with integer arguments
starting at ``0``). If it does not support either of those protocols,
:exc:`TypeError` is raised. If the second argument, *sentinel*, is given,
@ -1221,7 +1226,7 @@ are always available. They are listed here in alphabetical order.
*buffering* is an optional integer used to set the buffering policy. Pass 0
to switch buffering off (only allowed in binary mode), 1 to select line
buffering (only usable in text mode), and an integer > 1 to indicate the size
buffering (only usable when writing in text mode), and an integer > 1 to indicate the size
in bytes of a fixed-size chunk buffer. Note that specifying a buffer size this
way applies for binary buffered I/O, but ``TextIOWrapper`` (i.e., files opened
with ``mode='r+'``) would have another buffering. To disable buffering in
@ -1500,38 +1505,44 @@ are always available. They are listed here in alphabetical order.
"""Get the current voltage."""
return self._voltage
The ``@property`` decorator turns the :meth:`voltage` method into a "getter"
The ``@property`` decorator turns the :meth:`!voltage` method into a "getter"
for a read-only attribute with the same name, and it sets the docstring for
*voltage* to "Get the current voltage."
A property object has :attr:`~property.getter`, :attr:`~property.setter`,
and :attr:`~property.deleter` methods usable as decorators that create a
copy of the property with the corresponding accessor function set to the
decorated function. This is best explained with an example::
.. decorator:: property.getter
.. decorator:: property.setter
.. decorator:: property.deleter
class C:
def __init__(self):
self._x = None
A property object has ``getter``, ``setter``,
and ``deleter`` methods usable as decorators that create a
copy of the property with the corresponding accessor function set to the
decorated function. This is best explained with an example:
@property
def x(self):
"""I'm the 'x' property."""
return self._x
.. testcode::
@x.setter
def x(self, value):
self._x = value
class C:
def __init__(self):
self._x = None
@x.deleter
def x(self):
del self._x
@property
def x(self):
"""I'm the 'x' property."""
return self._x
This code is exactly equivalent to the first example. Be sure to give the
additional functions the same name as the original property (``x`` in this
case.)
@x.setter
def x(self, value):
self._x = value
The returned property object also has the attributes ``fget``, ``fset``, and
``fdel`` corresponding to the constructor arguments.
@x.deleter
def x(self):
del self._x
This code is exactly equivalent to the first example. Be sure to give the
additional functions the same name as the original property (``x`` in this
case.)
The returned property object also has the attributes ``fget``, ``fset``, and
``fdel`` corresponding to the constructor arguments.
.. versionchanged:: 3.5
The docstrings of property objects are now writeable.
@ -1554,7 +1565,8 @@ are always available. They are listed here in alphabetical order.
representation is a string enclosed in angle brackets that contains the name
of the type of the object together with additional information often
including the name and address of the object. A class can control what this
function returns for its instances by defining a :meth:`__repr__` method.
function returns for its instances
by defining a :meth:`~object.__repr__` method.
If :func:`sys.displayhook` is not accessible, this function will raise
:exc:`RuntimeError`.
@ -1562,9 +1574,9 @@ are always available. They are listed here in alphabetical order.
.. function:: reversed(seq)
Return a reverse :term:`iterator`. *seq* must be an object which has
a :meth:`__reversed__` method or supports the sequence protocol (the
:meth:`__len__` method and the :meth:`~object.__getitem__` method with integer
arguments starting at ``0``).
a :meth:`~object.__reversed__` method or supports the sequence protocol (the
:meth:`~object.__len__` method and the :meth:`~object.__getitem__` method
with integer arguments starting at ``0``).
.. function:: round(number, ndigits=None)
@ -1635,13 +1647,21 @@ are always available. They are listed here in alphabetical order.
Return a :term:`slice` object representing the set of indices specified by
``range(start, stop, step)``. The *start* and *step* arguments default to
``None``. Slice objects have read-only data attributes :attr:`~slice.start`,
:attr:`~slice.stop`, and :attr:`~slice.step` which merely return the argument
values (or their default). They have no other explicit functionality;
however, they are used by NumPy and other third-party packages.
``None``.
.. attribute:: slice.start
.. attribute:: slice.stop
.. attribute:: slice.step
Slice objects have read-only data attributes :attr:`!start`,
:attr:`!stop`, and :attr:`!step` which merely return the argument
values (or their default). They have no other explicit functionality;
however, they are used by NumPy and other third-party packages.
Slice objects are also generated when extended indexing syntax is used. For
example: ``a[start:stop:step]`` or ``a[start:stop, i]``. See
:func:`itertools.islice` for an alternate version that returns an iterator.
:func:`itertools.islice` for an alternate version that returns an
:term:`iterator`.
.. versionchanged:: 3.12
Slice objects are now :term:`hashable` (provided :attr:`~slice.start`,
@ -1780,6 +1800,13 @@ are always available. They are listed here in alphabetical order.
the second argument is a type, ``issubclass(type2, type)`` must be true (this
is useful for classmethods).
When called directly within an ordinary method of a class, both arguments may
be omitted ("zero-argument :func:`!super`"). In this case, *type* will be the
enclosing class, and *obj* will be the first argument of the immediately
enclosing function (typically ``self``). (This means that zero-argument
:func:`!super` will not work as expected within nested functions, including
generator expressions, which implicitly create nested functions.)
There are two typical use cases for *super*. In a class hierarchy with
single inheritance, *super* can be used to refer to parent classes without
naming them explicitly, thus making the code more maintainable. This use
@ -1808,7 +1835,8 @@ are always available. They are listed here in alphabetical order.
Note that :func:`super` is implemented as part of the binding process for
explicit dotted attribute lookups such as ``super().__getitem__(name)``.
It does so by implementing its own :meth:`__getattribute__` method for searching
It does so by implementing its own :meth:`~object.__getattribute__` method
for searching
classes in a predictable order that supports cooperative multiple inheritance.
Accordingly, :func:`super` is undefined for implicit lookups using statements or
operators such as ``super()[name]``.

View file

@ -742,7 +742,7 @@ have three read-only attributes:
called.
:class:`partial` objects are like :class:`function` objects in that they are
callable, weak referencable, and can have attributes. There are some important
callable, weak referenceable, and can have attributes. There are some important
differences. For instance, the :attr:`~definition.__name__` and :attr:`__doc__` attributes
are not created automatically. Also, :class:`partial` objects defined in
classes behave like static methods and do not transform into bound methods

View file

@ -42,8 +42,8 @@ The :mod:`gc` module provides the following functions:
With no arguments, run a full collection. The optional argument *generation*
may be an integer specifying which generation to collect (from 0 to 2). A
:exc:`ValueError` is raised if the generation number is invalid. The number of
unreachable objects found is returned.
:exc:`ValueError` is raised if the generation number is invalid. The sum of
collected objects and uncollectable objects is returned.
The free lists maintained for a number of built-in types are cleared
whenever a full collection or collection of the highest generation (2)

View file

@ -46,7 +46,10 @@ The :mod:`getpass` module provides two functions:
:envvar:`USER`, :envvar:`!LNAME` and :envvar:`USERNAME`, in order, and
returns the value of the first one which is set to a non-empty string. If
none are set, the login name from the password database is returned on
systems which support the :mod:`pwd` module, otherwise, an exception is
raised.
systems which support the :mod:`pwd` module, otherwise, an :exc:`OSError`
is raised.
In general, this function should be preferred over :func:`os.getlogin()`.
.. versionchanged:: 3.13
Previously, various exceptions beyond just :exc:`OSError` were raised.

View file

@ -257,7 +257,7 @@ are the methods of :class:`!NullTranslations`:
.. method:: info()
Return the "protected" :attr:`_info` variable, a dictionary containing
Return a dictionary containing
the metadata found in the message catalog file.
@ -296,9 +296,9 @@ are the methods of :class:`!NullTranslations`:
The :class:`GNUTranslations` class
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The :mod:`gettext` module provides one additional class derived from
The :mod:`!gettext` module provides one additional class derived from
:class:`NullTranslations`: :class:`GNUTranslations`. This class overrides
:meth:`_parse` to enable reading GNU :program:`gettext` format :file:`.mo` files
:meth:`!_parse` to enable reading GNU :program:`gettext` format :file:`.mo` files
in both big-endian and little-endian format.
:class:`GNUTranslations` parses optional metadata out of the translation
@ -306,7 +306,7 @@ catalog. It is convention with GNU :program:`gettext` to include metadata as
the translation for the empty string. This metadata is in :rfc:`822`\ -style
``key: value`` pairs, and should contain the ``Project-Id-Version`` key. If the
key ``Content-Type`` is found, then the ``charset`` property is used to
initialize the "protected" :attr:`_charset` instance variable, defaulting to
initialize the "protected" :attr:`!_charset` instance variable, defaulting to
``None`` if not found. If the charset encoding is specified, then all message
ids and message strings read from the catalog are converted to Unicode using
this encoding, else ASCII is assumed.
@ -315,7 +315,7 @@ Since message ids are read as Unicode strings too, all ``*gettext()`` methods
will assume message ids as Unicode strings, not byte strings.
The entire set of key/value pairs are placed into a dictionary and set as the
"protected" :attr:`_info` instance variable.
"protected" :attr:`!_info` instance variable.
If the :file:`.mo` file's magic number is invalid, the major version number is
unexpected, or if other problems occur while reading the file, instantiating a
@ -636,9 +636,9 @@ implementations, and valuable experience to the creation of this module:
.. rubric:: Footnotes
.. [#] The default locale directory is system dependent; for example, on RedHat Linux
.. [#] The default locale directory is system dependent; for example, on Red Hat Linux
it is :file:`/usr/share/locale`, but on Solaris it is :file:`/usr/lib/locale`.
The :mod:`gettext` module does not try to support these system dependent
The :mod:`!gettext` module does not try to support these system dependent
defaults; instead its default is :file:`{sys.base_prefix}/share/locale` (see
:data:`sys.base_prefix`). For this reason, it is always best to call
:func:`bindtextdomain` with an explicit absolute path at the start of your

View file

@ -105,7 +105,7 @@ The module defines the following items:
should only be provided in compression mode. If omitted or ``None``, the
current time is used. See the :attr:`mtime` attribute for more details.
Calling a :class:`GzipFile` object's :meth:`close` method does not close
Calling a :class:`GzipFile` object's :meth:`!close` method does not close
*fileobj*, since you might wish to append more material after the compressed
data. This also allows you to pass an :class:`io.BytesIO` object opened for
writing as *fileobj*, and retrieve the resulting memory buffer using the

View file

@ -14,7 +14,7 @@
This module implements the HMAC algorithm as described by :rfc:`2104`.
.. function:: new(key, msg=None, digestmod='')
.. function:: new(key, msg=None, digestmod)
Return a new hmac object. *key* is a bytes or bytearray object giving the
secret key. If *msg* is present, the method call ``update(msg)`` is made.
@ -27,10 +27,9 @@ This module implements the HMAC algorithm as described by :rfc:`2104`.
Parameter *msg* can be of any type supported by :mod:`hashlib`.
Parameter *digestmod* can be the name of a hash algorithm.
.. deprecated-removed:: 3.4 3.8
MD5 as implicit default digest for *digestmod* is deprecated.
The digestmod parameter is now required. Pass it as a keyword
argument to avoid awkwardness when you do not have an initial msg.
.. versionchanged:: 3.8
The *digestmod* argument is now required. Pass it as a keyword
argument to avoid awkwardness when you do not have an initial *msg*.
.. function:: digest(key, msg, digest)
@ -114,11 +113,9 @@ A hash object has the following attributes:
.. versionadded:: 3.4
.. deprecated:: 3.9
The undocumented attributes ``HMAC.digest_cons``, ``HMAC.inner``, and
``HMAC.outer`` are internal implementation details and will be removed in
Python 3.10.
.. versionchanged:: 3.10
Removed the undocumented attributes ``HMAC.digest_cons``, ``HMAC.inner``,
and ``HMAC.outer``.
This module also provides the following helper function:

View file

@ -18,16 +18,17 @@ cookie value.
The module formerly strictly applied the parsing rules described in the
:rfc:`2109` and :rfc:`2068` specifications. It has since been discovered that
MSIE 3.0x doesn't follow the character rules outlined in those specs and also
many current day browsers and servers have relaxed parsing rules when comes to
Cookie handling. As a result, the parsing rules used are a bit less strict.
MSIE 3.0x didn't follow the character rules outlined in those specs; many
current-day browsers and servers have also relaxed parsing rules when it comes
to cookie handling. As a result, this module now uses parsing rules that are a
bit less strict than they once were.
The character set, :data:`string.ascii_letters`, :data:`string.digits` and
``!#$%&'*+-.^_`|~:`` denote the set of valid characters allowed by this module
in Cookie name (as :attr:`~Morsel.key`).
in a cookie name (as :attr:`~Morsel.key`).
.. versionchanged:: 3.3
Allowed ':' as a valid Cookie name character.
Allowed ':' as a valid cookie name character.
.. note::
@ -54,9 +55,10 @@ in Cookie name (as :attr:`~Morsel.key`).
.. class:: SimpleCookie([input])
This class derives from :class:`BaseCookie` and overrides :meth:`value_decode`
and :meth:`value_encode`. SimpleCookie supports strings as cookie values.
When setting the value, SimpleCookie calls the builtin :func:`str()` to convert
This class derives from :class:`BaseCookie` and overrides :meth:`~BaseCookie.value_decode`
and :meth:`~BaseCookie.value_encode`. :class:`!SimpleCookie` supports
strings as cookie values. When setting the value, :class:`!SimpleCookie`
calls the builtin :func:`str` to convert
the value to a string. Values received from HTTP are kept as strings.
.. seealso::
@ -129,17 +131,17 @@ Morsel Objects
Abstract a key/value pair, which has some :rfc:`2109` attributes.
Morsels are dictionary-like objects, whose set of keys is constant --- the valid
:rfc:`2109` attributes, which are
:rfc:`2109` attributes, which are:
* ``expires``
* ``path``
* ``comment``
* ``domain``
* ``max-age``
* ``secure``
* ``version``
* ``httponly``
* ``samesite``
.. attribute:: expires
path
comment
domain
max-age
secure
version
httponly
samesite
The attribute :attr:`httponly` specifies that the cookie is only transferred
in HTTP requests, and is not accessible through JavaScript. This is intended
@ -152,7 +154,7 @@ Morsel Objects
The keys are case-insensitive and their default value is ``''``.
.. versionchanged:: 3.5
:meth:`~Morsel.__eq__` now takes :attr:`~Morsel.key` and :attr:`~Morsel.value`
:meth:`!__eq__` now takes :attr:`~Morsel.key` and :attr:`~Morsel.value`
into account.
.. versionchanged:: 3.7

View file

@ -65,10 +65,10 @@ provides three different variants:
The handler will parse the request and the headers, then call a method
specific to the request type. The method name is constructed from the
request. For example, for the request method ``SPAM``, the :meth:`do_SPAM`
request. For example, for the request method ``SPAM``, the :meth:`!do_SPAM`
method will be called with no arguments. All of the relevant information is
stored in instance variables of the handler. Subclasses should not need to
override or extend the :meth:`__init__` method.
override or extend the :meth:`!__init__` method.
:class:`BaseHTTPRequestHandler` has the following instance variables:
@ -187,13 +187,13 @@ provides three different variants:
Calls :meth:`handle_one_request` once (or, if persistent connections are
enabled, multiple times) to handle incoming HTTP requests. You should
never need to override it; instead, implement appropriate :meth:`do_\*`
never need to override it; instead, implement appropriate :meth:`!do_\*`
methods.
.. method:: handle_one_request()
This method will parse and dispatch the request to the appropriate
:meth:`do_\*` method. You should never need to override it.
:meth:`!do_\*` method. You should never need to override it.
.. method:: handle_expect_100()

View file

@ -171,16 +171,18 @@ group. Read `the setuptools docs
<https://setuptools.pypa.io/en/latest/userguide/entry_point.html>`_
for more information on entry points, their definition, and usage.
*Compatibility Note*
The "selectable" entry points were introduced in ``importlib_metadata``
3.6 and Python 3.10. Prior to those changes, ``entry_points`` accepted
no parameters and always returned a dictionary of entry points, keyed
by group. With ``importlib_metadata`` 5.0 and Python 3.12,
``entry_points`` always returns an ``EntryPoints`` object. See
`backports.entry_points_selectable <https://pypi.org/project/backports.entry-points-selectable>`_
for compatibility options.
.. versionchanged:: 3.12
The "selectable" entry points were introduced in ``importlib_metadata``
3.6 and Python 3.10. Prior to those changes, ``entry_points`` accepted
no parameters and always returned a dictionary of entry points, keyed
by group. With ``importlib_metadata`` 5.0 and Python 3.12,
``entry_points`` always returns an ``EntryPoints`` object. See
`backports.entry_points_selectable <https://pypi.org/project/backports.entry-points-selectable>`_
for compatibility options.
.. versionchanged:: 3.13
``EntryPoint`` objects no longer present a tuple-like interface
(:meth:`~object.__getitem__`).
.. _metadata:
@ -342,9 +344,17 @@ instance::
>>> dist.metadata['License'] # doctest: +SKIP
'MIT'
For editable packages, an origin property may present :pep:`610`
metadata::
>>> dist.origin.url
'file:///path/to/wheel-0.32.3.editable-py3-none-any.whl'
The full set of available metadata is not described here.
See the `Core metadata specifications <https://packaging.python.org/en/latest/specifications/core-metadata/#core-metadata>`_ for additional details.
.. versionadded:: 3.13
The ``.origin`` property was added.
Distribution Discovery
======================

View file

@ -50,7 +50,7 @@ for example, a package and its resources can be imported from a zip file using
``get_resource_reader(fullname)`` method as specified by
:class:`importlib.resources.abc.ResourceReader`.
.. data:: Anchor
.. class:: Anchor
Represents an anchor for resources, either a :class:`module object
<types.ModuleType>` or a module name as a string. Defined as
@ -63,7 +63,7 @@ for example, a package and its resources can be imported from a zip file using
(think files). A Traversable may contain other containers (think
subdirectories).
*anchor* is an optional :data:`Anchor`. If the anchor is a
*anchor* is an optional :class:`Anchor`. If the anchor is a
package, resources are resolved from that package. If a module,
resources are resolved adjacent to that module (in the same package
or the package root). If the anchor is omitted, the caller's module
@ -72,10 +72,10 @@ for example, a package and its resources can be imported from a zip file using
.. versionadded:: 3.9
.. versionchanged:: 3.12
"package" parameter was renamed to "anchor". "anchor" can now
*package* parameter was renamed to *anchor*. *anchor* can now
be a non-package module and if omitted will default to the caller's
module. "package" is still accepted for compatibility but will raise
a DeprecationWarning. Consider passing the anchor positionally or
module. *package* is still accepted for compatibility but will raise
a :exc:`DeprecationWarning`. Consider passing the anchor positionally or
using ``importlib_resources >= 5.10`` for a compatible interface
on older Pythons.
@ -96,4 +96,4 @@ for example, a package and its resources can be imported from a zip file using
.. versionadded:: 3.9
.. versionchanged:: 3.12
Added support for ``traversable`` representing a directory.
Added support for *traversable* representing a directory.

View file

@ -1145,7 +1145,7 @@ find and load modules.
.. versionadded:: 3.4
.. class:: NamespaceLoader(name, path, path_finder):
.. class:: NamespaceLoader(name, path, path_finder)
A concrete implementation of :class:`importlib.abc.InspectLoader` for
namespace packages. This is an alias for a private class and is only made

View file

@ -1,6 +1,11 @@
:mod:`inspect` --- Inspect live objects
=======================================
.. testsetup:: *
import inspect
from inspect import *
.. module:: inspect
:synopsis: Extract information and source code from live objects.
@ -268,7 +273,7 @@ attributes (see :ref:`import-mod-attrs` for module attributes):
:func:`getmembers` will only return class attributes defined in the
metaclass when the argument is a class and those attributes have been
listed in the metaclass' custom :meth:`__dir__`.
listed in the metaclass' custom :meth:`~object.__dir__`.
.. function:: getmembers_static(object[, predicate])
@ -387,7 +392,11 @@ attributes (see :ref:`import-mod-attrs` for module attributes):
Return ``True`` if the object can be used in :keyword:`await` expression.
Can also be used to distinguish generator-based coroutines from regular
generators::
generators:
.. testcode::
import types
def gen():
yield
@ -404,13 +413,15 @@ attributes (see :ref:`import-mod-attrs` for module attributes):
.. function:: isasyncgenfunction(object)
Return ``True`` if the object is an :term:`asynchronous generator` function,
for example::
for example:
>>> async def agen():
... yield 1
...
>>> inspect.isasyncgenfunction(agen)
True
.. doctest::
>>> async def agen():
... yield 1
...
>>> inspect.isasyncgenfunction(agen)
True
.. versionadded:: 3.6
@ -476,12 +487,13 @@ attributes (see :ref:`import-mod-attrs` for module attributes):
has a :meth:`~object.__get__` method but not a :meth:`~object.__set__`
method, but beyond that the set of attributes varies. A
:attr:`~definition.__name__` attribute is usually
sensible, and :attr:`__doc__` often is.
sensible, and :attr:`!__doc__` often is.
Methods implemented via descriptors that also pass one of the other tests
return ``False`` from the :func:`ismethoddescriptor` test, simply because the
other tests promise more -- you can, e.g., count on having the
:attr:`__func__` attribute (etc) when an object passes :func:`ismethod`.
:attr:`~method.__func__` attribute (etc) when an object passes
:func:`ismethod`.
.. function:: isdatadescriptor(object)
@ -492,7 +504,7 @@ attributes (see :ref:`import-mod-attrs` for module attributes):
Examples are properties (defined in Python), getsets, and members. The
latter two are defined in C and there are more specific tests available for
those types, which is robust across Python implementations. Typically, data
descriptors will also have :attr:`~definition.__name__` and :attr:`__doc__` attributes
descriptors will also have :attr:`~definition.__name__` and :attr:`!__doc__` attributes
(properties, getsets, and members have both of these attributes), but this is
not guaranteed.
@ -614,13 +626,16 @@ Introspecting callables with the Signature object
.. versionadded:: 3.3
The Signature object represents the call signature of a callable object and its
return annotation. To retrieve a Signature object, use the :func:`signature`
The :class:`Signature` object represents the call signature of a callable object
and its return annotation. To retrieve a :class:`!Signature` object,
use the :func:`!signature`
function.
.. function:: signature(callable, *, follow_wrapped=True, globals=None, locals=None, eval_str=False)
Return a :class:`Signature` object for the given ``callable``::
Return a :class:`Signature` object for the given *callable*:
.. doctest::
>>> from inspect import signature
>>> def foo(a, *, b:int, **kwargs):
@ -629,10 +644,10 @@ function.
>>> sig = signature(foo)
>>> str(sig)
'(a, *, b:int, **kwargs)'
'(a, *, b: int, **kwargs)'
>>> str(sig.parameters['b'])
'b:int'
'b: int'
>>> sig.parameters['b'].annotation
<class 'int'>
@ -646,29 +661,30 @@ function.
For objects defined in modules using stringized annotations
(``from __future__ import annotations``), :func:`signature` will
attempt to automatically un-stringize the annotations using
:func:`inspect.get_annotations()`. The
``global``, ``locals``, and ``eval_str`` parameters are passed
into :func:`inspect.get_annotations()` when resolving the
annotations; see the documentation for :func:`inspect.get_annotations()`
:func:`get_annotations`. The
*globals*, *locals*, and *eval_str* parameters are passed
into :func:`get_annotations` when resolving the
annotations; see the documentation for :func:`get_annotations`
for instructions on how to use these parameters.
Raises :exc:`ValueError` if no signature can be provided, and
:exc:`TypeError` if that type of object is not supported. Also,
if the annotations are stringized, and ``eval_str`` is not false,
the ``eval()`` call(s) to un-stringize the annotations could
potentially raise any kind of exception.
if the annotations are stringized, and *eval_str* is not false,
the ``eval()`` call(s) to un-stringize the annotations in :func:`get_annotations`
could potentially raise any kind of exception.
A slash(/) in the signature of a function denotes that the parameters prior
to it are positional-only. For more info, see
:ref:`the FAQ entry on positional-only parameters <faq-positional-only-arguments>`.
.. versionadded:: 3.5
``follow_wrapped`` parameter. Pass ``False`` to get a signature of
``callable`` specifically (``callable.__wrapped__`` will not be used to
.. versionchanged:: 3.5
The *follow_wrapped* parameter was added.
Pass ``False`` to get a signature of
*callable* specifically (``callable.__wrapped__`` will not be used to
unwrap decorated callables.)
.. versionadded:: 3.10
``globals``, ``locals``, and ``eval_str`` parameters.
.. versionchanged:: 3.10
The *globals*, *locals*, and *eval_str* parameters were added.
.. note::
@ -679,7 +695,8 @@ function.
.. class:: Signature(parameters=None, *, return_annotation=Signature.empty)
A Signature object represents the call signature of a function and its return
A :class:`!Signature` object represents the call signature of a function
and its return
annotation. For each parameter accepted by the function it stores a
:class:`Parameter` object in its :attr:`parameters` collection.
@ -689,14 +706,14 @@ function.
positional-only first, then positional-or-keyword, and that parameters with
defaults follow parameters without defaults.
The optional *return_annotation* argument, can be an arbitrary Python object,
is the "return" annotation of the callable.
The optional *return_annotation* argument can be an arbitrary Python object.
It represents the "return" annotation of the callable.
Signature objects are *immutable*. Use :meth:`Signature.replace` or
:class:`!Signature` objects are *immutable*. Use :meth:`Signature.replace` or
:func:`copy.replace` to make a modified copy.
.. versionchanged:: 3.5
Signature objects are picklable and :term:`hashable`.
:class:`!Signature` objects are now picklable and :term:`hashable`.
.. attribute:: Signature.empty
@ -733,13 +750,15 @@ function.
.. method:: Signature.replace(*[, parameters][, return_annotation])
Create a new Signature instance based on the instance :meth:`replace` was invoked
on. It is possible to pass different ``parameters`` and/or
``return_annotation`` to override the corresponding properties of the base
signature. To remove return_annotation from the copied Signature, pass in
Create a new :class:`Signature` instance based on the instance
:meth:`replace` was invoked on.
It is possible to pass different *parameters* and/or
*return_annotation* to override the corresponding properties of the base
signature. To remove ``return_annotation`` from the copied
:class:`!Signature`, pass in
:attr:`Signature.empty`.
::
.. doctest::
>>> def test(a, b):
... pass
@ -749,38 +768,50 @@ function.
>>> str(new_sig)
"(a, b) -> 'new return anno'"
Signature objects are also supported by generic function
:class:`Signature` objects are also supported by the generic function
:func:`copy.replace`.
.. classmethod:: Signature.from_callable(obj, *, follow_wrapped=True, globalns=None, localns=None)
.. method:: format(*, max_width=None)
Create a string representation of the :class:`Signature` object.
If *max_width* is passed, the method will attempt to fit
the signature into lines of at most *max_width* characters.
If the signature is longer than *max_width*,
all parameters will be on separate lines.
.. versionadded:: 3.13
.. classmethod:: Signature.from_callable(obj, *, follow_wrapped=True, globals=None, locals=None, eval_str=False)
Return a :class:`Signature` (or its subclass) object for a given callable
``obj``. Pass ``follow_wrapped=False`` to get a signature of ``obj``
without unwrapping its ``__wrapped__`` chain. ``globalns`` and
``localns`` will be used as the namespaces when resolving annotations.
*obj*.
This method simplifies subclassing of :class:`Signature`::
This method simplifies subclassing of :class:`Signature`:
class MySignature(Signature):
pass
sig = MySignature.from_callable(min)
assert isinstance(sig, MySignature)
.. testcode::
class MySignature(Signature):
pass
sig = MySignature.from_callable(sum)
assert isinstance(sig, MySignature)
Its behavior is otherwise identical to that of :func:`signature`.
.. versionadded:: 3.5
.. versionadded:: 3.10
``globalns`` and ``localns`` parameters.
.. versionchanged:: 3.10
The *globals*, *locals*, and *eval_str* parameters were added.
.. class:: Parameter(name, kind, *, default=Parameter.empty, annotation=Parameter.empty)
Parameter objects are *immutable*. Instead of modifying a Parameter object,
:class:`!Parameter` objects are *immutable*.
Instead of modifying a :class:`!Parameter` object,
you can use :meth:`Parameter.replace` or :func:`copy.replace` to create a modified copy.
.. versionchanged:: 3.5
Parameter objects are picklable and :term:`hashable`.
Parameter objects are now picklable and :term:`hashable`.
.. attribute:: Parameter.empty
@ -799,7 +830,7 @@ function.
expressions.
.. versionchanged:: 3.6
These parameter names are exposed by this module as names like
These parameter names are now exposed by this module as names like
``implicit0``.
.. attribute:: Parameter.default
@ -849,7 +880,9 @@ function.
| | definition. |
+------------------------+----------------------------------------------+
Example: print all keyword-only arguments without default values::
Example: print all keyword-only arguments without default values:
.. doctest::
>>> def foo(a, b, *, c, d=10):
... pass
@ -863,11 +896,13 @@ function.
.. attribute:: Parameter.kind.description
Describes a enum value of Parameter.kind.
Describes a enum value of :attr:`Parameter.kind`.
.. versionadded:: 3.8
Example: print all descriptions of arguments::
Example: print all descriptions of arguments:
.. doctest::
>>> def foo(a, b, *, c, d=10):
... pass
@ -882,12 +917,12 @@ function.
.. method:: Parameter.replace(*[, name][, kind][, default][, annotation])
Create a new Parameter instance based on the instance replaced was invoked
on. To override a :class:`Parameter` attribute, pass the corresponding
Create a new :class:`Parameter` instance based on the instance replaced was invoked
on. To override a :class:`!Parameter` attribute, pass the corresponding
argument. To remove a default value or/and an annotation from a
Parameter, pass :attr:`Parameter.empty`.
:class:`!Parameter`, pass :attr:`Parameter.empty`.
::
.. doctest::
>>> from inspect import Parameter
>>> param = Parameter('foo', Parameter.KEYWORD_ONLY, default=42)
@ -898,12 +933,13 @@ function.
'foo=42'
>>> str(param.replace(default=Parameter.empty, annotation='spam'))
"foo:'spam'"
"foo: 'spam'"
Parameter objects are also supported by generic function :func:`copy.replace`.
:class:`Parameter` objects are also supported by the generic function
:func:`copy.replace`.
.. versionchanged:: 3.4
In Python 3.3 Parameter objects were allowed to have ``name`` set
In Python 3.3 :class:`Parameter` objects were allowed to have ``name`` set
to ``None`` if their ``kind`` was set to ``POSITIONAL_ONLY``.
This is no longer permitted.
@ -956,18 +992,20 @@ function.
For variable-keyword arguments (``**kwargs``) the default is an
empty dict.
::
.. doctest::
>>> def foo(a, b='ham', *args): pass
>>> ba = inspect.signature(foo).bind('spam')
>>> ba.apply_defaults()
>>> ba.arguments
{'a': 'spam', 'b': 'ham', 'args': ()}
>>> def foo(a, b='ham', *args): pass
>>> ba = inspect.signature(foo).bind('spam')
>>> ba.apply_defaults()
>>> ba.arguments
{'a': 'spam', 'b': 'ham', 'args': ()}
.. versionadded:: 3.5
The :attr:`args` and :attr:`kwargs` properties can be used to invoke
functions::
functions:
.. testcode::
def test(a, *, b):
...
@ -1086,20 +1124,22 @@ Classes and functions
``**`` arguments, if any) to their values from *args* and *kwds*. In case of
invoking *func* incorrectly, i.e. whenever ``func(*args, **kwds)`` would raise
an exception because of incompatible signature, an exception of the same type
and the same or similar message is raised. For example::
and the same or similar message is raised. For example:
>>> from inspect import getcallargs
>>> def f(a, b=1, *pos, **named):
... pass
...
>>> getcallargs(f, 1, 2, 3) == {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
True
>>> getcallargs(f, a=2, x=4) == {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
True
>>> getcallargs(f)
Traceback (most recent call last):
...
TypeError: f() missing 1 required positional argument: 'a'
.. doctest::
>>> from inspect import getcallargs
>>> def f(a, b=1, *pos, **named):
... pass
...
>>> getcallargs(f, 1, 2, 3) == {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
True
>>> getcallargs(f, a=2, x=4) == {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
True
>>> getcallargs(f)
Traceback (most recent call last):
...
TypeError: f() missing 1 required positional argument: 'a'
.. versionadded:: 3.2
@ -1185,9 +1225,10 @@ Classes and functions
* If ``obj`` is a class, ``globals`` defaults to
``sys.modules[obj.__module__].__dict__`` and ``locals`` defaults
to the ``obj`` class namespace.
* If ``obj`` is a callable, ``globals`` defaults to ``obj.__globals__``,
* If ``obj`` is a callable, ``globals`` defaults to
:attr:`obj.__globals__ <function.__globals__>`,
although if ``obj`` is a wrapped function (using
``functools.update_wrapper()``) it is first unwrapped.
:func:`functools.update_wrapper`) it is first unwrapped.
Calling ``get_annotations`` is best practice for accessing the
annotations dict of any object. See :ref:`annotations-howto` for
@ -1401,7 +1442,8 @@ Fetching attributes statically
Both :func:`getattr` and :func:`hasattr` can trigger code execution when
fetching or checking for the existence of attributes. Descriptors, like
properties, will be invoked and :meth:`__getattr__` and :meth:`__getattribute__`
properties, will be invoked and :meth:`~object.__getattr__` and
:meth:`~object.__getattribute__`
may be called.
For cases where you want passive introspection, like documentation tools, this
@ -1411,7 +1453,8 @@ but avoids executing code when it fetches attributes.
.. function:: getattr_static(obj, attr, default=None)
Retrieve attributes without triggering dynamic lookup via the
descriptor protocol, :meth:`__getattr__` or :meth:`__getattribute__`.
descriptor protocol, :meth:`~object.__getattr__`
or :meth:`~object.__getattribute__`.
Note: this function may not be able to retrieve all attributes
that getattr can fetch (like dynamically created attributes)
@ -1554,8 +1597,8 @@ updated as expected:
Code Objects Bit Flags
----------------------
Python code objects have a ``co_flags`` attribute, which is a bitmap of
the following flags:
Python code objects have a :attr:`~codeobject.co_flags` attribute,
which is a bitmap of the following flags:
.. data:: CO_OPTIMIZED
@ -1563,8 +1606,8 @@ the following flags:
.. data:: CO_NEWLOCALS
If set, a new dict will be created for the frame's ``f_locals`` when
the code object is executed.
If set, a new dict will be created for the frame's :attr:`~frame.f_locals`
when the code object is executed.
.. data:: CO_VARARGS

View file

@ -164,11 +164,14 @@ loops that truncate the stream.
Added the optional *initial* parameter.
.. function:: batched(iterable, n)
.. function:: batched(iterable, n, *, strict=False)
Batch data from the *iterable* into tuples of length *n*. The last
batch may be shorter than *n*.
If *strict* is true, will raise a :exc:`ValueError` if the final
batch is shorter than *n*.
Loops over the input iterable and accumulates data into tuples up to
size *n*. The input is consumed lazily, just enough to fill a batch.
The result is yielded as soon as the batch is full or when the input
@ -190,16 +193,21 @@ loops that truncate the stream.
Roughly equivalent to::
def batched(iterable, n):
def batched(iterable, n, *, strict=False):
# batched('ABCDEFG', 3) --> ABC DEF G
if n < 1:
raise ValueError('n must be at least one')
it = iter(iterable)
while batch := tuple(islice(it, n)):
if strict and len(batch) != n:
raise ValueError('batched(): incomplete batch')
yield batch
.. versionadded:: 3.12
.. versionchanged:: 3.13
Added the *strict* option.
.. function:: chain(*iterables)
@ -795,11 +803,11 @@ which incur interpreter overhead.
import random
def take(n, iterable):
"Return first n items of the iterable as a list"
"Return first n items of the iterable as a list."
return list(islice(iterable, n))
def prepend(value, iterable):
"Prepend a single value in front of an iterable"
"Prepend a single value in front of an iterable."
# prepend(1, [2, 3, 4]) --> 1 2 3 4
return chain([value], iterable)
@ -817,15 +825,15 @@ which incur interpreter overhead.
return starmap(func, repeat(args, times))
def flatten(list_of_lists):
"Flatten one level of nesting"
"Flatten one level of nesting."
return chain.from_iterable(list_of_lists)
def ncycles(iterable, n):
"Returns the sequence elements n times"
"Returns the sequence elements n times."
return chain.from_iterable(repeat(tuple(iterable), n))
def tail(n, iterable):
"Return an iterator over the last n items"
"Return an iterator over the last n items."
# tail(3, 'ABCDEFG') --> E F G
return iter(collections.deque(iterable, maxlen=n))
@ -840,7 +848,7 @@ which incur interpreter overhead.
next(islice(iterator, n, n), None)
def nth(iterable, n, default=None):
"Returns the nth item or a default value"
"Returns the nth item or a default value."
return next(islice(iterable, n, None), default)
def quantify(iterable, pred=bool):
@ -848,7 +856,7 @@ which incur interpreter overhead.
return sum(map(pred, iterable))
def all_equal(iterable):
"Returns True if all the elements are equal to each other"
"Returns True if all the elements are equal to each other."
g = groupby(iterable)
return next(g, True) and not next(g, False)
@ -865,6 +873,30 @@ which incur interpreter overhead.
# first_true([a,b], x, f) --> a if f(a) else b if f(b) else x
return next(filter(pred, iterable), default)
def unique_everseen(iterable, key=None):
"List unique elements, preserving order. Remember all elements ever seen."
# unique_everseen('AAAABBBCCDAABBB') --> A B C D
# unique_everseen('ABBcCAD', str.casefold) --> A B c D
seen = set()
if key is None:
for element in filterfalse(seen.__contains__, iterable):
seen.add(element)
yield element
else:
for element in iterable:
k = key(element)
if k not in seen:
seen.add(k)
yield element
def unique_justseen(iterable, key=None):
"List unique elements, preserving order. Remember only the element just seen."
# unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
# unique_justseen('ABBcCAD', str.casefold) --> A B c A D
if key is None:
return map(operator.itemgetter(0), groupby(iterable))
return map(next, map(operator.itemgetter(1), groupby(iterable, key)))
def iter_index(iterable, value, start=0, stop=None):
"Return indices where a value occurs in a sequence or iterable."
# iter_index('AABCADEAF', 'A') --> 0 1 4 7
@ -885,45 +917,8 @@ which incur interpreter overhead.
except ValueError:
pass
def iter_except(func, exception, first=None):
""" Call a function repeatedly until an exception is raised.
Converts a call-until-exception interface to an iterator interface.
Like builtins.iter(func, sentinel) but uses an exception instead
of a sentinel to end the loop.
Examples:
iter_except(functools.partial(heappop, h), IndexError) # priority queue iterator
iter_except(d.popitem, KeyError) # non-blocking dict iterator
iter_except(d.popleft, IndexError) # non-blocking deque iterator
iter_except(q.get_nowait, Queue.Empty) # loop over a producer Queue
iter_except(s.pop, KeyError) # non-blocking set iterator
"""
try:
if first is not None:
yield first() # For database APIs needing an initial cast to db.first()
while True:
yield func()
except exception:
pass
def grouper(iterable, n, *, incomplete='fill', fillvalue=None):
"Collect data into non-overlapping fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, fillvalue='x') --> ABC DEF Gxx
# grouper('ABCDEFG', 3, incomplete='strict') --> ABC DEF ValueError
# grouper('ABCDEFG', 3, incomplete='ignore') --> ABC DEF
args = [iter(iterable)] * n
if incomplete == 'fill':
return zip_longest(*args, fillvalue=fillvalue)
if incomplete == 'strict':
return zip(*args, strict=True)
if incomplete == 'ignore':
return zip(*args)
else:
raise ValueError('Expected fill, strict, or ignore')
def sliding_window(iterable, n):
"Collect data into overlapping fixed-length chunks or blocks."
# sliding_window('ABCDEFG', 4) --> ABCD BCDE CDEF DEFG
it = iter(iterable)
window = collections.deque(islice(it, n-1), maxlen=n)
@ -931,8 +926,25 @@ which incur interpreter overhead.
window.append(x)
yield tuple(window)
def grouper(iterable, n, *, incomplete='fill', fillvalue=None):
"Collect data into non-overlapping fixed-length chunks or blocks."
# grouper('ABCDEFG', 3, fillvalue='x') --> ABC DEF Gxx
# grouper('ABCDEFG', 3, incomplete='strict') --> ABC DEF ValueError
# grouper('ABCDEFG', 3, incomplete='ignore') --> ABC DEF
args = [iter(iterable)] * n
match incomplete:
case 'fill':
return zip_longest(*args, fillvalue=fillvalue)
case 'strict':
return zip(*args, strict=True)
case 'ignore':
return zip(*args)
case _:
raise ValueError('Expected fill, strict, or ignore')
def roundrobin(*iterables):
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
"Visit input iterables in a cycle until each is exhausted."
# roundrobin('ABC', 'D', 'EF') --> A D E B F C
# Recipe credited to George Sakkis
num_active = len(iterables)
nexts = cycle(iter(it).__next__ for it in iterables)
@ -955,11 +967,43 @@ which incur interpreter overhead.
return filterfalse(pred, t1), filter(pred, t2)
def subslices(seq):
"Return all contiguous non-empty subslices of a sequence"
"Return all contiguous non-empty subslices of a sequence."
# subslices('ABCD') --> A AB ABC ABCD B BC BCD C CD D
slices = starmap(slice, combinations(range(len(seq) + 1), 2))
return map(operator.getitem, repeat(seq), slices)
def iter_except(func, exception, first=None):
""" Call a function repeatedly until an exception is raised.
Converts a call-until-exception interface to an iterator interface.
Like builtins.iter(func, sentinel) but uses an exception instead
of a sentinel to end the loop.
Priority queue iterator:
iter_except(functools.partial(heappop, h), IndexError)
Non-blocking dictionary iterator:
iter_except(d.popitem, KeyError)
Non-blocking deque iterator:
iter_except(d.popleft, IndexError)
Non-blocking iterator over a producer Queue:
iter_except(q.get_nowait, Queue.Empty)
Non-blocking set iterator:
iter_except(s.pop, KeyError)
"""
try:
if first is not None:
# For database APIs needing an initial call to db.first()
yield first()
while True:
yield func()
except exception:
pass
def before_and_after(predicate, it):
""" Variant of takewhile() that allows complete
access to the remainder of the iterator.
@ -971,12 +1015,12 @@ which incur interpreter overhead.
>>> ''.join(remainder) # takewhile() would lose the 'd'
'dEfGhI'
Note that the first iterator must be fully
consumed before the second iterator can
generate valid results.
Note that the true iterator must be fully consumed
before the remainder iterator can generate valid results.
"""
it = iter(it)
transition = []
def true_iterator():
for elem in it:
if predicate(elem):
@ -984,39 +1028,8 @@ which incur interpreter overhead.
else:
transition.append(elem)
return
def remainder_iterator():
yield from transition
yield from it
return true_iterator(), remainder_iterator()
def unique_everseen(iterable, key=None):
"List unique elements, preserving order. Remember all elements ever seen."
# unique_everseen('AAAABBBCCDAABBB') --> A B C D
# unique_everseen('ABBcCAD', str.lower) --> A B c D
seen = set()
if key is None:
for element in filterfalse(seen.__contains__, iterable):
seen.add(element)
yield element
# For order preserving deduplication,
# a faster but non-lazy solution is:
# yield from dict.fromkeys(iterable)
else:
for element in iterable:
k = key(element)
if k not in seen:
seen.add(k)
yield element
# For use cases that allow the last matching element to be returned,
# a faster but non-lazy solution is:
# t1, t2 = tee(iterable)
# yield from dict(zip(map(key, t1), t2)).values()
def unique_justseen(iterable, key=None):
"List unique elements, preserving order. Remember only the element just seen."
# unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
# unique_justseen('ABBcCAD', str.lower) --> A B c A D
return map(next, map(operator.itemgetter(1), groupby(iterable, key)))
return true_iterator(), chain(transition, it)
The following recipes have a more mathematical flavor:
@ -1033,10 +1046,15 @@ The following recipes have a more mathematical flavor:
# sum_of_squares([10, 20, 30]) -> 1400
return math.sumprod(*tee(it))
def transpose(it):
"Swap the rows and columns of the input."
def reshape(matrix, cols):
"Reshape a 2-D matrix to have a given number of columns."
# reshape([(0, 1), (2, 3), (4, 5)], 3) --> (0, 1, 2), (3, 4, 5)
return batched(chain.from_iterable(matrix), cols, strict=True)
def transpose(matrix):
"Swap the rows and columns of a 2-D matrix."
# transpose([(1, 2, 3), (11, 22, 33)]) --> (1, 11) (2, 22) (3, 33)
return zip(*it, strict=True)
return zip(*matrix, strict=True)
def matmul(m1, m2):
"Multiply two matrices."
@ -1127,23 +1145,13 @@ The following recipes have a more mathematical flavor:
if n > 1:
yield n
def nth_combination(iterable, r, index):
"Equivalent to list(combinations(iterable, r))[index]"
pool = tuple(iterable)
n = len(pool)
c = math.comb(n, r)
if index < 0:
index += c
if index < 0 or index >= c:
raise IndexError
result = []
while r:
c, n, r = c*r//n, n-1, r-1
while index >= c:
index -= c
c, n = c*(n-r)//n, n-1
result.append(pool[-1-n])
return tuple(result)
def totient(n):
"Count of natural numbers up to n that are coprime to n."
# https://mathworld.wolfram.com/TotientFunction.html
# totient(12) --> 4 because len([1, 5, 7, 11]) == 4
for p in unique_justseen(factor(n)):
n = n // p * (p - 1)
return n
.. doctest::
@ -1261,6 +1269,26 @@ The following recipes have a more mathematical flavor:
>>> sum_of_squares([10, 20, 30])
1400
>>> list(reshape([(0, 1), (2, 3), (4, 5)], 3))
[(0, 1, 2), (3, 4, 5)]
>>> M = [(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11)]
>>> list(reshape(M, 1))
[(0,), (1,), (2,), (3,), (4,), (5,), (6,), (7,), (8,), (9,), (10,), (11,)]
>>> list(reshape(M, 2))
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10, 11)]
>>> list(reshape(M, 3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)]
>>> list(reshape(M, 4))
[(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11)]
>>> list(reshape(M, 5))
Traceback (most recent call last):
...
ValueError: batched(): incomplete batch
>>> list(reshape(M, 6))
[(0, 1, 2, 3, 4, 5), (6, 7, 8, 9, 10, 11)]
>>> list(reshape(M, 12))
[(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)]
>>> list(transpose([(1, 2, 3), (11, 22, 33)]))
[(1, 11), (2, 22), (3, 33)]
@ -1428,6 +1456,25 @@ The following recipes have a more mathematical flavor:
>>> all(list(factor(n)) == sorted(factor(n)) for n in range(2_000))
True
>>> totient(0) # https://www.wolframalpha.com/input?i=totient+0
0
>>> first_totients = [1, 1, 2, 2, 4, 2, 6, 4, 6, 4, 10, 4, 12, 6, 8, 8, 16, 6,
... 18, 8, 12, 10, 22, 8, 20, 12, 18, 12, 28, 8, 30, 16, 20, 16, 24, 12, 36, 18,
... 24, 16, 40, 12, 42, 20, 24, 22, 46, 16, 42, 20, 32, 24, 52, 18, 40, 24, 36,
... 28, 58, 16, 60, 30, 36, 32, 48, 20, 66, 32, 44] # https://oeis.org/A000010
...
>>> list(map(totient, range(1, 70))) == first_totients
True
>>> reference_totient = lambda n: sum(math.gcd(t, n) == 1 for t in range(1, n+1))
>>> all(totient(n) == reference_totient(n) for n in range(1000))
True
>>> totient(128_884_753_939) == 128_884_753_938 # large prime
True
>>> totient(999953 * 999983) == 999952 * 999982 # large semiprime
True
>>> totient(6 ** 20) == 1 * 2**19 * 2 * 3**19 # repeated primes
True
>>> list(flatten([('a', 'b'), (), ('c', 'd', 'e'), ('f',), ('g', 'h', 'i')]))
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
@ -1517,16 +1564,16 @@ The following recipes have a more mathematical flavor:
>>> list(unique_everseen('AAAABBBCCDAABBB'))
['A', 'B', 'C', 'D']
>>> list(unique_everseen('ABBCcAD', str.lower))
>>> list(unique_everseen('ABBCcAD', str.casefold))
['A', 'B', 'C', 'D']
>>> list(unique_everseen('ABBcCAD', str.lower))
>>> list(unique_everseen('ABBcCAD', str.casefold))
['A', 'B', 'c', 'D']
>>> list(unique_justseen('AAAABBBCCDAABBB'))
['A', 'B', 'C', 'D', 'A', 'B']
>>> list(unique_justseen('ABBCcAD', str.lower))
>>> list(unique_justseen('ABBCcAD', str.casefold))
['A', 'B', 'C', 'A', 'D']
>>> list(unique_justseen('ABBcCAD', str.lower))
>>> list(unique_justseen('ABBcCAD', str.casefold))
['A', 'B', 'c', 'A', 'D']
>>> d = dict(a=1, b=2, c=3)
@ -1549,20 +1596,6 @@ The following recipes have a more mathematical flavor:
>>> first_true('ABC0DEF1', '9', str.isdigit)
'0'
>>> population = 'ABCDEFGH'
>>> for r in range(len(population) + 1):
... seq = list(combinations(population, r))
... for i in range(len(seq)):
... assert nth_combination(population, r, i) == seq[i]
... for i in range(-len(seq), 0):
... assert nth_combination(population, r, i) == seq[i]
>>> iterable = 'abcde'
>>> r = 3
>>> combos = list(combinations(iterable, r))
>>> all(nth_combination(iterable, r, i) == comb for i, comb in enumerate(combos))
True
.. testcode::
:hide:
@ -1589,6 +1622,24 @@ The following recipes have a more mathematical flavor:
for (a, _), (b, c) in pairwise(pairwise(iterable)):
yield a, b, c
def nth_combination(iterable, r, index):
"Equivalent to list(combinations(iterable, r))[index]"
pool = tuple(iterable)
n = len(pool)
c = math.comb(n, r)
if index < 0:
index += c
if index < 0 or index >= c:
raise IndexError
result = []
while r:
c, n, r = c*r//n, n-1, r-1
while index >= c:
index -= c
c, n = c*(n-r)//n, n-1
result.append(pool[-1-n])
return tuple(result)
.. doctest::
:hide:
@ -1604,3 +1655,17 @@ The following recipes have a more mathematical flavor:
>>> list(triplewise('ABCDEFG'))
[('A', 'B', 'C'), ('B', 'C', 'D'), ('C', 'D', 'E'), ('D', 'E', 'F'), ('E', 'F', 'G')]
>>> population = 'ABCDEFGH'
>>> for r in range(len(population) + 1):
... seq = list(combinations(population, r))
... for i in range(len(seq)):
... assert nth_combination(population, r, i) == seq[i]
... for i in range(-len(seq), 0):
... assert nth_combination(population, r, i) == seq[i]
>>> iterable = 'abcde'
>>> r = 3
>>> combos = list(combinations(iterable, r))
>>> all(nth_combination(iterable, r, i) == comb for i, comb in enumerate(combos))
True

View file

@ -309,7 +309,7 @@ The :mod:`locale` module defines the following exception and functions:
.. function:: getlocale(category=LC_CTYPE)
Returns the current setting for the given locale category as sequence containing
*language code*, *encoding*. *category* may be one of the :const:`LC_\*` values
*language code*, *encoding*. *category* may be one of the :const:`!LC_\*` values
except :const:`LC_ALL`. It defaults to :const:`LC_CTYPE`.
Except for the code ``'C'``, the language code corresponds to :rfc:`1766`.

View file

@ -93,8 +93,8 @@ in :mod:`logging` itself) and defining handlers which are declared either in
:param fname: A filename, or a file-like object, or an instance derived
from :class:`~configparser.RawConfigParser`. If a
``RawConfigParser``-derived instance is passed, it is used as
is. Otherwise, a :class:`~configparser.Configparser` is
:class:`!RawConfigParser`-derived instance is passed, it is used as
is. Otherwise, a :class:`~configparser.ConfigParser` is
instantiated, and the configuration read by it from the
object passed in ``fname``. If that has a :meth:`readline`
method, it is assumed to be a file-like object and read using
@ -103,7 +103,7 @@ in :mod:`logging` itself) and defining handlers which are declared either in
:meth:`~configparser.ConfigParser.read`.
:param defaults: Defaults to be passed to the ConfigParser can be specified
:param defaults: Defaults to be passed to the :class:`!ConfigParser` can be specified
in this argument.
:param disable_existing_loggers: If specified as ``False``, loggers which

View file

@ -13,8 +13,8 @@
This module defines two classes, :class:`Mailbox` and :class:`Message`, for
accessing and manipulating on-disk mailboxes and the messages they contain.
:class:`Mailbox` offers a dictionary-like mapping from keys to messages.
:class:`Message` extends the :mod:`email.message` module's
:class:`!Mailbox` offers a dictionary-like mapping from keys to messages.
:class:`!Message` extends the :mod:`email.message` module's
:class:`~email.message.Message` class with format-specific state and behavior.
Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
@ -27,37 +27,38 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
.. _mailbox-objects:
:class:`Mailbox` objects
------------------------
:class:`!Mailbox` objects
-------------------------
.. class:: Mailbox
A mailbox, which may be inspected and modified.
The :class:`Mailbox` class defines an interface and is not intended to be
The :class:`!Mailbox` class defines an interface and is not intended to be
instantiated. Instead, format-specific subclasses should inherit from
:class:`Mailbox` and your code should instantiate a particular subclass.
:class:`!Mailbox` and your code should instantiate a particular subclass.
The :class:`Mailbox` interface is dictionary-like, with small keys
corresponding to messages. Keys are issued by the :class:`Mailbox` instance
with which they will be used and are only meaningful to that :class:`Mailbox`
The :class:`!Mailbox` interface is dictionary-like, with small keys
corresponding to messages. Keys are issued by the :class:`!Mailbox` instance
with which they will be used and are only meaningful to that :class:`!Mailbox`
instance. A key continues to identify a message even if the corresponding
message is modified, such as by replacing it with another message.
Messages may be added to a :class:`Mailbox` instance using the set-like
Messages may be added to a :class:`!Mailbox` instance using the set-like
method :meth:`add` and removed using a ``del`` statement or the set-like
methods :meth:`remove` and :meth:`discard`.
:class:`Mailbox` interface semantics differ from dictionary semantics in some
:class:`!Mailbox` interface semantics differ from dictionary semantics in some
noteworthy ways. Each time a message is requested, a new representation
(typically a :class:`Message` instance) is generated based upon the current
state of the mailbox. Similarly, when a message is added to a
:class:`Mailbox` instance, the provided message representation's contents are
:class:`!Mailbox` instance, the provided message representation's contents are
copied. In neither case is a reference to the message representation kept by
the :class:`Mailbox` instance.
the :class:`!Mailbox` instance.
The default :class:`Mailbox` iterator iterates over message representations,
not keys as the default dictionary iterator does. Moreover, modification of a
The default :class:`!Mailbox` :term:`iterator` iterates over message
representations, not keys as the default :class:`dictionary <dict>`
iterator does. Moreover, modification of a
mailbox during iteration is safe and well-defined. Messages added to the
mailbox after an iterator is created will not be seen by the
iterator. Messages removed from the mailbox before the iterator yields them
@ -69,14 +70,15 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
Be very cautious when modifying mailboxes that might be simultaneously
changed by some other process. The safest mailbox format to use for such
tasks is Maildir; try to avoid using single-file formats such as mbox for
tasks is :class:`Maildir`; try to avoid using single-file formats such as
:class:`mbox` for
concurrent writing. If you're modifying a mailbox, you *must* lock it by
calling the :meth:`lock` and :meth:`unlock` methods *before* reading any
messages in the file or making any changes by adding or deleting a
message. Failing to lock the mailbox runs the risk of losing messages or
corrupting the entire mailbox.
:class:`Mailbox` instances have the following methods:
:class:`!Mailbox` instances have the following methods:
.. method:: add(message)
@ -127,21 +129,23 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
.. method:: iterkeys()
keys()
Return an iterator over all keys if called as :meth:`iterkeys` or return a
list of keys if called as :meth:`keys`.
Return an :term:`iterator` over all keys
.. method:: keys()
The same as :meth:`iterkeys`, except that a :class:`list` is returned
rather than an :term:`iterator`
.. method:: itervalues()
__iter__()
values()
Return an iterator over representations of all messages if called as
:meth:`itervalues` or :meth:`__iter__` or return a list of such
representations if called as :meth:`values`. The messages are represented
Return an :term:`iterator` over representations of all messages.
The messages are represented
as instances of the appropriate format-specific :class:`Message` subclass
unless a custom message factory was specified when the :class:`Mailbox`
unless a custom message factory was specified when the :class:`!Mailbox`
instance was initialized.
.. note::
@ -150,15 +154,25 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
iterate over keys.
.. method:: iteritems()
items()
.. method:: values()
Return an iterator over (*key*, *message*) pairs, where *key* is a key and
*message* is a message representation, if called as :meth:`iteritems` or
return a list of such pairs if called as :meth:`items`. The messages are
The same as :meth:`itervalues`, except that a :class:`list` is returned
rather than an :term:`iterator`
.. method:: iteritems()
Return an :term:`iterator` over (*key*, *message*) pairs, where *key* is
a key and *message* is a message representation. The messages are
represented as instances of the appropriate format-specific
:class:`Message` subclass unless a custom message factory was specified
when the :class:`Mailbox` instance was initialized.
when the :class:`!Mailbox` instance was initialized.
.. method:: items()
The same as :meth:`iteritems`, except that a :class:`list` of pairs is
returned rather than an :term:`iterator` of pairs.
.. method:: get(key, default=None)
@ -167,9 +181,9 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
Return a representation of the message corresponding to *key*. If no such
message exists, *default* is returned if the method was called as
:meth:`get` and a :exc:`KeyError` exception is raised if the method was
called as :meth:`~object.__getitem__`. The message is represented as an instance
called as :meth:`!__getitem__`. The message is represented as an instance
of the appropriate format-specific :class:`Message` subclass unless a
custom message factory was specified when the :class:`Mailbox` instance
custom message factory was specified when the :class:`!Mailbox` instance
was initialized.
@ -198,21 +212,23 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
.. method:: get_file(key)
Return a file-like representation of the message corresponding to *key*,
Return a :term:`file-like <file-like object>` representation of the
message corresponding to *key*,
or raise a :exc:`KeyError` exception if no such message exists. The
file-like object behaves as if open in binary mode. This file should be
closed once it is no longer needed.
.. versionchanged:: 3.2
The file object really is a binary file; previously it was incorrectly
returned in text mode. Also, the file-like object now supports the
context management protocol: you can use a :keyword:`with` statement to
automatically close it.
The file object really is a :term:`binary file`; previously it was
incorrectly returned in text mode. Also, the :term:`file-like object`
now supports the :term:`context manager` protocol: you can use a
:keyword:`with` statement to automatically close it.
.. note::
Unlike other representations of messages, file-like representations are
not necessarily independent of the :class:`Mailbox` instance that
Unlike other representations of messages,
:term:`file-like <file-like object>` representations are not
necessarily independent of the :class:`!Mailbox` instance that
created them or of the underlying mailbox. More specific documentation
is provided by each subclass.
@ -238,7 +254,7 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
the message. If no such message exists, return *default*. The message is
represented as an instance of the appropriate format-specific
:class:`Message` subclass unless a custom message factory was specified
when the :class:`Mailbox` instance was initialized.
when the :class:`!Mailbox` instance was initialized.
.. method:: popitem()
@ -248,7 +264,7 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
message. If the mailbox is empty, raise a :exc:`KeyError` exception. The
message is represented as an instance of the appropriate format-specific
:class:`Message` subclass unless a custom message factory was specified
when the :class:`Mailbox` instance was initialized.
when the :class:`!Mailbox` instance was initialized.
.. method:: update(arg)
@ -259,7 +275,7 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
*message* as if by using :meth:`__setitem__`. As with :meth:`__setitem__`,
each *key* must already correspond to a message in the mailbox or else a
:exc:`KeyError` exception will be raised, so in general it is incorrect
for *arg* to be a :class:`Mailbox` instance.
for *arg* to be a :class:`!Mailbox` instance.
.. note::
@ -269,7 +285,7 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
.. method:: flush()
Write any pending changes to the filesystem. For some :class:`Mailbox`
subclasses, changes are always written immediately and :meth:`flush` does
subclasses, changes are always written immediately and :meth:`!flush` does
nothing, but you should still make a habit of calling this method.
@ -290,13 +306,13 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
.. method:: close()
Flush the mailbox, unlock it if necessary, and close any open files. For
some :class:`Mailbox` subclasses, this method does nothing.
some :class:`!Mailbox` subclasses, this method does nothing.
.. _mailbox-maildir:
:class:`Maildir`
^^^^^^^^^^^^^^^^
:class:`!Maildir` objects
^^^^^^^^^^^^^^^^^^^^^^^^^
.. class:: Maildir(dirname, factory=None, create=True)
@ -330,11 +346,11 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
Folders of the style introduced by the Courier mail transfer agent are also
supported. Any subdirectory of the main mailbox is considered a folder if
``'.'`` is the first character in its name. Folder names are represented by
:class:`Maildir` without the leading ``'.'``. Each folder is itself a Maildir
:class:`!Maildir` without the leading ``'.'``. Each folder is itself a Maildir
mailbox but should not contain other folders. Instead, a logical nesting is
indicated using ``'.'`` to delimit levels, e.g., "Archived.2005.07".
.. note::
.. attribute:: Maildir.colon
The Maildir specification requires the use of a colon (``':'``) in certain
message file names. However, some operating systems do not permit this
@ -346,9 +362,12 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
import mailbox
mailbox.Maildir.colon = '!'
The :attr:`colon` attribute may also be set on a per-instance basis.
The :attr:`!colon` attribute may also be set on a per-instance basis.
:class:`Maildir` instances have all of the methods of :class:`Mailbox` in
.. versionchanged:: 3.13
:class:`Maildir` now ignores files with a leading dot.
:class:`!Maildir` instances have all of the methods of :class:`Mailbox` in
addition to the following:
@ -359,14 +378,14 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
.. method:: get_folder(folder)
Return a :class:`Maildir` instance representing the folder whose name is
Return a :class:`!Maildir` instance representing the folder whose name is
*folder*. A :exc:`NoSuchMailboxError` exception is raised if the folder
does not exist.
.. method:: add_folder(folder)
Create a folder whose name is *folder* and return a :class:`Maildir`
Create a folder whose name is *folder* and return a :class:`!Maildir`
instance representing it.
@ -383,46 +402,6 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
last 36 hours. The Maildir specification says that mail-reading programs
should do this occasionally.
Some :class:`Mailbox` methods implemented by :class:`Maildir` deserve special
remarks:
.. method:: add(message)
__setitem__(key, message)
update(arg)
.. warning::
These methods generate unique file names based upon the current process
ID. When using multiple threads, undetected name clashes may occur and
cause corruption of the mailbox unless threads are coordinated to avoid
using these methods to manipulate the same mailbox simultaneously.
.. method:: flush()
All changes to Maildir mailboxes are immediately applied, so this method
does nothing.
.. method:: lock()
unlock()
Maildir mailboxes do not support (or require) locking, so these methods do
nothing.
.. method:: close()
:class:`Maildir` instances do not keep any open files and the underlying
mailboxes do not support locking, so this method does nothing.
.. method:: get_file(key)
Depending upon the host platform, it may not be possible to modify or
remove the underlying message while the returned file remains open.
.. method:: get_flags(key)
@ -525,6 +504,46 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
.. versionadded:: 3.13
Some :class:`Mailbox` methods implemented by :class:`!Maildir` deserve special
remarks:
.. method:: add(message)
__setitem__(key, message)
update(arg)
.. warning::
These methods generate unique file names based upon the current process
ID. When using multiple threads, undetected name clashes may occur and
cause corruption of the mailbox unless threads are coordinated to avoid
using these methods to manipulate the same mailbox simultaneously.
.. method:: flush()
All changes to Maildir mailboxes are immediately applied, so this method
does nothing.
.. method:: lock()
unlock()
Maildir mailboxes do not support (or require) locking, so these methods do
nothing.
.. method:: close()
:class:`!Maildir` instances do not keep any open files and the underlying
mailboxes do not support locking, so this method does nothing.
.. method:: get_file(key)
Depending upon the host platform, it may not be possible to modify or
remove the underlying message while the returned file remains open.
.. seealso::
@ -539,8 +558,8 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
.. _mailbox-mbox:
:class:`mbox`
^^^^^^^^^^^^^
:class:`!mbox` objects
^^^^^^^^^^^^^^^^^^^^^^
.. class:: mbox(path, factory=None, create=True)
@ -557,22 +576,22 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
each message indicated by a line whose first five characters are "From ".
Several variations of the mbox format exist to address perceived shortcomings in
the original. In the interest of compatibility, :class:`mbox` implements the
the original. In the interest of compatibility, :class:`!mbox` implements the
original format, which is sometimes referred to as :dfn:`mboxo`. This means that
the :mailheader:`Content-Length` header, if present, is ignored and that any
occurrences of "From " at the beginning of a line in a message body are
transformed to ">From " when storing the message, although occurrences of ">From
" are not transformed to "From " when reading the message.
Some :class:`Mailbox` methods implemented by :class:`mbox` deserve special
Some :class:`Mailbox` methods implemented by :class:`!mbox` deserve special
remarks:
.. method:: get_file(key)
Using the file after calling :meth:`flush` or :meth:`close` on the
:class:`mbox` instance may yield unpredictable results or raise an
exception.
Using the file after calling :meth:`~Mailbox.flush` or
:meth:`~Mailbox.close` on the :class:`!mbox` instance may yield
unpredictable results or raise an exception.
.. method:: lock()
@ -596,8 +615,8 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
.. _mailbox-mh:
:class:`MH`
^^^^^^^^^^^
:class:`!MH` objects
^^^^^^^^^^^^^^^^^^^^
.. class:: MH(path, factory=None, create=True)
@ -617,14 +636,18 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
messages without moving them to sub-folders. Sequences are defined in a file
called :file:`.mh_sequences` in each folder.
The :class:`MH` class manipulates MH mailboxes, but it does not attempt to
The :class:`!MH` class manipulates MH mailboxes, but it does not attempt to
emulate all of :program:`mh`'s behaviors. In particular, it does not modify
and is not affected by the :file:`context` or :file:`.mh_profile` files that
are used by :program:`mh` to store its state and configuration.
:class:`MH` instances have all of the methods of :class:`Mailbox` in addition
:class:`!MH` instances have all of the methods of :class:`Mailbox` in addition
to the following:
.. versionchanged:: 3.13
Supported folders that don't contain a :file:`.mh_sequences` file.
.. method:: list_folders()
@ -633,14 +656,14 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
.. method:: get_folder(folder)
Return an :class:`MH` instance representing the folder whose name is
Return an :class:`!MH` instance representing the folder whose name is
*folder*. A :exc:`NoSuchMailboxError` exception is raised if the folder
does not exist.
.. method:: add_folder(folder)
Create a folder whose name is *folder* and return an :class:`MH` instance
Create a folder whose name is *folder* and return an :class:`!MH` instance
representing it.
@ -674,7 +697,7 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
Already-issued keys are invalidated by this operation and should not be
subsequently used.
Some :class:`Mailbox` methods implemented by :class:`MH` deserve special
Some :class:`Mailbox` methods implemented by :class:`!MH` deserve special
remarks:
@ -710,7 +733,7 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
.. method:: close()
:class:`MH` instances do not keep any open files, so this method is
:class:`!MH` instances do not keep any open files, so this method is
equivalent to :meth:`unlock`.
@ -726,8 +749,8 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
.. _mailbox-babyl:
:class:`Babyl`
^^^^^^^^^^^^^^
:class:`!Babyl` objects
^^^^^^^^^^^^^^^^^^^^^^^
.. class:: Babyl(path, factory=None, create=True)
@ -754,7 +777,7 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
message, and a list of all user-defined labels found in the mailbox is kept
in the Babyl options section.
:class:`Babyl` instances have all of the methods of :class:`Mailbox` in
:class:`!Babyl` instances have all of the methods of :class:`Mailbox` in
addition to the following:
@ -769,7 +792,7 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
options section, but the Babyl section is updated whenever the mailbox
is modified.
Some :class:`Mailbox` methods implemented by :class:`Babyl` deserve special
Some :class:`Mailbox` methods implemented by :class:`!Babyl` deserve special
remarks:
@ -802,8 +825,8 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
.. _mailbox-mmdf:
:class:`MMDF`
^^^^^^^^^^^^^
:class:`!MMDF` objects
^^^^^^^^^^^^^^^^^^^^^^
.. class:: MMDF(path, factory=None, create=True)
@ -824,15 +847,15 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
">From " when storing messages because the extra message separator lines
prevent mistaking such occurrences for the starts of subsequent messages.
Some :class:`Mailbox` methods implemented by :class:`MMDF` deserve special
Some :class:`Mailbox` methods implemented by :class:`!MMDF` deserve special
remarks:
.. method:: get_file(key)
Using the file after calling :meth:`flush` or :meth:`close` on the
:class:`MMDF` instance may yield unpredictable results or raise an
exception.
Using the file after calling :meth:`~Mailbox.flush` or
:meth:`~Mailbox.close` on the :class:`!MMDF` instance may yield
unpredictable results or raise an exception.
.. method:: lock()
@ -854,20 +877,20 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
.. _mailbox-message-objects:
:class:`Message` objects
------------------------
:class:`!Message` objects
-------------------------
.. class:: Message(message=None)
A subclass of the :mod:`email.message` module's
:class:`~email.message.Message`. Subclasses of :class:`mailbox.Message` add
:class:`~email.message.Message`. Subclasses of :class:`!mailbox.Message` add
mailbox-format-specific state and behavior.
If *message* is omitted, the new instance is created in a default, empty state.
If *message* is an :class:`email.message.Message` instance, its contents are
copied; furthermore, any format-specific information is converted insofar as
possible if *message* is a :class:`Message` instance. If *message* is a string,
possible if *message* is a :class:`!Message` instance. If *message* is a string,
a byte string,
or a file, it should contain an :rfc:`2822`\ -compliant message, which is read
and parsed. Files should be open in binary mode, but text mode files
@ -882,18 +905,18 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
such as whether a message has been read by the user or marked as important is
retained, because it applies to the message itself.
There is no requirement that :class:`Message` instances be used to represent
There is no requirement that :class:`!Message` instances be used to represent
messages retrieved using :class:`Mailbox` instances. In some situations, the
time and memory required to generate :class:`Message` representations might
not be acceptable. For such situations, :class:`Mailbox` instances also
time and memory required to generate :class:`!Message` representations might
not be acceptable. For such situations, :class:`!Mailbox` instances also
offer string and file-like representations, and a custom message factory may
be specified when a :class:`Mailbox` instance is initialized.
be specified when a :class:`!Mailbox` instance is initialized.
.. _mailbox-maildirmessage:
:class:`MaildirMessage`
^^^^^^^^^^^^^^^^^^^^^^^
:class:`!MaildirMessage` objects
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. class:: MaildirMessage(message=None)
@ -928,7 +951,7 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
| T | Trashed | Marked for subsequent deletion |
+------+---------+--------------------------------+
:class:`MaildirMessage` instances offer the following methods:
:class:`!MaildirMessage` instances offer the following methods:
.. method:: get_subdir()
@ -1005,7 +1028,7 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
Set "info" to *info*, which should be a string.
When a :class:`MaildirMessage` instance is created based upon an
When a :class:`!MaildirMessage` instance is created based upon an
:class:`mboxMessage` or :class:`MMDFMessage` instance, the :mailheader:`Status`
and :mailheader:`X-Status` headers are omitted and the following conversions
take place:
@ -1025,7 +1048,7 @@ take place:
| T flag | D flag |
+--------------------+----------------------------------------------+
When a :class:`MaildirMessage` instance is created based upon an
When a :class:`!MaildirMessage` instance is created based upon an
:class:`MHMessage` instance, the following conversions take place:
+-------------------------------+--------------------------+
@ -1040,7 +1063,7 @@ When a :class:`MaildirMessage` instance is created based upon an
| R flag | "replied" sequence |
+-------------------------------+--------------------------+
When a :class:`MaildirMessage` instance is created based upon a
When a :class:`!MaildirMessage` instance is created based upon a
:class:`BabylMessage` instance, the following conversions take place:
+-------------------------------+-------------------------------+
@ -1060,8 +1083,8 @@ When a :class:`MaildirMessage` instance is created based upon a
.. _mailbox-mboxmessage:
:class:`mboxMessage`
^^^^^^^^^^^^^^^^^^^^
:class:`!mboxMessage` objects
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. class:: mboxMessage(message=None)
@ -1097,7 +1120,7 @@ When a :class:`MaildirMessage` instance is created based upon a
"D", "F", and "A" flags are stored in the :mailheader:`X-Status` header. The
flags and headers typically appear in the order mentioned.
:class:`mboxMessage` instances offer the following methods:
:class:`!mboxMessage` instances offer the following methods:
.. method:: get_from()
@ -1145,7 +1168,7 @@ When a :class:`MaildirMessage` instance is created based upon a
remove more than one flag at a time, *flag* maybe a string of more than
one character.
When an :class:`mboxMessage` instance is created based upon a
When an :class:`!mboxMessage` instance is created based upon a
:class:`MaildirMessage` instance, a "From " line is generated based upon the
:class:`MaildirMessage` instance's delivery date, and the following conversions
take place:
@ -1164,7 +1187,7 @@ take place:
| A flag | R flag |
+-----------------+-------------------------------+
When an :class:`mboxMessage` instance is created based upon an
When an :class:`!mboxMessage` instance is created based upon an
:class:`MHMessage` instance, the following conversions take place:
+-------------------+--------------------------+
@ -1179,7 +1202,7 @@ When an :class:`mboxMessage` instance is created based upon an
| A flag | "replied" sequence |
+-------------------+--------------------------+
When an :class:`mboxMessage` instance is created based upon a
When an :class:`!mboxMessage` instance is created based upon a
:class:`BabylMessage` instance, the following conversions take place:
+-------------------+-----------------------------+
@ -1194,7 +1217,8 @@ When an :class:`mboxMessage` instance is created based upon a
| A flag | "answered" label |
+-------------------+-----------------------------+
When a :class:`Message` instance is created based upon an :class:`MMDFMessage`
When a :class:`!mboxMessage` instance is created based upon an
:class:`MMDFMessage`
instance, the "From " line is copied and all flags directly correspond:
+-----------------+----------------------------+
@ -1214,8 +1238,8 @@ instance, the "From " line is copied and all flags directly correspond:
.. _mailbox-mhmessage:
:class:`MHMessage`
^^^^^^^^^^^^^^^^^^
:class:`!MHMessage` objects
^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. class:: MHMessage(message=None)
@ -1239,7 +1263,7 @@ instance, the "From " line is copied and all flags directly correspond:
| flagged | Marked as important |
+----------+------------------------------------------+
:class:`MHMessage` instances offer the following methods:
:class:`!MHMessage` instances offer the following methods:
.. method:: get_sequences()
@ -1261,7 +1285,7 @@ instance, the "From " line is copied and all flags directly correspond:
Remove *sequence* from the list of sequences that include this message.
When an :class:`MHMessage` instance is created based upon a
When an :class:`!MHMessage` instance is created based upon a
:class:`MaildirMessage` instance, the following conversions take place:
+--------------------+-------------------------------+
@ -1274,7 +1298,7 @@ When an :class:`MHMessage` instance is created based upon a
| "flagged" sequence | F flag |
+--------------------+-------------------------------+
When an :class:`MHMessage` instance is created based upon an
When an :class:`!MHMessage` instance is created based upon an
:class:`mboxMessage` or :class:`MMDFMessage` instance, the :mailheader:`Status`
and :mailheader:`X-Status` headers are omitted and the following conversions
take place:
@ -1290,7 +1314,7 @@ take place:
| "flagged" sequence | F flag |
+--------------------+----------------------------------------------+
When an :class:`MHMessage` instance is created based upon a
When an :class:`!MHMessage` instance is created based upon a
:class:`BabylMessage` instance, the following conversions take place:
+--------------------+-----------------------------+
@ -1304,8 +1328,8 @@ When an :class:`MHMessage` instance is created based upon a
.. _mailbox-babylmessage:
:class:`BabylMessage`
^^^^^^^^^^^^^^^^^^^^^
:class:`!BabylMessage` objects
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. class:: BabylMessage(message=None)
@ -1334,11 +1358,11 @@ When an :class:`MHMessage` instance is created based upon a
| resent | Resent |
+-----------+------------------------------------------+
By default, Rmail displays only visible headers. The :class:`BabylMessage`
By default, Rmail displays only visible headers. The :class:`!BabylMessage`
class, though, uses the original headers because they are more
complete. Visible headers may be accessed explicitly if desired.
:class:`BabylMessage` instances offer the following methods:
:class:`!BabylMessage` instances offer the following methods:
.. method:: get_labels()
@ -1377,7 +1401,7 @@ When an :class:`MHMessage` instance is created based upon a
.. method:: update_visible()
When a :class:`BabylMessage` instance's original headers are modified, the
When a :class:`!BabylMessage` instance's original headers are modified, the
visible headers are not automatically modified to correspond. This method
updates the visible headers as follows: each visible header with a
corresponding original header is set to the value of the original header,
@ -1387,7 +1411,7 @@ When an :class:`MHMessage` instance is created based upon a
present in the original headers but not the visible headers are added to
the visible headers.
When a :class:`BabylMessage` instance is created based upon a
When a :class:`!BabylMessage` instance is created based upon a
:class:`MaildirMessage` instance, the following conversions take place:
+-------------------+-------------------------------+
@ -1402,7 +1426,7 @@ When a :class:`BabylMessage` instance is created based upon a
| "forwarded" label | P flag |
+-------------------+-------------------------------+
When a :class:`BabylMessage` instance is created based upon an
When a :class:`!BabylMessage` instance is created based upon an
:class:`mboxMessage` or :class:`MMDFMessage` instance, the :mailheader:`Status`
and :mailheader:`X-Status` headers are omitted and the following conversions
take place:
@ -1418,7 +1442,7 @@ take place:
| "answered" label | A flag |
+------------------+----------------------------------------------+
When a :class:`BabylMessage` instance is created based upon an
When a :class:`!BabylMessage` instance is created based upon an
:class:`MHMessage` instance, the following conversions take place:
+------------------+--------------------------+
@ -1432,8 +1456,8 @@ When a :class:`BabylMessage` instance is created based upon an
.. _mailbox-mmdfmessage:
:class:`MMDFMessage`
^^^^^^^^^^^^^^^^^^^^
:class:`!MMDFMessage` objects
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. class:: MMDFMessage(message=None)
@ -1467,7 +1491,7 @@ When a :class:`BabylMessage` instance is created based upon an
"D", "F", and "A" flags are stored in the :mailheader:`X-Status` header. The
flags and headers typically appear in the order mentioned.
:class:`MMDFMessage` instances offer the following methods, which are
:class:`!MMDFMessage` instances offer the following methods, which are
identical to those offered by :class:`mboxMessage`:
@ -1516,7 +1540,7 @@ When a :class:`BabylMessage` instance is created based upon an
remove more than one flag at a time, *flag* maybe a string of more than
one character.
When an :class:`MMDFMessage` instance is created based upon a
When an :class:`!MMDFMessage` instance is created based upon a
:class:`MaildirMessage` instance, a "From " line is generated based upon the
:class:`MaildirMessage` instance's delivery date, and the following conversions
take place:
@ -1535,7 +1559,7 @@ take place:
| A flag | R flag |
+-----------------+-------------------------------+
When an :class:`MMDFMessage` instance is created based upon an
When an :class:`!MMDFMessage` instance is created based upon an
:class:`MHMessage` instance, the following conversions take place:
+-------------------+--------------------------+
@ -1550,7 +1574,7 @@ When an :class:`MMDFMessage` instance is created based upon an
| A flag | "replied" sequence |
+-------------------+--------------------------+
When an :class:`MMDFMessage` instance is created based upon a
When an :class:`!MMDFMessage` instance is created based upon a
:class:`BabylMessage` instance, the following conversions take place:
+-------------------+-----------------------------+
@ -1565,7 +1589,7 @@ When an :class:`MMDFMessage` instance is created based upon a
| A flag | "answered" label |
+-------------------+-----------------------------+
When an :class:`MMDFMessage` instance is created based upon an
When an :class:`!MMDFMessage` instance is created based upon an
:class:`mboxMessage` instance, the "From " line is copied and all flags directly
correspond:
@ -1587,7 +1611,7 @@ correspond:
Exceptions
----------
The following exception classes are defined in the :mod:`mailbox` module:
The following exception classes are defined in the :mod:`!mailbox` module:
.. exception:: Error()

View file

@ -36,7 +36,7 @@ or other communications requiring the serialization/deserialization and
copying of data.
.. class:: SharedMemory(name=None, create=False, size=0)
.. class:: SharedMemory(name=None, create=False, size=0, *, track=True)
Creates a new shared memory block or attaches to an existing shared
memory block. Each shared memory block is assigned a unique name.
@ -64,26 +64,45 @@ copying of data.
memory block may be larger or equal to the size requested. When attaching
to an existing shared memory block, the ``size`` parameter is ignored.
*track*, when enabled, registers the shared memory block with a resource
tracker process on platforms where the OS does not do this automatically.
The resource tracker ensures proper cleanup of the shared memory even
if all other processes with access to the memory exit without doing so.
Python processes created from a common ancestor using :mod:`multiprocessing`
facilities share a single resource tracker process, and the lifetime of
shared memory segments is handled automatically among these processes.
Python processes created in any other way will receive their own
resource tracker when accessing shared memory with *track* enabled.
This will cause the shared memory to be deleted by the resource tracker
of the first process that terminates.
To avoid this issue, users of :mod:`subprocess` or standalone Python
processes should set *track* to ``False`` when there is already another
process in place that does the bookkeeping.
*track* is ignored on Windows, which has its own tracking and
automatically deletes shared memory when all handles to it have been closed.
.. versionchanged:: 3.13 Added *track* parameter.
.. method:: close()
Closes access to the shared memory from this instance. In order to
ensure proper cleanup of resources, all instances should call
``close()`` once the instance is no longer needed. Note that calling
``close()`` does not cause the shared memory block itself to be
destroyed.
Closes the file descriptor/handle to the shared memory from this
instance. :meth:`close()` should be called once access to the shared
memory block from this instance is no longer needed. Depending
on operating system, the underlying memory may or may not be freed
even if all handles to it have been closed. To ensure proper cleanup,
use the :meth:`unlink()` method.
.. method:: unlink()
Requests that the underlying shared memory block be destroyed. In
order to ensure proper cleanup of resources, ``unlink()`` should be
called once (and only once) across all processes which have need
for the shared memory block. After requesting its destruction, a
shared memory block may or may not be immediately destroyed and
this behavior may differ across platforms. Attempts to access data
inside the shared memory block after ``unlink()`` has been called may
result in memory access errors. Note: the last process relinquishing
its hold on a shared memory block may call ``unlink()`` and
:meth:`close()` in either order.
Deletes the underlying shared memory block. This should be called only
once per shared memory block regardless of the number of handles to it,
even in other processes.
:meth:`unlink()` and :meth:`close()` can be called in any order, but
trying to access data inside a shared memory block after :meth:`unlink()`
may result in memory access errors, depending on platform.
This method has no effect on Windows, where the only way to delete a
shared memory block is to close all handles.
.. attribute:: buf

View file

@ -8,7 +8,7 @@
--------------
The :mod:`numbers` module (:pep:`3141`) defines a hierarchy of numeric
The :mod:`!numbers` module (:pep:`3141`) defines a hierarchy of numeric
:term:`abstract base classes <abstract base class>` which progressively define
more operations. None of the types defined in this module are intended to be instantiated.
@ -45,7 +45,7 @@ The numeric tower
.. class:: Real
To :class:`Complex`, :class:`Real` adds the operations that work on real
To :class:`Complex`, :class:`!Real` adds the operations that work on real
numbers.
In short, those are: a conversion to :class:`float`, :func:`math.trunc`,
@ -126,7 +126,8 @@ We want to implement the arithmetic operations so that mixed-mode
operations either call an implementation whose author knew about the
types of both arguments, or convert both to the nearest built in type
and do the operation there. For subtypes of :class:`Integral`, this
means that :meth:`__add__` and :meth:`__radd__` should be defined as::
means that :meth:`~object.__add__` and :meth:`~object.__radd__` should be
defined as::
class MyIntegral(Integral):
@ -160,15 +161,15 @@ refer to ``MyIntegral`` and ``OtherTypeIKnowAbout`` as
of :class:`Complex` (``a : A <: Complex``), and ``b : B <:
Complex``. I'll consider ``a + b``:
1. If ``A`` defines an :meth:`__add__` which accepts ``b``, all is
1. If ``A`` defines an :meth:`~object.__add__` which accepts ``b``, all is
well.
2. If ``A`` falls back to the boilerplate code, and it were to
return a value from :meth:`__add__`, we'd miss the possibility
that ``B`` defines a more intelligent :meth:`__radd__`, so the
return a value from :meth:`~object.__add__`, we'd miss the possibility
that ``B`` defines a more intelligent :meth:`~object.__radd__`, so the
boilerplate should return :const:`NotImplemented` from
:meth:`__add__`. (Or ``A`` may not implement :meth:`__add__` at
:meth:`!__add__`. (Or ``A`` may not implement :meth:`!__add__` at
all.)
3. Then ``B``'s :meth:`__radd__` gets a chance. If it accepts
3. Then ``B``'s :meth:`~object.__radd__` gets a chance. If it accepts
``a``, all is well.
4. If it falls back to the boilerplate, there are no more possible
methods to try, so this is where the default implementation
@ -180,7 +181,7 @@ Complex``. I'll consider ``a + b``:
If ``A <: Complex`` and ``B <: Real`` without sharing any other knowledge,
then the appropriate shared operation is the one involving the built
in :class:`complex`, and both :meth:`__radd__` s land there, so ``a+b
in :class:`complex`, and both :meth:`~object.__radd__` s land there, so ``a+b
== b+a``.
Because most of the operations on any given type will be very similar,

View file

@ -1001,11 +1001,14 @@ as internal buffering of data.
.. audit-event:: os.chmod path,mode,dir_fd os.fchmod
.. availability:: Unix.
.. availability:: Unix, Windows.
The function is limited on Emscripten and WASI, see
:ref:`wasm-availability` for more information.
.. versionchanged:: 3.13
Added support on Windows.
.. function:: fchown(fd, uid, gid)
@ -2062,6 +2065,7 @@ features:
Although Windows supports :func:`chmod`, you can only set the file's
read-only flag with it (via the ``stat.S_IWRITE`` and ``stat.S_IREAD``
constants or a corresponding integer value). All other bits are ignored.
The default value of *follow_symlinks* is ``False`` on Windows.
The function is limited on Emscripten and WASI, see
:ref:`wasm-availability` for more information.
@ -2075,6 +2079,10 @@ features:
.. versionchanged:: 3.6
Accepts a :term:`path-like object`.
.. versionchanged:: 3.13
Added support for a file descriptor and the *follow_symlinks* argument
on Windows.
.. function:: chown(path, uid, gid, *, dir_fd=None, follow_symlinks=True)
@ -2160,13 +2168,19 @@ features:
for possible values of *mode*. As of Python 3.3, this is equivalent to
``os.chmod(path, mode, follow_symlinks=False)``.
``lchmod()`` is not part of POSIX, but Unix implementations may have it if
changing the mode of symbolic links is supported.
.. audit-event:: os.chmod path,mode,dir_fd os.lchmod
.. availability:: Unix.
.. availability:: Unix, Windows, not Linux, FreeBSD >= 1.3, NetBSD >= 1.3, not OpenBSD
.. versionchanged:: 3.6
Accepts a :term:`path-like object`.
.. versionchanged:: 3.13
Added support on Windows.
.. function:: lchown(path, uid, gid)
Change the owner and group id of *path* to the numeric *uid* and *gid*. This
@ -4170,7 +4184,7 @@ to be ignored.
The "l" and "v" variants of the :func:`exec\* <execl>` functions differ in how
command-line arguments are passed. The "l" variants are perhaps the easiest
to work with if the number of parameters is fixed when the code is written; the
individual parameters simply become additional parameters to the :func:`execl\*`
individual parameters simply become additional parameters to the :func:`!execl\*`
functions. The "v" variants are good when the number of parameters is
variable, with the arguments being passed in a list or tuple as the *args*
parameter. In either case, the arguments to the child process should start with
@ -4373,6 +4387,11 @@ written in Python, such as a mail server's external command delivery program.
If you use TLS sockets in an application calling ``fork()``, see
the warning in the :mod:`ssl` documentation.
.. warning::
On macOS the use of this function is unsafe when mixed with using
higher-level system APIs, and that includes using :mod:`urllib.request`.
.. versionchanged:: 3.8
Calling ``fork()`` in a subinterpreter is no longer supported
(:exc:`RuntimeError` is raised).
@ -4412,6 +4431,11 @@ written in Python, such as a mail server's external command delivery program.
.. audit-event:: os.forkpty "" os.forkpty
.. warning::
On macOS the use of this function is unsafe when mixed with using
higher-level system APIs, and that includes using :mod:`urllib.request`.
.. versionchanged:: 3.12
If Python is able to detect that your process has multiple
threads, this now raises a :exc:`DeprecationWarning`. See the
@ -4550,7 +4574,8 @@ written in Python, such as a mail server's external command delivery program.
Most users should use :func:`subprocess.run` instead of :func:`posix_spawn`.
The positional-only arguments *path*, *args*, and *env* are similar to
:func:`execve`.
:func:`execve`. *env* is allowed to be ``None``, in which case current
process' environment is used.
The *path* parameter is the path to the executable file. The *path* should
contain a directory. Use :func:`posix_spawnp` to pass an executable file
@ -4580,10 +4605,17 @@ written in Python, such as a mail server's external command delivery program.
Performs ``os.dup2(fd, new_fd)``.
.. data:: POSIX_SPAWN_CLOSEFROM
(``os.POSIX_SPAWN_CLOSEFROM``, *fd*)
Performs ``os.closerange(fd, INF)``.
These tuples correspond to the C library
:c:func:`!posix_spawn_file_actions_addopen`,
:c:func:`!posix_spawn_file_actions_addclose`, and
:c:func:`!posix_spawn_file_actions_adddup2` API calls used to prepare
:c:func:`!posix_spawn_file_actions_addclose`,
:c:func:`!posix_spawn_file_actions_adddup2`, and
:c:func:`!posix_spawn_file_actions_addclosefrom_np` API calls used to prepare
for the :c:func:`!posix_spawn` call itself.
The *setpgroup* argument will set the process group of the child to the value
@ -4625,6 +4657,13 @@ written in Python, such as a mail server's external command delivery program.
.. versionadded:: 3.8
.. versionchanged:: 3.13
*env* parameter accepts ``None``.
.. versionchanged:: 3.13
``os.POSIX_SPAWN_CLOSEFROM`` is available on platforms where
:c:func:`!posix_spawn_file_actions_addclosefrom_np` exists.
.. availability:: Unix, not Emscripten, not WASI.
.. function:: posix_spawnp(path, argv, env, *, file_actions=None, \
@ -4708,7 +4747,7 @@ written in Python, such as a mail server's external command delivery program.
command-line arguments are passed. The "l" variants are perhaps the easiest
to work with if the number of parameters is fixed when the code is written; the
individual parameters simply become additional parameters to the
:func:`spawnl\*` functions. The "v" variants are good when the number of
:func:`!spawnl\*` functions. The "v" variants are good when the number of
parameters is variable, with the arguments being passed in a list or tuple as
the *args* parameter. In either case, the arguments to the child process must
start with the name of the command being run.
@ -4758,7 +4797,7 @@ written in Python, such as a mail server's external command delivery program.
P_NOWAITO
Possible values for the *mode* parameter to the :func:`spawn\* <spawnl>` family of
functions. If either of these values is given, the :func:`spawn\*` functions
functions. If either of these values is given, the :func:`spawn\* <spawnl>` functions
will return as soon as the new process has been created, with the process id as
the return value.
@ -4768,7 +4807,7 @@ written in Python, such as a mail server's external command delivery program.
.. data:: P_WAIT
Possible value for the *mode* parameter to the :func:`spawn\* <spawnl>` family of
functions. If this is given as *mode*, the :func:`spawn\*` functions will not
functions. If this is given as *mode*, the :func:`spawn\* <spawnl>` functions will not
return until the new process has run to completion and will return the exit code
of the process the run is successful, or ``-signal`` if a signal kills the
process.
@ -4949,6 +4988,9 @@ written in Python, such as a mail server's external command delivery program.
.. versionadded:: 3.3
.. versionchanged:: 3.13
This function is now available on macOS as well.
.. function:: waitpid(pid, options, /)

View file

@ -306,7 +306,7 @@ Pure paths provide the following methods and properties:
.. attribute:: PurePath.pathmod
The implementation of the :mod:`os.path` module used for low-level path
operations: either ``posixpath`` or ``ntpath``.
operations: either :mod:`posixpath` or :mod:`ntpath`.
.. versionadded:: 3.13
@ -595,6 +595,9 @@ Pure paths provide the following methods and properties:
>>> PurePath('a/b.py').match(pattern)
True
.. versionchanged:: 3.12
Accepts an object implementing the :class:`os.PathLike` interface.
As with other methods, case-sensitivity follows platform defaults::
>>> PurePosixPath('b.py').match('*.PY')
@ -1017,15 +1020,21 @@ call fails (for example because the path doesn't exist).
future Python release, patterns with this ending will match both files
and directories. Add a trailing slash to match only directories.
.. method:: Path.group()
.. method:: Path.group(*, follow_symlinks=True)
Return the name of the group owning the file. :exc:`KeyError` is raised
Return the name of the group owning the file. :exc:`KeyError` is raised
if the file's gid isn't found in the system database.
This method normally follows symlinks; to get the group of the symlink, add
the argument ``follow_symlinks=False``.
.. versionchanged:: 3.13
Raises :exc:`UnsupportedOperation` if the :mod:`grp` module is not
available. In previous versions, :exc:`NotImplementedError` was raised.
.. versionchanged:: 3.13
The *follow_symlinks* parameter was added.
.. method:: Path.is_dir(*, follow_symlinks=True)
@ -1291,15 +1300,21 @@ call fails (for example because the path doesn't exist).
'#!/usr/bin/env python3\n'
.. method:: Path.owner()
.. method:: Path.owner(*, follow_symlinks=True)
Return the name of the user owning the file. :exc:`KeyError` is raised
Return the name of the user owning the file. :exc:`KeyError` is raised
if the file's uid isn't found in the system database.
This method normally follows symlinks; to get the owner of the symlink, add
the argument ``follow_symlinks=False``.
.. versionchanged:: 3.13
Raises :exc:`UnsupportedOperation` if the :mod:`pwd` module is not
available. In previous versions, :exc:`NotImplementedError` was raised.
.. versionchanged:: 3.13
The *follow_symlinks* parameter was added.
.. method:: Path.read_bytes()

View file

@ -570,10 +570,27 @@ can be overridden by the local file.
Start an interactive interpreter (using the :mod:`code` module) whose global
namespace contains all the (global and local) names found in the current
scope.
scope. Use ``exit()`` or ``quit()`` to exit the interpreter and return to
the debugger.
.. note::
Because interact creates a new global namespace with the current global
and local namespace for execution, assignment to variables will not
affect the original namespaces.
However, modification to the mutable objects will be reflected in the
original namespaces.
.. versionadded:: 3.2
.. versionadded:: 3.13
``exit()`` and ``quit()`` can be used to exit :pdbcmd:`interact`
command.
.. versionchanged:: 3.13
:pdbcmd:`interact` directs its output to the debugger's
output channel rather than :data:`sys.stderr`.
.. _debugger-aliases:
.. pdbcommand:: alias [name [command]]

View file

@ -27,7 +27,7 @@ top level object is a dictionary.
To write out and to parse a plist file, use the :func:`dump` and
:func:`load` functions.
To work with plist data in bytes objects, use :func:`dumps`
To work with plist data in bytes or string objects, use :func:`dumps`
and :func:`loads`.
Values can be strings, integers, floats, booleans, tuples, lists, dictionaries
@ -52,7 +52,7 @@ or :class:`datetime.datetime` objects.
This module defines the following functions:
.. function:: load(fp, *, fmt=None, dict_type=dict)
.. function:: load(fp, *, fmt=None, dict_type=dict, aware_datetime=False)
Read a plist file. *fp* should be a readable and binary file object.
Return the unpacked root object (which usually is a
@ -69,6 +69,10 @@ This module defines the following functions:
The *dict_type* is the type used for dictionaries that are read from the
plist file.
When *aware_datetime* is true, fields with type ``datetime.datetime`` will
be created as :ref:`aware object <datetime-naive-aware>`, with
:attr:`!tzinfo` as :attr:`datetime.UTC`.
XML data for the :data:`FMT_XML` format is parsed using the Expat parser
from :mod:`xml.parsers.expat` -- see its documentation for possible
exceptions on ill-formed XML. Unknown elements will simply be ignored
@ -79,16 +83,21 @@ This module defines the following functions:
.. versionadded:: 3.4
.. versionchanged:: 3.13
The keyword-only parameter *aware_datetime* has been added.
.. function:: loads(data, *, fmt=None, dict_type=dict)
Load a plist from a bytes object. See :func:`load` for an explanation of
the keyword arguments.
.. function:: loads(data, *, fmt=None, dict_type=dict, aware_datetime=False)
Load a plist from a bytes or string object. See :func:`load` for an
explanation of the keyword arguments.
.. versionadded:: 3.4
.. versionchanged:: 3.13
*data* can be a string when *fmt* equals :data:`FMT_XML`.
.. function:: dump(value, fp, *, fmt=FMT_XML, sort_keys=True, skipkeys=False)
.. function:: dump(value, fp, *, fmt=FMT_XML, sort_keys=True, skipkeys=False, aware_datetime=False)
Write *value* to a plist file. *Fp* should be a writable, binary
file object.
@ -107,6 +116,10 @@ This module defines the following functions:
When *skipkeys* is false (the default) the function raises :exc:`TypeError`
when a key of a dictionary is not a string, otherwise such keys are skipped.
When *aware_datetime* is true and any field with type ``datetime.datetime``
is set as a :ref:`aware object <datetime-naive-aware>`, it will convert to
UTC timezone before writing it.
A :exc:`TypeError` will be raised if the object is of an unsupported type or
a container that contains objects of unsupported types.
@ -115,8 +128,11 @@ This module defines the following functions:
.. versionadded:: 3.4
.. versionchanged:: 3.13
The keyword-only parameter *aware_datetime* has been added.
.. function:: dumps(value, *, fmt=FMT_XML, sort_keys=True, skipkeys=False)
.. function:: dumps(value, *, fmt=FMT_XML, sort_keys=True, skipkeys=False, aware_datetime=False)
Return *value* as a plist-formatted bytes object. See
the documentation for :func:`dump` for an explanation of the keyword

View file

@ -33,6 +33,9 @@ The :mod:`pty` module defines the following functions:
file descriptor connected to the child's controlling terminal (and also to the
child's standard input and output).
.. warning:: On macOS the use of this function is unsafe when mixed with using
higher-level system APIs, and that includes using :mod:`urllib.request`.
.. function:: openpty()

View file

@ -58,106 +58,115 @@ of these classes.
Function Objects
----------------
Class :class:`Function` instances describe functions defined by def
statements. They have the following attributes:
.. class:: Function
Class :class:`!Function` instances describe functions defined by def
statements. They have the following attributes:
.. attribute:: Function.file
.. attribute:: file
Name of the file in which the function is defined.
Name of the file in which the function is defined.
.. attribute:: Function.module
.. attribute:: module
The name of the module defining the function described.
The name of the module defining the function described.
.. attribute:: Function.name
.. attribute:: name
The name of the function.
The name of the function.
.. attribute:: Function.lineno
.. attribute:: lineno
The line number in the file where the definition starts.
The line number in the file where the definition starts.
.. attribute:: Function.parent
.. attribute:: parent
For top-level functions, None. For nested functions, the parent.
For top-level functions, ``None``. For nested functions, the parent.
.. versionadded:: 3.7
.. versionadded:: 3.7
.. attribute:: Function.children
.. attribute:: children
A dictionary mapping names to descriptors for nested functions and
classes.
A :class:`dictionary <dict>` mapping names to descriptors for nested functions and
classes.
.. versionadded:: 3.7
.. versionadded:: 3.7
.. attribute:: Function.is_async
.. attribute:: is_async
``True`` for functions that are defined with the ``async`` prefix, ``False`` otherwise.
``True`` for functions that are defined with the
:keyword:`async <async def>` prefix, ``False`` otherwise.
.. versionadded:: 3.10
.. versionadded:: 3.10
.. _pyclbr-class-objects:
Class Objects
-------------
Class :class:`Class` instances describe classes defined by class
statements. They have the same attributes as Functions and two more.
.. class:: Class
Class :class:`!Class` instances describe classes defined by class
statements. They have the same attributes as :class:`Functions <Function>`
and two more.
.. attribute:: Class.file
.. attribute:: file
Name of the file in which the class is defined.
Name of the file in which the class is defined.
.. attribute:: Class.module
.. attribute:: module
The name of the module defining the class described.
The name of the module defining the class described.
.. attribute:: Class.name
.. attribute:: name
The name of the class.
The name of the class.
.. attribute:: Class.lineno
.. attribute:: lineno
The line number in the file where the definition starts.
The line number in the file where the definition starts.
.. attribute:: Class.parent
.. attribute:: parent
For top-level classes, None. For nested classes, the parent.
For top-level classes, None. For nested classes, the parent.
.. versionadded:: 3.7
.. versionadded:: 3.7
.. attribute:: Class.children
.. attribute:: children
A dictionary mapping names to descriptors for nested functions and
classes.
A dictionary mapping names to descriptors for nested functions and
classes.
.. versionadded:: 3.7
.. versionadded:: 3.7
.. attribute:: Class.super
.. attribute:: super
A list of :class:`Class` objects which describe the immediate base
classes of the class being described. Classes which are named as
superclasses but which are not discoverable by :func:`readmodule_ex`
are listed as a string with the class name instead of as
:class:`Class` objects.
A list of :class:`!Class` objects which describe the immediate base
classes of the class being described. Classes which are named as
superclasses but which are not discoverable by :func:`readmodule_ex`
are listed as a string with the class name instead of as
:class:`!Class` objects.
.. attribute:: Class.methods
.. attribute:: methods
A dictionary mapping method names to line numbers. This can be
derived from the newer children dictionary, but remains for
back-compatibility.
A :class:`dictionary <dict>` mapping method names to line numbers.
This can be derived from the newer :attr:`children` dictionary,
but remains for
back-compatibility.

View file

@ -34,10 +34,8 @@ instance of the :class:`random.Random` class. You can instantiate your own
instances of :class:`Random` to get generators that don't share state.
Class :class:`Random` can also be subclassed if you want to use a different
basic generator of your own devising: in that case, override the :meth:`~Random.random`,
:meth:`~Random.seed`, :meth:`~Random.getstate`, and :meth:`~Random.setstate` methods.
Optionally, a new generator can supply a :meth:`~Random.getrandbits` method --- this
allows :meth:`randrange` to produce selections over an arbitrarily large range.
basic generator of your own devising: see the documentation on that class for
more details.
The :mod:`random` module also provides the :class:`SystemRandom` class which
uses the system function :func:`os.urandom` to generate random numbers
@ -88,7 +86,7 @@ Bookkeeping functions
.. versionchanged:: 3.11
The *seed* must be one of the following types:
*NoneType*, :class:`int`, :class:`float`, :class:`str`,
``None``, :class:`int`, :class:`float`, :class:`str`,
:class:`bytes`, or :class:`bytearray`.
.. function:: getstate()
@ -220,8 +218,8 @@ Functions for sequences
generated. For example, a sequence of length 2080 is the largest that
can fit within the period of the Mersenne Twister random number generator.
.. deprecated-removed:: 3.9 3.11
The optional parameter *random*.
.. versionchanged:: 3.11
Removed the optional parameter *random*.
.. function:: sample(population, k, *, counts=None)
@ -407,11 +405,42 @@ Alternative Generator
Class that implements the default pseudo-random number generator used by the
:mod:`random` module.
.. deprecated-removed:: 3.9 3.11
.. versionchanged:: 3.11
Formerly the *seed* could be any hashable object. Now it is limited to:
:class:`NoneType`, :class:`int`, :class:`float`, :class:`str`,
``None``, :class:`int`, :class:`float`, :class:`str`,
:class:`bytes`, or :class:`bytearray`.
Subclasses of :class:`!Random` should override the following methods if they
wish to make use of a different basic generator:
.. method:: Random.seed(a=None, version=2)
Override this method in subclasses to customise the :meth:`~random.seed`
behaviour of :class:`!Random` instances.
.. method:: Random.getstate()
Override this method in subclasses to customise the :meth:`~random.getstate`
behaviour of :class:`!Random` instances.
.. method:: Random.setstate(state)
Override this method in subclasses to customise the :meth:`~random.setstate`
behaviour of :class:`!Random` instances.
.. method:: Random.random()
Override this method in subclasses to customise the :meth:`~random.random`
behaviour of :class:`!Random` instances.
Optionally, a custom generator subclass can also supply the following method:
.. method:: Random.getrandbits(k)
Override this method in subclasses to customise the
:meth:`~random.getrandbits` behaviour of :class:`!Random` instances.
.. class:: SystemRandom([seed])
Class that uses the :func:`os.urandom` function for generating random numbers
@ -445,30 +474,30 @@ Examples
Basic examples::
>>> random() # Random float: 0.0 <= x < 1.0
>>> random() # Random float: 0.0 <= x < 1.0
0.37444887175646646
>>> uniform(2.5, 10.0) # Random float: 2.5 <= x <= 10.0
>>> uniform(2.5, 10.0) # Random float: 2.5 <= x <= 10.0
3.1800146073117523
>>> expovariate(1 / 5) # Interval between arrivals averaging 5 seconds
>>> expovariate(1 / 5) # Interval between arrivals averaging 5 seconds
5.148957571865031
>>> randrange(10) # Integer from 0 to 9 inclusive
>>> randrange(10) # Integer from 0 to 9 inclusive
7
>>> randrange(0, 101, 2) # Even integer from 0 to 100 inclusive
>>> randrange(0, 101, 2) # Even integer from 0 to 100 inclusive
26
>>> choice(['win', 'lose', 'draw']) # Single random element from a sequence
>>> choice(['win', 'lose', 'draw']) # Single random element from a sequence
'draw'
>>> deck = 'ace two three four'.split()
>>> shuffle(deck) # Shuffle a list
>>> shuffle(deck) # Shuffle a list
>>> deck
['four', 'two', 'ace', 'three']
>>> sample([10, 20, 30, 40, 50], k=4) # Four samples without replacement
>>> sample([10, 20, 30, 40, 50], k=4) # Four samples without replacement
[40, 10, 50, 30]
Simulations::
@ -572,14 +601,14 @@ Simulation of arrival times and service deliveries for a multiserver queue::
including simulation, sampling, shuffling, and cross-validation.
`Economics Simulation
<https://nbviewer.jupyter.org/url/norvig.com/ipython/Economics.ipynb>`_
<https://nbviewer.org/url/norvig.com/ipython/Economics.ipynb>`_
a simulation of a marketplace by
`Peter Norvig <https://norvig.com/bio.html>`_ that shows effective
use of many of the tools and distributions provided by this module
(gauss, uniform, sample, betavariate, choice, triangular, and randrange).
`A Concrete Introduction to Probability (using Python)
<https://nbviewer.jupyter.org/url/norvig.com/ipython/Probability.ipynb>`_
<https://nbviewer.org/url/norvig.com/ipython/Probability.ipynb>`_
a tutorial by `Peter Norvig <https://norvig.com/bio.html>`_ covering
the basics of probability theory, how to write simulations, and
how to perform data analysis using Python.

View file

@ -1093,12 +1093,12 @@ Functions
Exceptions
^^^^^^^^^^
.. exception:: error(msg, pattern=None, pos=None)
.. exception:: PatternError(msg, pattern=None, pos=None)
Exception raised when a string passed to one of the functions here is not a
valid regular expression (for example, it might contain unmatched parentheses)
or when some other error occurs during compilation or matching. It is never an
error if a string contains no match for a pattern. The error instance has
error if a string contains no match for a pattern. The ``PatternError`` instance has
the following additional attributes:
.. attribute:: msg
@ -1124,6 +1124,10 @@ Exceptions
.. versionchanged:: 3.5
Added additional attributes.
.. versionchanged:: 3.13
``PatternError`` was originally named ``error``; the latter is kept as an alias for
backward compatibility.
.. _re-objects:
Regular Expression Objects

View file

@ -27,16 +27,15 @@ Readline library in general.
.. note::
The underlying Readline library API may be implemented by
the ``libedit`` library instead of GNU readline.
the ``editline`` (``libedit``) library instead of GNU readline.
On macOS the :mod:`readline` module detects which library is being used
at run time.
The configuration file for ``libedit`` is different from that
The configuration file for ``editline`` is different from that
of GNU readline. If you programmatically load configuration strings
you can check for the text "libedit" in :const:`readline.__doc__`
to differentiate between GNU readline and libedit.
you can use :data:`backend` to determine which library is being used.
If you use *editline*/``libedit`` readline emulation on macOS, the
If you use ``editline``/``libedit`` readline emulation on macOS, the
initialization file located in your home directory is named
``.editrc``. For example, the following content in ``~/.editrc`` will
turn ON *vi* keybindings and TAB completion::
@ -44,6 +43,12 @@ Readline library in general.
python:bind -v
python:bind ^I rl_complete
.. data:: backend
The name of the underlying Readline library being used, either
``"readline"`` or ``"editline"``.
.. versionadded:: 3.13
Init file
---------
@ -213,6 +218,8 @@ Startup hooks
if Python was compiled for a version of the library that supports it.
.. _readline-completion:
Completion
----------

View file

@ -10,7 +10,7 @@
--------------
The :mod:`reprlib` module provides a means for producing object representations
The :mod:`!reprlib` module provides a means for producing object representations
with limits on the size of the resulting strings. This is used in the Python
debugger and may be useful in other contexts as well.
@ -58,29 +58,31 @@ This module provides a class, an instance, and a function:
limits on most sizes.
In addition to size-limiting tools, the module also provides a decorator for
detecting recursive calls to :meth:`__repr__` and substituting a placeholder
string instead.
detecting recursive calls to :meth:`~object.__repr__` and substituting a
placeholder string instead.
.. index:: single: ...; placeholder
.. decorator:: recursive_repr(fillvalue="...")
Decorator for :meth:`__repr__` methods to detect recursive calls within the
Decorator for :meth:`~object.__repr__` methods to detect recursive calls within the
same thread. If a recursive call is made, the *fillvalue* is returned,
otherwise, the usual :meth:`__repr__` call is made. For example:
otherwise, the usual :meth:`!__repr__` call is made. For example:
>>> from reprlib import recursive_repr
>>> class MyList(list):
... @recursive_repr()
... def __repr__(self):
... return '<' + '|'.join(map(repr, self)) + '>'
...
>>> m = MyList('abc')
>>> m.append(m)
>>> m.append('x')
>>> print(m)
<'a'|'b'|'c'|...|'x'>
.. doctest::
>>> from reprlib import recursive_repr
>>> class MyList(list):
... @recursive_repr()
... def __repr__(self):
... return '<' + '|'.join(map(repr, self)) + '>'
...
>>> m = MyList('abc')
>>> m.append(m)
>>> m.append('x')
>>> print(m)
<'a'|'b'|'c'|...|'x'>
.. versionadded:: 3.2
@ -148,10 +150,10 @@ which format specific object types.
with no line breaks or indentation, like the standard :func:`repr`.
For example:
.. code-block:: pycon
.. doctest:: indent
>>> example = [
1, 'spam', {'a': 2, 'b': 'spam eggs', 'c': {3: 4.5, 6: []}}, 'ham']
... 1, 'spam', {'a': 2, 'b': 'spam eggs', 'c': {3: 4.5, 6: []}}, 'ham']
>>> import reprlib
>>> aRepr = reprlib.Repr()
>>> print(aRepr.repr(example))
@ -160,7 +162,7 @@ which format specific object types.
If :attr:`~Repr.indent` is set to a string, each recursion level
is placed on its own line, indented by that string:
.. code-block:: pycon
.. doctest:: indent
>>> aRepr.indent = '-->'
>>> print(aRepr.repr(example))
@ -181,7 +183,7 @@ which format specific object types.
Setting :attr:`~Repr.indent` to a positive integer value behaves as if it
was set to a string with that number of spaces:
.. code-block:: pycon
.. doctest:: indent
>>> aRepr.indent = 4
>>> print(aRepr.repr(example))
@ -234,7 +236,9 @@ Subclassing Repr Objects
The use of dynamic dispatching by :meth:`Repr.repr1` allows subclasses of
:class:`Repr` to add support for additional built-in object types or to modify
the handling of types already supported. This example shows how special support
for file objects could be added::
for file objects could be added:
.. testcode::
import reprlib
import sys
@ -248,3 +252,7 @@ for file objects could be added::
aRepr = MyRepr()
print(aRepr.repr(sys.stdin)) # prints '<stdin>'
.. testoutput::
<stdin>

View file

@ -277,7 +277,7 @@ These functions are used to retrieve resource usage information:
This function returns an object that describes the resources consumed by either
the current process or its children, as specified by the *who* parameter. The
*who* parameter should be specified using one of the :const:`RUSAGE_\*`
*who* parameter should be specified using one of the :const:`!RUSAGE_\*`
constants described below.
A simple example::
@ -353,7 +353,7 @@ These functions are used to retrieve resource usage information:
Returns the number of bytes in a system page. (This need not be the same as the
hardware page size.)
The following :const:`RUSAGE_\*` symbols are passed to the :func:`getrusage`
The following :const:`!RUSAGE_\*` symbols are passed to the :func:`getrusage`
function to specify which processes information should be provided for.

View file

@ -10,12 +10,14 @@
--------------
The :mod:`rlcompleter` module defines a completion function suitable for the
:mod:`readline` module by completing valid Python identifiers and keywords.
The :mod:`!rlcompleter` module defines a completion function suitable to be
passed to :func:`~readline.set_completer` in the :mod:`readline` module.
When this module is imported on a Unix platform with the :mod:`readline` module
available, an instance of the :class:`Completer` class is automatically created
and its :meth:`complete` method is set as the :mod:`readline` completer.
and its :meth:`~Completer.complete` method is set as the
:ref:`readline completer <readline-completion>`. The method provides
completion of valid Python :ref:`identifiers and keywords <identifiers>`.
Example::
@ -28,7 +30,7 @@ Example::
readline.__name__ readline.parse_and_bind(
>>> readline.
The :mod:`rlcompleter` module is designed for use with Python's
The :mod:`!rlcompleter` module is designed for use with Python's
:ref:`interactive mode <tut-interactive>`. Unless Python is run with the
:option:`-S` option, the module is automatically imported and configured
(see :ref:`rlcompleter-config`).
@ -39,23 +41,25 @@ this module can still be used for custom purposes.
.. _completer-objects:
Completer Objects
-----------------
.. class:: Completer
Completer objects have the following method:
Completer objects have the following method:
.. method:: Completer.complete(text, state)
.. method:: Completer.complete(text, state)
Return the next possible completion for *text*.
Return the *state*\ th completion for *text*.
When called by the :mod:`readline` module, this method is called
successively with ``state == 0, 1, 2, ...`` until the method returns
``None``.
If called for *text* that doesn't include a period character (``'.'``), it will
complete from names currently defined in :mod:`__main__`, :mod:`builtins` and
keywords (as defined by the :mod:`keyword` module).
If called for a dotted name, it will try to evaluate anything without obvious
side-effects (functions will not be evaluated, but it can generate calls to
:meth:`__getattr__`) up to the last part, and find matches for the rest via the
:func:`dir` function. Any exception raised during the evaluation of the
expression is caught, silenced and :const:`None` is returned.
If called for *text* that doesn't include a period character (``'.'``), it will
complete from names currently defined in :mod:`__main__`, :mod:`builtins` and
keywords (as defined by the :mod:`keyword` module).
If called for a dotted name, it will try to evaluate anything without obvious
side-effects (functions will not be evaluated, but it can generate calls to
:meth:`~object.__getattr__`) up to the last part, and find matches for the
rest via the :func:`dir` function. Any exception raised during the
evaluation of the expression is caught, silenced and :const:`None` is
returned.

View file

@ -113,6 +113,9 @@ Restrictions
differs across Unix versions and requires knowledge about the database
implementation used.
* On macOS :mod:`dbm.ndbm` can silently corrupt the database file on updates,
which can cause hard crashes when trying to read from the database.
.. class:: Shelf(dict, protocol=None, writeback=False, keyencoding='utf-8')
@ -149,13 +152,14 @@ Restrictions
.. class:: BsdDbShelf(dict, protocol=None, writeback=False, keyencoding='utf-8')
A subclass of :class:`Shelf` which exposes :meth:`first`, :meth:`!next`,
:meth:`previous`, :meth:`last` and :meth:`set_location` which are available
in the third-party :mod:`bsddb` module from `pybsddb
A subclass of :class:`Shelf` which exposes :meth:`!first`, :meth:`!next`,
:meth:`!previous`, :meth:`!last` and :meth:`!set_location` methods.
These are available
in the third-party :mod:`!bsddb` module from `pybsddb
<https://www.jcea.es/programacion/pybsddb.htm>`_ but not in other database
modules. The *dict* object passed to the constructor must support those
methods. This is generally accomplished by calling one of
:func:`bsddb.hashopen`, :func:`bsddb.btopen` or :func:`bsddb.rnopen`. The
:func:`!bsddb.hashopen`, :func:`!bsddb.btopen` or :func:`!bsddb.rnopen`. The
optional *protocol*, *writeback*, and *keyencoding* parameters have the same
interpretation as for the :class:`Shelf` class.

View file

@ -343,6 +343,12 @@ Directory and files operations
.. versionchanged:: 3.12
Added the *onexc* parameter, deprecated *onerror*.
.. versionchanged:: 3.13
:func:`!rmtree` now ignores :exc:`FileNotFoundError` exceptions for all
but the top-level path.
Exceptions other than :exc:`OSError` and subclasses of :exc:`!OSError`
are now always propagated to the caller.
.. attribute:: rmtree.avoids_symlink_attacks
Indicates whether the current platform and implementation provides a

View file

@ -157,6 +157,8 @@ The variables defined in the :mod:`signal` module are:
Alias to :data:`SIGCHLD`.
.. availability:: not macOS.
.. data:: SIGCONT
Continue the process if it is currently stopped

View file

@ -23,7 +23,7 @@ all modern Unix systems, Windows, MacOS, and probably additional platforms.
The Python interface is a straightforward transliteration of the Unix system
call and library interface for sockets to Python's object-oriented style: the
:func:`.socket` function returns a :dfn:`socket object` whose methods implement
:func:`~socket.socket` function returns a :dfn:`socket object` whose methods implement
the various socket system calls. Parameter types are somewhat higher-level than
in the C interface: as with :meth:`read` and :meth:`write` operations on Python
files, buffer allocation on receive operations is automatic, and buffer length
@ -185,7 +185,7 @@ created. Socket addresses are represented as follows:
.. versionadded:: 3.7
- :const:`AF_PACKET` is a low-level interface directly to network devices.
The packets are represented by the tuple
The addresses are represented by the tuple
``(ifname, proto[, pkttype[, hatype[, addr]]])`` where:
- *ifname* - String specifying the device name.
@ -193,7 +193,6 @@ created. Socket addresses are represented as follows:
May be :data:`ETH_P_ALL` to capture all protocols,
one of the :ref:`ETHERTYPE_* constants <socket-ethernet-types>`
or any other Ethernet protocol number.
Value must be in network-byte-order.
- *pkttype* - Optional integer specifying the packet type:
- ``PACKET_HOST`` (the default) - Packet addressed to the local host.
@ -312,7 +311,7 @@ Exceptions
The accompanying value is a pair ``(error, string)`` representing an error
returned by a library call. *string* represents the description of
*error*, as returned by the :c:func:`gai_strerror` C function. The
numeric *error* value will match one of the :const:`EAI_\*` constants
numeric *error* value will match one of the :const:`!EAI_\*` constants
defined in this module.
.. versionchanged:: 3.3
@ -348,7 +347,7 @@ Constants
AF_INET6
These constants represent the address (and protocol) families, used for the
first argument to :func:`.socket`. If the :const:`AF_UNIX` constant is not
first argument to :func:`~socket.socket`. If the :const:`AF_UNIX` constant is not
defined then this protocol is unsupported. More constants may be available
depending on the system.
@ -365,7 +364,7 @@ Constants
SOCK_SEQPACKET
These constants represent the socket types, used for the second argument to
:func:`.socket`. More constants may be available depending on the system.
:func:`~socket.socket`. More constants may be available depending on the system.
(Only :const:`SOCK_STREAM` and :const:`SOCK_DGRAM` appear to be generally
useful.)
@ -404,7 +403,7 @@ Constants
Many constants of these forms, documented in the Unix documentation on sockets
and/or the IP protocol, are also defined in the socket module. They are
generally used in arguments to the :meth:`setsockopt` and :meth:`getsockopt`
generally used in arguments to the :meth:`~socket.setsockopt` and :meth:`~socket.getsockopt`
methods of socket objects. In most cases, only those symbols that are defined
in the Unix header files are defined; for a few symbols, default values are
provided.
@ -770,7 +769,7 @@ The following functions all create :ref:`socket objects <socket-objects>`.
Build a pair of connected socket objects using the given address family, socket
type, and protocol number. Address family, socket type, and protocol number are
as for the :func:`.socket` function above. The default family is :const:`AF_UNIX`
as for the :func:`~socket.socket` function above. The default family is :const:`AF_UNIX`
if defined on the platform; otherwise, the default is :const:`AF_INET`.
The newly created sockets are :ref:`non-inheritable <fd_inheritance>`.
@ -866,7 +865,7 @@ The following functions all create :ref:`socket objects <socket-objects>`.
Duplicate the file descriptor *fd* (an integer as returned by a file object's
:meth:`~io.IOBase.fileno` method) and build a socket object from the result. Address
family, socket type and protocol number are as for the :func:`.socket` function
family, socket type and protocol number are as for the :func:`~socket.socket` function
above. The file descriptor should refer to a socket, but this is not checked ---
subsequent operations on the object may fail if the file descriptor is invalid.
This function is rarely needed, but can be used to get or set socket options on
@ -931,7 +930,7 @@ The :mod:`socket` module also offers various network-related services:
``(family, type, proto, canonname, sockaddr)``
In these tuples, *family*, *type*, *proto* are all integers and are
meant to be passed to the :func:`.socket` function. *canonname* will be
meant to be passed to the :func:`~socket.socket` function. *canonname* will be
a string representing the canonical name of the *host* if
:const:`AI_CANONNAME` is part of the *flags* argument; else *canonname*
will be empty. *sockaddr* is a tuple describing a socket address, whose
@ -1047,7 +1046,7 @@ The :mod:`socket` module also offers various network-related services:
.. function:: getprotobyname(protocolname)
Translate an internet protocol name (for example, ``'icmp'``) to a constant
suitable for passing as the (optional) third argument to the :func:`.socket`
suitable for passing as the (optional) third argument to the :func:`~socket.socket`
function. This is usually only needed for sockets opened in "raw" mode
(:const:`SOCK_RAW`); for the normal socket modes, the correct protocol is chosen
automatically if the protocol is omitted or zero.
@ -1331,7 +1330,7 @@ The :mod:`socket` module also offers various network-related services:
Send the list of file descriptors *fds* over an :const:`AF_UNIX` socket *sock*.
The *fds* parameter is a sequence of file descriptors.
Consult :meth:`sendmsg` for the documentation of these parameters.
Consult :meth:`~socket.sendmsg` for the documentation of these parameters.
.. availability:: Unix, Windows, not Emscripten, not WASI.
@ -1345,7 +1344,7 @@ The :mod:`socket` module also offers various network-related services:
Receive up to *maxfds* file descriptors from an :const:`AF_UNIX` socket *sock*.
Return ``(msg, list(fds), flags, addr)``.
Consult :meth:`recvmsg` for the documentation of these parameters.
Consult :meth:`~socket.recvmsg` for the documentation of these parameters.
.. availability:: Unix, Windows, not Emscripten, not WASI.
@ -1518,7 +1517,7 @@ to sockets.
.. method:: socket.getsockopt(level, optname[, buflen])
Return the value of the given socket option (see the Unix man page
:manpage:`getsockopt(2)`). The needed symbolic constants (:const:`SO_\*` etc.)
:manpage:`getsockopt(2)`). The needed symbolic constants (:ref:`SO_\* etc. <socket-unix-constants>`)
are defined in this module. If *buflen* is absent, an integer option is assumed
and its integer value is returned by the function. If *buflen* is present, it
specifies the maximum length of the buffer used to receive the option in, and
@ -1938,8 +1937,8 @@ to sockets.
.. index:: pair: module; struct
Set the value of the given socket option (see the Unix manual page
:manpage:`setsockopt(2)`). The needed symbolic constants are defined in the
:mod:`socket` module (:const:`SO_\*` etc.). The value can be an integer,
:manpage:`setsockopt(2)`). The needed symbolic constants are defined in this
module (:ref:`!SO_\* etc. <socket-unix-constants>`). The value can be an integer,
``None`` or a :term:`bytes-like object` representing a buffer. In the later
case it is up to the caller to ensure that the bytestring contains the
proper bits (see the optional built-in module :mod:`struct` for a way to
@ -2064,10 +2063,10 @@ Example
Here are four minimal example programs using the TCP/IP protocol: a server that
echoes all data that it receives back (servicing only one client), and a client
using it. Note that a server must perform the sequence :func:`.socket`,
using it. Note that a server must perform the sequence :func:`~socket.socket`,
:meth:`~socket.bind`, :meth:`~socket.listen`, :meth:`~socket.accept` (possibly
repeating the :meth:`~socket.accept` to service more than one client), while a
client only needs the sequence :func:`.socket`, :meth:`~socket.connect`. Also
client only needs the sequence :func:`~socket.socket`, :meth:`~socket.connect`. Also
note that the server does not :meth:`~socket.sendall`/:meth:`~socket.recv` on
the socket it is listening on but on the new socket returned by
:meth:`~socket.accept`.

View file

@ -1502,7 +1502,7 @@ Cursor objects
.. method:: execute(sql, parameters=(), /)
Execute SQL a single SQL statement,
Execute a single SQL statement,
optionally binding Python values using
:ref:`placeholders <sqlite3-placeholders>`.

View file

@ -25,7 +25,7 @@ probably additional platforms, as long as OpenSSL is installed on that platform.
Some behavior may be platform dependent, since calls are made to the
operating system socket APIs. The installed version of OpenSSL may also
cause variations in behavior. For example, TLSv1.3 with OpenSSL version
cause variations in behavior. For example, TLSv1.3 comes with OpenSSL version
1.1.1.
.. warning::
@ -908,6 +908,12 @@ Constants
.. versionadded:: 3.7
.. data:: HAS_PSK
Whether the OpenSSL library has built-in support for TLS-PSK.
.. versionadded:: 3.13
.. data:: CHANNEL_BINDING_TYPES
List of supported TLS channel binding types. Strings in this list
@ -2006,6 +2012,100 @@ to speed up repeated connections from the same clients.
>>> ssl.create_default_context().verify_mode # doctest: +SKIP
<VerifyMode.CERT_REQUIRED: 2>
.. method:: SSLContext.set_psk_client_callback(callback)
Enables TLS-PSK (pre-shared key) authentication on a client-side connection.
In general, certificate based authentication should be preferred over this method.
The parameter ``callback`` is a callable object with the signature:
``def callback(hint: str | None) -> tuple[str | None, bytes]``.
The ``hint`` parameter is an optional identity hint sent by the server.
The return value is a tuple in the form (client-identity, psk).
Client-identity is an optional string which may be used by the server to
select a corresponding PSK for the client. The string must be less than or
equal to ``256`` octets when UTF-8 encoded. PSK is a
:term:`bytes-like object` representing the pre-shared key. Return a zero
length PSK to reject the connection.
Setting ``callback`` to :const:`None` removes any existing callback.
.. note::
When using TLS 1.3:
- the ``hint`` parameter is always :const:`None`.
- client-identity must be a non-empty string.
Example usage::
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
context.maximum_version = ssl.TLSVersion.TLSv1_2
context.set_ciphers('PSK')
# A simple lambda:
psk = bytes.fromhex('c0ffee')
context.set_psk_client_callback(lambda hint: (None, psk))
# A table using the hint from the server:
psk_table = { 'ServerId_1': bytes.fromhex('c0ffee'),
'ServerId_2': bytes.fromhex('facade')
}
def callback(hint):
return 'ClientId_1', psk_table.get(hint, b'')
context.set_psk_client_callback(callback)
This method will raise :exc:`NotImplementedError` if :data:`HAS_PSK` is
``False``.
.. versionadded:: 3.13
.. method:: SSLContext.set_psk_server_callback(callback, identity_hint=None)
Enables TLS-PSK (pre-shared key) authentication on a server-side connection.
In general, certificate based authentication should be preferred over this method.
The parameter ``callback`` is a callable object with the signature:
``def callback(identity: str | None) -> bytes``.
The ``identity`` parameter is an optional identity sent by the client which can
be used to select a corresponding PSK.
The return value is a :term:`bytes-like object` representing the pre-shared key.
Return a zero length PSK to reject the connection.
Setting ``callback`` to :const:`None` removes any existing callback.
The parameter ``identity_hint`` is an optional identity hint string sent to
the client. The string must be less than or equal to ``256`` octets when
UTF-8 encoded.
.. note::
When using TLS 1.3 the ``identity_hint`` parameter is not sent to the client.
Example usage::
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.maximum_version = ssl.TLSVersion.TLSv1_2
context.set_ciphers('PSK')
# A simple lambda:
psk = bytes.fromhex('c0ffee')
context.set_psk_server_callback(lambda identity: psk)
# A table using the identity of the client:
psk_table = { 'ClientId_1': bytes.fromhex('c0ffee'),
'ClientId_2': bytes.fromhex('facade')
}
def callback(identity):
return psk_table.get(identity, b'')
context.set_psk_server_callback(callback, 'ServerId_1')
This method will raise :exc:`NotImplementedError` if :data:`HAS_PSK` is
``False``.
.. versionadded:: 3.13
.. index:: single: certificates
.. index:: single: X509 certificate

View file

@ -44,7 +44,8 @@ Any object can be tested for truth value, for use in an :keyword:`if` or
.. index:: single: true
By default, an object is considered true unless its class defines either a
:meth:`~object.__bool__` method that returns ``False`` or a :meth:`__len__` method that
:meth:`~object.__bool__` method that returns ``False`` or a
:meth:`~object.__len__` method that
returns zero, when called with the object. [1]_ Here are most of the built-in
objects considered false:
@ -197,7 +198,7 @@ exception.
Two more operations with the same syntactic priority, :keyword:`in` and
:keyword:`not in`, are supported by types that are :term:`iterable` or
implement the :meth:`__contains__` method.
implement the :meth:`~object.__contains__` method.
.. _typesnumeric:
@ -717,7 +718,7 @@ that's defined for any rational number, and hence applies to all instances of
:class:`int` and :class:`fractions.Fraction`, and all finite instances of
:class:`float` and :class:`decimal.Decimal`. Essentially, this function is
given by reduction modulo ``P`` for a fixed prime ``P``. The value of ``P`` is
made available to Python as the :attr:`modulus` attribute of
made available to Python as the :attr:`~sys.hash_info.modulus` attribute of
:data:`sys.hash_info`.
.. impl-detail::
@ -906,9 +907,9 @@ Generator Types
---------------
Python's :term:`generator`\s provide a convenient way to implement the iterator
protocol. If a container object's :meth:`__iter__` method is implemented as a
protocol. If a container object's :meth:`~iterator.__iter__` method is implemented as a
generator, it will automatically return an iterator object (technically, a
generator object) supplying the :meth:`__iter__` and :meth:`~generator.__next__`
generator object) supplying the :meth:`!__iter__` and :meth:`~generator.__next__`
methods.
More information about generators can be found in :ref:`the documentation for
the yield expression <yieldexpr>`.
@ -3672,7 +3673,7 @@ The conversion types are:
+------------+-----------------------------------------------------+-------+
| ``'b'`` | Bytes (any object that follows the | \(5) |
| | :ref:`buffer protocol <bufferobjects>` or has | |
| | :meth:`__bytes__`). | |
| | :meth:`~object.__bytes__`). | |
+------------+-----------------------------------------------------+-------+
| ``'s'`` | ``'s'`` is an alias for ``'b'`` and should only | \(6) |
| | be used for Python2/3 code bases. | |
@ -4410,7 +4411,8 @@ The constructors for both classes work the same:
:meth:`symmetric_difference_update` methods will accept any iterable as an
argument.
Note, the *elem* argument to the :meth:`__contains__`, :meth:`remove`, and
Note, the *elem* argument to the :meth:`~object.__contains__`,
:meth:`remove`, and
:meth:`discard` methods may be a set. To support searching for an equivalent
frozenset, a temporary one is created from *elem*.
@ -5236,9 +5238,11 @@ instantiated from the type::
TypeError: cannot create 'types.UnionType' instances
.. note::
The :meth:`__or__` method for type objects was added to support the syntax
``X | Y``. If a metaclass implements :meth:`__or__`, the Union may
override it::
The :meth:`!__or__` method for type objects was added to support the syntax
``X | Y``. If a metaclass implements :meth:`!__or__`, the Union may
override it:
.. doctest::
>>> class M(type):
... def __or__(self, other):
@ -5250,7 +5254,7 @@ instantiated from the type::
>>> C | int
'Hello'
>>> int | C
int | __main__.C
int | C
.. seealso::
@ -5324,25 +5328,30 @@ Methods
.. index:: pair: object; method
Methods are functions that are called using the attribute notation. There are
two flavors: built-in methods (such as :meth:`append` on lists) and class
instance methods. Built-in methods are described with the types that support
them.
two flavors: :ref:`built-in methods <builtin-methods>` (such as :meth:`append`
on lists) and :ref:`class instance method <instance-methods>`.
Built-in methods are described with the types that support them.
If you access a method (a function defined in a class namespace) through an
instance, you get a special object: a :dfn:`bound method` (also called
:dfn:`instance method`) object. When called, it will add the ``self`` argument
:ref:`instance method <instance-methods>`) object. When called, it will add
the ``self`` argument
to the argument list. Bound methods have two special read-only attributes:
``m.__self__`` is the object on which the method operates, and ``m.__func__`` is
:attr:`m.__self__ <method.__self__>` is the object on which the method
operates, and :attr:`m.__func__ <method.__func__>` is
the function implementing the method. Calling ``m(arg-1, arg-2, ..., arg-n)``
is completely equivalent to calling ``m.__func__(m.__self__, arg-1, arg-2, ...,
arg-n)``.
Like function objects, bound method objects support getting arbitrary
Like :ref:`function objects <user-defined-funcs>`, bound method objects support
getting arbitrary
attributes. However, since method attributes are actually stored on the
underlying function object (``meth.__func__``), setting method attributes on
underlying function object (:attr:`method.__func__`), setting method attributes on
bound methods is disallowed. Attempting to set an attribute on a method
results in an :exc:`AttributeError` being raised. In order to set a method
attribute, you need to explicitly set it on the underlying function object::
attribute, you need to explicitly set it on the underlying function object:
.. doctest::
>>> class C:
... def method(self):
@ -5357,7 +5366,7 @@ attribute, you need to explicitly set it on the underlying function object::
>>> c.method.whoami
'my name is method'
See :ref:`types` for more information.
See :ref:`instance-methods` for more information.
.. index:: object; code, code object
@ -5375,10 +5384,10 @@ Code objects are used by the implementation to represent "pseudo-compiled"
executable Python code such as a function body. They differ from function
objects because they don't contain a reference to their global execution
environment. Code objects are returned by the built-in :func:`compile` function
and can be extracted from function objects through their :attr:`__code__`
attribute. See also the :mod:`code` module.
and can be extracted from function objects through their
:attr:`~function.__code__` attribute. See also the :mod:`code` module.
Accessing ``__code__`` raises an :ref:`auditing event <auditing>`
Accessing :attr:`~function.__code__` raises an :ref:`auditing event <auditing>`
``object.__getattr__`` with arguments ``obj`` and ``"__code__"``.
.. index::
@ -5452,8 +5461,9 @@ It is written as ``NotImplemented``.
Internal Objects
----------------
See :ref:`types` for this information. It describes stack frame objects,
traceback objects, and slice objects.
See :ref:`types` for this information. It describes
:ref:`stack frame objects <frame-objects>`,
:ref:`traceback objects <traceback-objects>`, and slice objects.
.. _specialattrs:

Some files were not shown because too many files have changed in this diff Show more