Skip to content

Commit

Permalink
Pull in main
Browse files Browse the repository at this point in the history
  • Loading branch information
erlend-aasland committed Feb 20, 2024
2 parents 7720c66 + 494739e commit c5bd50a
Show file tree
Hide file tree
Showing 230 changed files with 5,488 additions and 4,719 deletions.
3 changes: 2 additions & 1 deletion .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ 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/internal/pycore_uop_metadata.h generated
Include/opcode.h generated
Include/opcode_ids.h generated
Include/token.h generated
Expand All @@ -94,7 +95,7 @@ Programs/test_frozenmain.h generated
Python/Python-ast.c generated
Python/executor_cases.c.h generated
Python/generated_cases.c.h generated
Python/tier2_redundancy_eliminator_bytecodes.c.h generated
Python/tier2_redundancy_eliminator_cases.c.h generated
Python/opcode_targets.h generated
Python/stdlib_module_names.h generated
Tools/peg_generator/pegen/grammar_parser.py generated
Expand Down
1 change: 1 addition & 0 deletions Doc/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,7 @@
('py:attr', '__annotations__'),
('py:meth', '__missing__'),
('py:attr', '__wrapped__'),
('py:attr', 'decimal.Context.clamp'),
('py:meth', 'index'), # list.index, tuple.index, etc.
]

Expand Down
45 changes: 36 additions & 9 deletions Doc/howto/descriptor.rst
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
.. _descriptorhowto:

======================
Descriptor HowTo Guide
======================
================
Descriptor Guide
================

:Author: Raymond Hettinger
:Contact: <python at rcn dot com>
Expand Down Expand Up @@ -1004,31 +1004,42 @@ here is a pure Python equivalent:
if doc is None and fget is not None:
doc = fget.__doc__
self.__doc__ = doc
self._name = ''
self._name = None

def __set_name__(self, owner, name):
self._name = name

@property
def __name__(self):
return self._name if self._name is not None else self.fget.__name__

@__name__.setter
def __name__(self, value):
self._name = value

def __get__(self, obj, objtype=None):
if obj is None:
return self
if self.fget is None:
raise AttributeError(
f'property {self._name!r} of {type(obj).__name__!r} object has no getter'
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!r} of {type(obj).__name__!r} object has no setter'
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!r} of {type(obj).__name__!r} object has no deleter'
f'property {self.__name__!r} of {type(obj).__name__!r} '
'object has no deleter'
)
self.fdel(obj)

Expand Down Expand Up @@ -1192,6 +1203,10 @@ roughly equivalent to:
"Emulate method_getattro() in Objects/classobject.c"
return getattr(self.__func__, name)

def __get__(self, obj, objtype=None):
"Emulate method_descr_get() in Objects/classobject.c"
return self

To support automatic creation of methods, functions include the
:meth:`__get__` method for binding methods during attribute access. This
means that functions are non-data descriptors that return bound methods
Expand All @@ -1214,8 +1229,20 @@ descriptor works in practice:
.. testcode::

class D:
def f(self, x):
return x
def f(self):
return self

class D2:
pass

.. doctest::
:hide:

>>> d = D()
>>> d2 = D2()
>>> d2.f = d.f.__get__(d2, D2)
>>> d2.f() is d
True

The function has a :term:`qualified name` attribute to support introspection:

Expand Down
64 changes: 56 additions & 8 deletions Doc/howto/sorting.rst
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
.. _sortinghowto:

Sorting HOW TO
**************
Sorting Techniques
******************

:Author: Andrew Dalke and Raymond Hettinger
:Release: 0.1


Python lists have a built-in :meth:`list.sort` method that modifies the list
Expand Down Expand Up @@ -56,7 +55,7 @@ For example, here's a case-insensitive string comparison:

.. doctest::

>>> sorted("This is a test string from Andrew".split(), key=str.lower)
>>> sorted("This is a test string from Andrew".split(), key=str.casefold)
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']

The value of the *key* parameter should be a function (or other callable) that
Expand Down Expand Up @@ -97,10 +96,14 @@ The same technique works for objects with named attributes. For example:
>>> sorted(student_objects, key=lambda student: student.age) # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

Operator Module Functions
=========================
Objects with named attributes can be made by a regular class as shown
above, or they can be instances of :class:`~dataclasses.dataclass` or
a :term:`named tuple`.

The key-function patterns shown above are very common, so Python provides
Operator Module Functions and Partial Function Evaluation
=========================================================

The :term:`key function` patterns shown above are very common, so Python provides
convenience functions to make accessor functions easier and faster. The
:mod:`operator` module has :func:`~operator.itemgetter`,
:func:`~operator.attrgetter`, and a :func:`~operator.methodcaller` function.
Expand Down Expand Up @@ -128,6 +131,24 @@ sort by *grade* then by *age*:
>>> sorted(student_objects, key=attrgetter('grade', 'age'))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

The :mod:`functools` module provides another helpful tool for making
key-functions. The :func:`~functools.partial` function can reduce the
`arity <https://en.wikipedia.org/wiki/Arity>`_ of a multi-argument
function making it suitable for use as a key-function.

.. doctest::

>>> from functools import partial
>>> from unicodedata import normalize

>>> names = 'Zoë Åbjørn Núñez Élana Zeke Abe Nubia Eloise'.split()

>>> sorted(names, key=partial(normalize, 'NFD'))
['Abe', 'Åbjørn', 'Eloise', 'Élana', 'Nubia', 'Núñez', 'Zeke', 'Zoë']

>>> sorted(names, key=partial(normalize, 'NFC'))
['Abe', 'Eloise', 'Nubia', 'Núñez', 'Zeke', 'Zoë', 'Åbjørn', 'Élana']

