Skip to content
This repository was archived by the owner on Feb 13, 2025. It is now read-only.

Commit 48b1d86

Browse files
author
Anselm Kruis
committed
Merge branch main into main-slp
2 parents 7abfb91 + 175421b commit 48b1d86

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

67 files changed

+1235
-281
lines changed

Doc/howto/regex.rst

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -96,8 +96,9 @@ special nature.
9696

9797
You can match the characters not listed within the class by :dfn:`complementing`
9898
the set. This is indicated by including a ``'^'`` as the first character of the
99-
class; ``'^'`` outside a character class will simply match the ``'^'``
100-
character. For example, ``[^5]`` will match any character except ``'5'``.
99+
class. For example, ``[^5]`` will match any character except ``'5'``. If the
100+
caret appears elsewhere in a character class, it does not have special meaning.
101+
For example: ``[5^]`` will match either a ``'5'`` or a ``'^'``.
101102

102103
Perhaps the most important metacharacter is the backslash, ``\``. As in Python
103104
string literals, the backslash can be followed by various characters to signal

Doc/library/asyncio-eventloop.rst

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1394,8 +1394,7 @@ Do not instantiate the class directly.
13941394

13951395
.. attribute:: sockets
13961396

1397-
List of :class:`socket.socket` objects the server is listening on,
1398-
or ``None`` if the server is closed.
1397+
List of :class:`socket.socket` objects the server is listening on.
13991398

14001399
.. versionchanged:: 3.7
14011400
Prior to Python 3.7 ``Server.sockets`` used to return an

Doc/library/collections.rst

Lines changed: 79 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,21 @@ The class can be used to simulate nested scopes and is useful in templating.
100100
:func:`super` function. A reference to ``d.parents`` is equivalent to:
101101
``ChainMap(*d.maps[1:])``.
102102

103+
Note, the iteration order of a :class:`ChainMap()` is determined by
104+
scanning the mappings last to first::
105+
106+
>>> baseline = {'music': 'bach', 'art': 'rembrandt'}
107+
>>> adjustments = {'art': 'van gogh', 'opera': 'carmen'}
108+
>>> list(ChainMap(adjustments, baseline))
109+
['music', 'art', 'opera']
110+
111+
This gives the same ordering as a series of :meth:`dict.update` calls
112+
starting with the last mapping::
113+
114+
>>> combined = baseline.copy()
115+
>>> combined.update(adjustments)
116+
>>> list(combined)
117+
['music', 'art', 'opera']
103118

104119
.. seealso::
105120

@@ -163,8 +178,8 @@ contexts::
163178
e.maps[-1] # Root context -- like Python's globals()
164179
e.parents # Enclosing context chain -- like Python's nonlocals
165180

166-
d['x'] # Get first key in the chain of contexts
167181
d['x'] = 1 # Set value in current context
182+
d['x'] # Get first key in the chain of contexts
168183
del d['x'] # Delete from current context
169184
list(d) # All nested values
170185
k in d # Check all nested values
@@ -253,15 +268,20 @@ For example::
253268

254269
.. versionadded:: 3.1
255270

271+
.. versionchanged:: 3.7 As a :class:`dict` subclass, :class:`Counter`
272+
Inherited the capability to remember insertion order. Math operations
273+
on *Counter* objects also preserve order. Results are ordered
274+
according to when an element is first encountered in the left operand
275+
and then by the order encountered in the right operand.
256276

257277
Counter objects support three methods beyond those available for all
258278
dictionaries:
259279

260280
.. method:: elements()
261281

262282
Return an iterator over elements repeating each as many times as its
263-
count. Elements are returned in arbitrary order. If an element's count
264-
is less than one, :meth:`elements` will ignore it.
283+
count. Elements are returned in the order first encountered. If an
284+
element's count is less than one, :meth:`elements` will ignore it.
265285

266286
>>> c = Counter(a=4, b=2, c=0, d=-2)
267287
>>> sorted(c.elements())
@@ -272,10 +292,10 @@ For example::
272292
Return a list of the *n* most common elements and their counts from the
273293
most common to the least. If *n* is omitted or ``None``,
274294
:meth:`most_common` returns *all* elements in the counter.
275-
Elements with equal counts are ordered arbitrarily:
295+
Elements with equal counts are ordered in the order first encountered:
276296

277-
>>> Counter('abracadabra').most_common(3) # doctest: +SKIP
278-
[('a', 5), ('r', 2), ('b', 2)]
297+
>>> Counter('abracadabra').most_common(3)
298+
[('a', 5), ('b', 2), ('r', 2)]
279299

280300
.. method:: subtract([iterable-or-mapping])
281301

@@ -887,7 +907,7 @@ field names, the method and attribute names start with an underscore.
887907

888908
.. method:: somenamedtuple._asdict()
889909

890-
Return a new :class:`OrderedDict` which maps field names to their corresponding
910+
Return a new :class:`dict` which maps field names to their corresponding
891911
values:
892912

893913
.. doctest::
@@ -1024,17 +1044,41 @@ customize a prototype instance:
10241044
:class:`OrderedDict` objects
10251045
----------------------------
10261046

1027-
Ordered dictionaries are just like regular dictionaries but they remember the
1028-
order that items were inserted. When iterating over an ordered dictionary,
1029-
the items are returned in the order their keys were first added.
1047+
Ordered dictionaries are just like regular dictionaries but have some extra
1048+
capabilities relating to ordering operations. They have become less
1049+
important now that the built-in :class:`dict` class gained the ability
1050+
to remember insertion order (this new behavior became guaranteed in
1051+
Python 3.7).
1052+
1053+
Some differences from :class:`dict` still remain:
1054+
1055+
* The regular :class:`dict` was designed to be very good at mapping
1056+
operations. Tracking insertion order was secondary.
1057+
1058+
* The :class:`OrderedDict` was designed to be good at reordering operations.
1059+
Space efficiency, iteration speed, and the performance of update
1060+
operations were secondary.
1061+
1062+
* Algorithmically, :class:`OrderedDict` can handle frequent reordering
1063+
operations better than :class:`dict`. This makes it suitable for tracking
1064+
recent accesses (for example in an `LRU cache
1065+
<https://medium.com/@krishankantsinghal/my-first-blog-on-medium-583159139237>`_).
1066+
1067+
* The equality operation for :class:`OrderedDict` checks for matching order.
1068+
1069+
* The :meth:`popitem` method of :class:`OrderedDict` has a different
1070+
signature. It accepts an optional argument to specify which item is popped.
1071+
1072+
* :class:`OrderedDict` has a :meth:`move_to_end` method to
1073+
efficiently reposition an element to an endpoint.
1074+
1075+
* Until Python 3.8, :class:`dict` lacked a :meth:`__reversed__` method.
1076+
10301077

10311078
.. class:: OrderedDict([items])
10321079

1033-
Return an instance of a dict subclass, supporting the usual :class:`dict`
1034-
methods. An *OrderedDict* is a dict that remembers the order that keys
1035-
were first inserted. If a new entry overwrites an existing entry, the
1036-
original insertion position is left unchanged. Deleting an entry and
1037-
reinserting it will move it to the end.
1080+
Return an instance of a :class:`dict` subclass that has methods
1081+
specialized for rearranging dictionary order.
10381082

10391083
.. versionadded:: 3.1
10401084

@@ -1084,29 +1128,7 @@ anywhere a regular dictionary is used.
10841128
:class:`OrderedDict` Examples and Recipes
10851129
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
10861130

1087-
Since an ordered dictionary remembers its insertion order, it can be used
1088-
in conjunction with sorting to make a sorted dictionary::
1089-
1090-
>>> # regular unsorted dictionary
1091-
>>> d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}
1092-
1093-
>>> # dictionary sorted by key
1094-
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
1095-
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
1096-
1097-
>>> # dictionary sorted by value
1098-
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
1099-
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])
1100-
1101-
>>> # dictionary sorted by length of the key string
1102-
>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
1103-
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
1104-
1105-
The new sorted dictionaries maintain their sort order when entries
1106-
are deleted. But when new keys are added, the keys are appended
1107-
to the end and the sort is not maintained.
1108-
1109-
It is also straight-forward to create an ordered dictionary variant
1131+
It is straightforward to create an ordered dictionary variant
11101132
that remembers the order the keys were *last* inserted.
11111133
If a new entry overwrites an existing entry, the
11121134
original insertion position is changed and moved to the end::
@@ -1115,21 +1137,29 @@ original insertion position is changed and moved to the end::
11151137
'Store items in the order the keys were last added'
11161138