Ascending and Descending
========================

Expand Down Expand Up @@ -200,6 +221,8 @@ This idiom is called Decorate-Sort-Undecorate after its three steps:

For example, to sort the student data by *grade* using the DSU approach:

.. doctest::

>>> decorated = [(student.grade, i, student) for i, student in enumerate(student_objects)]
>>> decorated.sort()
>>> [student for grade, i, student in decorated] # undecorate
Expand Down Expand Up @@ -282,7 +305,11 @@ Odds and Ends
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

However, note that ``<`` can fall back to using :meth:`~object.__gt__` if
:meth:`~object.__lt__` is not implemented (see :func:`object.__lt__`).
:meth:`~object.__lt__` is not implemented (see :func:`object.__lt__`
for details on the mechanics). To avoid surprises, :pep:`8`
recommends that all six comparison methods be implemented.
The :func:`~functools.total_ordering` decorator is provided to make that
task easier.

* Key functions need not depend directly on the objects being sorted. A key
function can also access external resources. For instance, if the student grades
Expand All @@ -295,3 +322,24 @@ Odds and Ends
>>> newgrades = {'john': 'F', 'jane':'A', 'dave': 'C'}
>>> sorted(students, key=newgrades.__getitem__)
['jane', 'dave', 'john']

Partial Sorts
=============

Some applications require only some of the data to be ordered. The standard
library provides several tools that do less work than a full sort:

* :func:`min` and :func:`max` return the smallest and largest values,
respectively. These functions make a single pass over the input data and
require almost no auxiliary memory.

* :func:`heapq.nsmallest` and :func:`heapq.nlargest` return
the *n* smallest and largest values, respectively. These functions
make a single pass over the data keeping only *n* elements in memory
at a time. For values of *n* that are small relative to the number of
inputs, these functions make far fewer comparisons than a full sort.

* :func:`heapq.heappush` and :func:`heapq.heappop` create and maintain a
partially sorted arrangement of data that keeps the smallest element
at position ``0``. These functions are suitable for implementing
priority queues which are commonly used for task scheduling.
2 changes: 1 addition & 1 deletion Doc/library/argparse.rst
Original file line number Diff line number Diff line change
Expand Up @@ -745,7 +745,7 @@ The add_argument() method

.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \
[const], [default], [type], [choices], [required], \
[help], [metavar], [dest])
[help], [metavar], [dest], [deprecated])

Define how a single command-line argument should be parsed. Each parameter
has its own more detailed description below, but in short they are:
Expand Down
5 changes: 5 additions & 0 deletions Doc/library/asyncio-protocol.rst
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,11 @@ Datagram Transports
This method does not block; it buffers the data and arranges
for it to be sent out asynchronously.

.. versionchanged:: 3.13
This method can be called with an empty bytes object to send a
zero-length datagram. The buffer size calculation used for flow
control is also updated to account for the datagram header.

.. method:: DatagramTransport.abort()

Close the transport immediately, without waiting for pending
Expand Down
9 changes: 5 additions & 4 deletions Doc/library/codecs.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1132,7 +1132,8 @@ particular, the following variants typically exist:
+-----------------+--------------------------------+--------------------------------+
| cp875 | | Greek |
+-----------------+--------------------------------+--------------------------------+
| cp932 | 932, ms932, mskanji, ms-kanji | Japanese |
| cp932 | 932, ms932, mskanji, ms-kanji, | Japanese |
| | windows-31j | |
+-----------------+--------------------------------+--------------------------------+
| cp949 | 949, ms949, uhc | Korean |
+-----------------+--------------------------------+--------------------------------+
Expand Down Expand Up @@ -1540,13 +1541,13 @@ This module implements the ANSI codepage (CP_ACP).

.. availability:: Windows.

.. versionchanged:: 3.3
Support any error handler.

.. versionchanged:: 3.2
Before 3.2, the *errors* argument was ignored; ``'replace'`` was always used
to encode, and ``'ignore'`` to decode.

.. versionchanged:: 3.3
Support any error handler.


:mod:`encodings.utf_8_sig` --- UTF-8 codec with BOM signature
-------------------------------------------------------------
Expand Down
4 changes: 2 additions & 2 deletions Doc/library/ftplib.rst
Original file line number Diff line number Diff line change
Expand Up @@ -232,8 +232,8 @@ FTP objects
.. method:: FTP.voidcmd(cmd)

Send a simple command string to the server and handle the response. Return
nothing if a response code corresponding to success (codes in the range
200--299) is received. Raise :exc:`error_reply` otherwise.
the response string if the response code corresponds to success (codes in
the range 200--299). Raise :exc:`error_reply` otherwise.

.. audit-event:: ftplib.sendcmd self,cmd ftplib.FTP.voidcmd

Expand Down
8 changes: 4 additions & 4 deletions Doc/library/math.rst
Original file line number Diff line number Diff line change
Expand Up @@ -239,11 +239,11 @@ Number-theoretic and representation functions

See also :func:`math.ulp`.

.. versionadded:: 3.9

.. versionchanged:: 3.12
Added the *steps* argument.

.. versionadded:: 3.9

.. function:: perm(n, k=None)

Return the number of ways to choose *k* items from *n* items
Expand Down Expand Up @@ -680,11 +680,11 @@ Constants
>>> math.isnan(float('nan'))
True

.. versionadded:: 3.5

.. versionchanged:: 3.11
It is now always available.

.. versionadded:: 3.5


.. impl-detail::

Expand Down
Loading

0 comments on commit c5bd50a

Please sign in to comment.