11171139
def __setitem__(self, key, value):
1118-
if key in self:
1119-
del self[key]
1120-
OrderedDict.__setitem__(self, key, value)
1140+
super().__setitem__(key, value)
1141+
super().move_to_end(key)
11211142

1122-
An ordered dictionary can be combined with the :class:`Counter` class
1123-
so that the counter remembers the order elements are first encountered::
1143+
An :class:`OrderedDict` would also be useful for implementing
1144+
variants of :func:`functools.lru_cache`::
11241145

1125-
class OrderedCounter(Counter, OrderedDict):
1126-
'Counter that remembers the order elements are first encountered'
1146+
class LRU(OrderedDict):
1147+
'Limit size, evicting the least recently looked-up key when full'
11271148

1128-
def __repr__(self):
1129-
return '%s(%r)' % (self.__class__.__name__, OrderedDict(self))
1149+
def __init__(self, maxsize=128, *args, **kwds):
1150+
self.maxsize = maxsize
1151+
super().__init__(*args, **kwds)
11301152

1131-
def __reduce__(self):
1132-
return self.__class__, (OrderedDict(self),)
1153+
def __getitem__(self, key):
1154+
value = super().__getitem__(key)
1155+
self.move_to_end(key)
1156+
return value
1157+
1158+
def __setitem__(self, key, value):
1159+
super().__setitem__(key, value)
1160+
if len(self) > self.maxsize:
1161+
oldest = next(iter(self))
1162+
del self[oldest]
11331163

11341164

11351165
:class:`UserDict` objects

Doc/library/functions.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -816,7 +816,7 @@ are always available. They are listed here in alphabetical order.
816816

817817
from functools import partial
818818
with open('mydata.db', 'rb') as f:
819-
for block in iter(partial(f.read, 64), ''):
819+
for block in iter(partial(f.read, 64), b''):
820820
process_block(block)
821821

822822

Doc/library/gc.rst

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,11 +63,14 @@ The :mod:`gc` module provides the following functions:
6363
Return the debugging flags currently set.
6464

6565

66-
.. function:: get_objects()
66+
.. function:: get_objects(generation=None)
6767

6868
Returns a list of all objects tracked by the collector, excluding the list
69-
returned.
69+
returned. If *generation* is not None, return only the objects tracked by
70+
the collector that are in that generation.
7071

72+
.. versionchanged:: 3.8
73+
New *generation* parameter.
7174

7275
.. function:: get_stats()
7376

Doc/library/random.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -404,7 +404,7 @@ with replacement to estimate a confidence interval for the mean of a sample of
404404
size five::
405405

406406
# http://statistics.about.com/od/Applications/a/Example-Of-Bootstrapping.htm
407-
from statistics import mean
407+
from statistics import fmean as mean
408408
from random import choices
409409

410410
data = 1, 2, 4, 4, 10
@@ -419,7 +419,7 @@ to determine the statistical significance or `p-value
419419
between the effects of a drug versus a placebo::
420420

421421
# Example from "Statistics is Easy" by Dennis Shasha and Manda Wilson
422-
from statistics import mean
422+
from statistics import fmean as mean
423423
from random import shuffle
424424

425425
drug = [54, 73, 53, 70, 73, 68, 52, 65, 65]

Doc/library/statistics.rst

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ or sample.
3939

4040
======================= =============================================
4141
:func:`mean` Arithmetic mean ("average") of data.
42+
:func:`fmean` Fast, floating point arithmetic mean.
4243
:func:`harmonic_mean` Harmonic mean of data.
4344
:func:`median` Median (middle value) of data.
4445
:func:`median_low` Low median of data.
@@ -111,6 +112,23 @@ However, for reading convenience, most of the examples show sorted sequences.
111112
``mean(data)`` is equivalent to calculating the true population mean μ.
112113

113114

115+
.. function:: fmean(data)
116+
117+
Convert *data* to floats and compute the arithmetic mean.
118+
119+
This runs faster than the :func:`mean` function and it always returns a
120+
:class:`float`. The result is highly accurate but not as perfect as
121+
:func:`mean`. If the input dataset is empty, raises a
122+
:exc:`StatisticsError`.
123+
124+
.. doctest::
125+
126+
>>> fmean([3.5, 4.0, 5.25])
127+
4.25
128+
129+
.. versionadded:: 3.8
130+
131+
114132
.. function:: harmonic_mean(data)
115133

116134
Return the harmonic mean of *data*, a sequence or iterator of

Doc/library/test.rst

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -356,6 +356,10 @@ The :mod:`test.support` module defines the following constants:
356356

357357
Check for presence of docstrings.
358358

359+
.. data:: TEST_HTTP_URL
360+
361+
Define the URL of a dedicated HTTP server for the network tests.
362+
359363

360364

361365
The :mod:`test.support` module defines the following functions:
@@ -936,9 +940,24 @@ The :mod:`test.support` module defines the following functions:
936940

937941
Test for syntax errors in *statement* by attempting to compile *statement*.
938942
*testcase* is the :mod:`unittest` instance for the test. *errtext* is the
939-
text of the error raised by :exc:`SyntaxError`. If *lineno* is not None,
940-
compares to the line of the :exc:`SyntaxError`. If *offset* is not None,
941-
compares to the offset of the :exc:`SyntaxError`.
943+
regular expression which should match the string representation of the
944+
raised :exc:`SyntaxError`. If *lineno* is not ``None``, compares to
945+
the line of the exception. If *offset* is not ``None``, compares to
946+
the offset of the exception.
947+
948+
949+
.. function:: check_syntax_warning(testcase, statement, errtext='', *, lineno=1, offset=None)
950+
951+
Test for syntax warning in *statement* by attempting to compile *statement*.
952+
Test also that the :exc:`SyntaxWarning` is emitted only once, and that it
953+
will be converted to a :exc:`SyntaxError` when turned into error.
954+
*testcase* is the :mod:`unittest` instance for the test. *errtext* is the
955+
regular expression which should match the string representation of the
956+
emitted :exc:`SyntaxWarning` and raised :exc:`SyntaxError`. If *lineno*
957+
is not ``None``, compares to the line of the warning and exception.
958+
If *offset* is not ``None``, compares to the offset of the exception.
959+
960+
.. versionadded:: 3.8
942961

943962

944963
.. function:: open_urlresource(url, *args, **kw)

Doc/library/unittest.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ object-oriented way:
2727

2828
test fixture
2929
A :dfn:`test fixture` represents the preparation needed to perform one or more
30-
tests, and any associate cleanup actions. This may involve, for example,
30+
tests, and any associated cleanup actions. This may involve, for example,
3131
creating temporary or proxy databases, directories, or starting a server
3232
process.
3333

@@ -2083,7 +2083,7 @@ Loading and running tests
20832083

20842084
.. method:: run(test)
20852085

2086-
This method is the main public interface to the `TextTestRunner`. This
2086+
This method is the main public interface to the ``TextTestRunner``. This
20872087
method takes a :class:`TestSuite` or :class:`TestCase` instance. A
20882088
:class:`TestResult` is created by calling
20892089
:func:`_makeResult` and the test(s) are run and the

Doc/library/xml.etree.elementtree.rst

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -494,10 +494,12 @@ Functions
494494
by the user.
495495

496496

497-
.. function:: fromstring(text)
497+
.. function:: fromstring(text, parser=None)
498498

499499
Parses an XML section from a string constant. Same as :func:`XML`. *text*
500-
is a string containing XML data. Returns an :class:`Element` instance.
500+
is a string containing XML data. *parser* is an optional parser instance.
501+
If not given, the standard :class:`XMLParser` parser is used.
502+
Returns an :class:`Element` instance.
501503

502504

503505
.. function:: fromstringlist(sequence, parser=None)

0 commit comments

Comments
 (0)