aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/Doc/library
diff options
context:
space:
mode:
Diffstat (limited to 'Doc/library')
-rw-r--r--Doc/library/annotationlib.rst4
-rw-r--r--Doc/library/archiving.rst4
-rw-r--r--Doc/library/argparse.rst17
-rw-r--r--Doc/library/ast.rst303
-rw-r--r--Doc/library/asyncio-dev.rst4
-rw-r--r--Doc/library/asyncio-eventloop.rst25
-rw-r--r--Doc/library/asyncio-stream.rst9
-rw-r--r--Doc/library/asyncio-task.rst21
-rw-r--r--Doc/library/base64.rst48
-rw-r--r--Doc/library/calendar.rst2
-rw-r--r--Doc/library/code.rst6
-rw-r--r--Doc/library/codecs.rst8
-rw-r--r--Doc/library/compileall.rst13
-rw-r--r--Doc/library/compression.rst18
-rw-r--r--Doc/library/compression.zstd.rst891
-rw-r--r--Doc/library/concurrency.rst1
-rw-r--r--Doc/library/concurrent.futures.rst19
-rw-r--r--Doc/library/concurrent.interpreters.rst387
-rw-r--r--Doc/library/concurrent.rst3
-rw-r--r--Doc/library/copy.rst2
-rw-r--r--Doc/library/csv.rst54
-rw-r--r--Doc/library/ctypes.rst68
-rw-r--r--Doc/library/curses.rst10
-rw-r--r--Doc/library/dataclasses.rst11
-rw-r--r--Doc/library/datetime.rst14
-rw-r--r--Doc/library/dbm.rst43
-rw-r--r--Doc/library/decimal.rst72
-rw-r--r--Doc/library/dialog.rst2
-rw-r--r--Doc/library/dis.rst8
-rw-r--r--Doc/library/doctest.rst133
-rw-r--r--Doc/library/email.header.rst34
-rw-r--r--Doc/library/exceptions.rst2
-rw-r--r--Doc/library/faulthandler.rst39
-rw-r--r--Doc/library/functions.rst86
-rw-r--r--Doc/library/hashlib.rst9
-rw-r--r--Doc/library/http.server.rst70
-rw-r--r--Doc/library/importlib.resources.abc.rst48
-rw-r--r--Doc/library/io.rst92
-rw-r--r--Doc/library/json.rst15
-rw-r--r--Doc/library/logging.config.rst4
-rw-r--r--Doc/library/logging.handlers.rst19
-rw-r--r--Doc/library/logging.rst21
-rw-r--r--Doc/library/math.rst36
-rw-r--r--Doc/library/mmap.rst2
-rw-r--r--Doc/library/multiprocessing.rst22
-rw-r--r--Doc/library/netrc.rst4
-rw-r--r--Doc/library/os.path.rst32
-rw-r--r--Doc/library/pathlib.rst9
-rw-r--r--Doc/library/pdb.rst20
-rw-r--r--Doc/library/pkgutil.rst4
-rw-r--r--Doc/library/platform.rst18
-rw-r--r--Doc/library/python.rst5
-rw-r--r--Doc/library/re.rst16
-rw-r--r--Doc/library/shelve.rst16
-rw-r--r--Doc/library/shutil.rst11
-rw-r--r--Doc/library/signal.rst4
-rw-r--r--Doc/library/socket.rst16
-rw-r--r--Doc/library/socketserver.rst4
-rw-r--r--Doc/library/sqlite3.rst31
-rw-r--r--Doc/library/stdtypes.rst68
-rw-r--r--Doc/library/string.rst2
-rw-r--r--Doc/library/sys.rst28
-rw-r--r--Doc/library/tarfile.rst20
-rw-r--r--Doc/library/threading.rst116
-rw-r--r--Doc/library/time.rst7
-rw-r--r--Doc/library/token.rst2
-rw-r--r--Doc/library/typing.rst47
-rw-r--r--Doc/library/unittest.rst2
-rw-r--r--Doc/library/uuid.rst33
-rw-r--r--Doc/library/venv.rst70
-rw-r--r--Doc/library/wave.rst20
-rw-r--r--Doc/library/zlib.rst28
-rw-r--r--Doc/library/zoneinfo.rst4
73 files changed, 2587 insertions, 749 deletions
diff --git a/Doc/library/annotationlib.rst b/Doc/library/annotationlib.rst
index 41c9ce479ff..7dfc11449a6 100644
--- a/Doc/library/annotationlib.rst
+++ b/Doc/library/annotationlib.rst
@@ -211,6 +211,10 @@ Classes
means may not have any information about their scope, so passing
arguments to this method may be necessary to evaluate them successfully.
+ If no *owner*, *globals*, *locals*, or *type_params* are provided and the
+ :class:`~ForwardRef` does not contain information about its origin,
+ empty globals and locals dictionaries are used.
+
.. versionadded:: 3.14
diff --git a/Doc/library/archiving.rst b/Doc/library/archiving.rst
index c9284949af4..da0b3f8c3e7 100644
--- a/Doc/library/archiving.rst
+++ b/Doc/library/archiving.rst
@@ -5,13 +5,15 @@ Data Compression and Archiving
******************************
The modules described in this chapter support data compression with the zlib,
-gzip, bzip2 and lzma algorithms, and the creation of ZIP- and tar-format
+gzip, bzip2, lzma, and zstd algorithms, and the creation of ZIP- and tar-format
archives. See also :ref:`archiving-operations` provided by the :mod:`shutil`
module.
.. toctree::
+ compression.rst
+ compression.zstd.rst
zlib.rst
gzip.rst
bz2.rst
diff --git a/Doc/library/argparse.rst b/Doc/library/argparse.rst
index 29396c7a036..a03d88092db 100644
--- a/Doc/library/argparse.rst
+++ b/Doc/library/argparse.rst
@@ -955,7 +955,7 @@ See also :ref:`specifying-ambiguous-arguments`. The supported values are:
.. index:: single: + (plus); in argparse module
-* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
+* ``'+'``. Just like ``'*'``, all command-line arguments present are gathered into a
list. Additionally, an error message will be generated if there wasn't at
least one command-line argument present. For example::
@@ -2122,12 +2122,15 @@ Partial parsing
.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
- Sometimes a script may only parse a few of the command-line arguments, passing
- the remaining arguments on to another script or program. In these cases, the
- :meth:`~ArgumentParser.parse_known_args` method can be useful. It works much like
- :meth:`~ArgumentParser.parse_args` except that it does not produce an error when
- extra arguments are present. Instead, it returns a two item tuple containing
- the populated namespace and the list of remaining argument strings.
+ Sometimes a script only needs to handle a specific set of command-line
+ arguments, leaving any unrecognized arguments for another script or program.
+ In these cases, the :meth:`~ArgumentParser.parse_known_args` method can be
+ useful.
+
+ This method works similarly to :meth:`~ArgumentParser.parse_args`, but it does
+ not raise an error for extra, unrecognized arguments. Instead, it parses the
+ known arguments and returns a two item tuple that contains the populated
+ namespace and the list of any unrecognized arguments.
::
diff --git a/Doc/library/ast.rst b/Doc/library/ast.rst
index ca9a6b0712c..ef6c62dca1e 100644
--- a/Doc/library/ast.rst
+++ b/Doc/library/ast.rst
@@ -252,12 +252,11 @@ Root nodes
>>> print(ast.dump(ast.parse('(int, str) -> List[int]', mode='func_type'), indent=4))
FunctionType(
argtypes=[
- Name(id='int', ctx=Load()),
- Name(id='str', ctx=Load())],
+ Name(id='int'),
+ Name(id='str')],
returns=Subscript(
- value=Name(id='List', ctx=Load()),
- slice=Name(id='int', ctx=Load()),
- ctx=Load()))
+ value=Name(id='List'),
+ slice=Name(id='int')))
.. versionadded:: 3.8
@@ -268,9 +267,9 @@ Literals
.. class:: Constant(value)
A constant value. The ``value`` attribute of the ``Constant`` literal contains the
- Python object it represents. The values represented can be simple types
- such as a number, string or ``None``, but also immutable container types
- (tuples and frozensets) if all of their elements are constant.
+ Python object it represents. The values represented can be instances of :class:`str`,
+ :class:`bytes`, :class:`int`, :class:`float`, :class:`complex`, and :class:`bool`,
+ and the constants :data:`None` and :data:`Ellipsis`.
.. doctest::
@@ -312,14 +311,14 @@ Literals
values=[
Constant(value='sin('),
FormattedValue(
- value=Name(id='a', ctx=Load()),
+ value=Name(id='a'),
conversion=-1),
Constant(value=') is '),
FormattedValue(
value=Call(
- func=Name(id='sin', ctx=Load()),
+ func=Name(id='sin'),
args=[
- Name(id='a', ctx=Load())]),
+ Name(id='a')]),
conversion=-1,
format_spec=JoinedStr(
values=[
@@ -341,16 +340,14 @@ Literals
elts=[
Constant(value=1),
Constant(value=2),
- Constant(value=3)],
- ctx=Load()))
+ Constant(value=3)]))
>>> print(ast.dump(ast.parse('(1, 2, 3)', mode='eval'), indent=4))
Expression(
body=Tuple(
elts=[
Constant(value=1),
Constant(value=2),
- Constant(value=3)],
- ctx=Load()))
+ Constant(value=3)]))
.. class:: Set(elts)
@@ -388,7 +385,7 @@ Literals
None],
values=[
Constant(value=1),
- Name(id='d', ctx=Load())]))
+ Name(id='d')]))
Variables
@@ -414,7 +411,7 @@ Variables
Module(
body=[
Expr(
- value=Name(id='a', ctx=Load()))])
+ value=Name(id='a'))])
>>> print(ast.dump(ast.parse('a = 1'), indent=4))
Module(
@@ -452,7 +449,7 @@ Variables
value=Name(id='b', ctx=Store()),
ctx=Store())],
ctx=Store())],
- value=Name(id='it', ctx=Load()))])
+ value=Name(id='it'))])
.. _ast-expressions:
@@ -475,7 +472,7 @@ Expressions
Expr(
value=UnaryOp(
op=USub(),
- operand=Name(id='a', ctx=Load())))])
+ operand=Name(id='a')))])
.. class:: UnaryOp(op, operand)
@@ -498,7 +495,7 @@ Expressions
Expression(
body=UnaryOp(
op=Not(),
- operand=Name(id='x', ctx=Load())))
+ operand=Name(id='x')))
.. class:: BinOp(left, op, right)
@@ -511,9 +508,9 @@ Expressions
>>> print(ast.dump(ast.parse('x + y', mode='eval'), indent=4))
Expression(
body=BinOp(
- left=Name(id='x', ctx=Load()),
+ left=Name(id='x'),
op=Add(),
- right=Name(id='y', ctx=Load())))
+ right=Name(id='y')))
.. class:: Add
@@ -549,8 +546,8 @@ Expressions
body=BoolOp(
op=Or(),
values=[
- Name(id='x', ctx=Load()),
- Name(id='y', ctx=Load())]))
+ Name(id='x'),
+ Name(id='y')]))
.. class:: And
@@ -575,7 +572,7 @@ Expressions
LtE(),
Lt()],
comparators=[
- Name(id='a', ctx=Load()),
+ Name(id='a'),
Constant(value=10)]))
@@ -609,18 +606,17 @@ Expressions
>>> print(ast.dump(ast.parse('func(a, b=c, *d, **e)', mode='eval'), indent=4))
Expression(
body=Call(
- func=Name(id='func', ctx=Load()),
+ func=Name(id='func'),
args=[
- Name(id='a', ctx=Load()),
+ Name(id='a'),
Starred(
- value=Name(id='d', ctx=Load()),
- ctx=Load())],
+ value=Name(id='d'))],
keywords=[
keyword(
arg='b',
- value=Name(id='c', ctx=Load())),
+ value=Name(id='c')),
keyword(
- value=Name(id='e', ctx=Load()))]))
+ value=Name(id='e'))]))
.. class:: keyword(arg, value)
@@ -639,9 +635,9 @@ Expressions
>>> print(ast.dump(ast.parse('a if b else c', mode='eval'), indent=4))
Expression(
body=IfExp(
- test=Name(id='b', ctx=Load()),
- body=Name(id='a', ctx=Load()),
- orelse=Name(id='c', ctx=Load())))
+ test=Name(id='b'),
+ body=Name(id='a'),
+ orelse=Name(id='c')))
.. class:: Attribute(value, attr, ctx)
@@ -656,9 +652,8 @@ Expressions
>>> print(ast.dump(ast.parse('snake.colour', mode='eval'), indent=4))
Expression(
body=Attribute(
- value=Name(id='snake', ctx=Load()),
- attr='colour',
- ctx=Load()))
+ value=Name(id='snake'),
+ attr='colour'))
.. class:: NamedExpr(target, value)
@@ -694,15 +689,13 @@ Subscripting
>>> print(ast.dump(ast.parse('l[1:2, 3]', mode='eval'), indent=4))
Expression(
body=Subscript(
- value=Name(id='l', ctx=Load()),
+ value=Name(id='l'),
slice=Tuple(
elts=[
Slice(
lower=Constant(value=1),
upper=Constant(value=2)),
- Constant(value=3)],
- ctx=Load()),
- ctx=Load()))
+ Constant(value=3)])))
.. class:: Slice(lower, upper, step)
@@ -716,11 +709,10 @@ Subscripting
>>> print(ast.dump(ast.parse('l[1:2]', mode='eval'), indent=4))
Expression(
body=Subscript(
- value=Name(id='l', ctx=Load()),
+ value=Name(id='l'),
slice=Slice(
lower=Constant(value=1),
- upper=Constant(value=2)),
- ctx=Load()))
+ upper=Constant(value=2))))
Comprehensions
@@ -745,11 +737,11 @@ Comprehensions
... ))
Expression(
body=ListComp(
- elt=Name(id='x', ctx=Load()),
+ elt=Name(id='x'),
generators=[
comprehension(
target=Name(id='x', ctx=Store()),
- iter=Name(id='numbers', ctx=Load()),
+ iter=Name(id='numbers'),
is_async=0)]))
>>> print(ast.dump(
... ast.parse('{x: x**2 for x in numbers}', mode='eval'),
@@ -757,15 +749,15 @@ Comprehensions
... ))
Expression(
body=DictComp(
- key=Name(id='x', ctx=Load()),
+ key=Name(id='x'),
value=BinOp(
- left=Name(id='x', ctx=Load()),
+ left=Name(id='x'),
op=Pow(),
right=Constant(value=2)),
generators=[
comprehension(
target=Name(id='x', ctx=Store()),
- iter=Name(id='numbers', ctx=Load()),
+ iter=Name(id='numbers'),
is_async=0)]))
>>> print(ast.dump(
... ast.parse('{x for x in numbers}', mode='eval'),
@@ -773,11 +765,11 @@ Comprehensions
... ))
Expression(
body=SetComp(
- elt=Name(id='x', ctx=Load()),
+ elt=Name(id='x'),
generators=[
comprehension(
target=Name(id='x', ctx=Store()),
- iter=Name(id='numbers', ctx=Load()),
+ iter=Name(id='numbers'),
is_async=0)]))
@@ -798,17 +790,17 @@ Comprehensions
Expression(
body=ListComp(
elt=Call(
- func=Name(id='ord', ctx=Load()),
+ func=Name(id='ord'),
args=[
- Name(id='c', ctx=Load())]),
+ Name(id='c')]),
generators=[
comprehension(
target=Name(id='line', ctx=Store()),
- iter=Name(id='file', ctx=Load()),
+ iter=Name(id='file'),
is_async=0),
comprehension(
target=Name(id='c', ctx=Store()),
- iter=Name(id='line', ctx=Load()),
+ iter=Name(id='line'),
is_async=0)]))
>>> print(ast.dump(ast.parse('(n**2 for n in it if n>5 if n<10)', mode='eval'),
@@ -816,22 +808,22 @@ Comprehensions
Expression(
body=GeneratorExp(
elt=BinOp(
- left=Name(id='n', ctx=Load()),
+ left=Name(id='n'),
op=Pow(),
right=Constant(value=2)),
generators=[
comprehension(
target=Name(id='n', ctx=Store()),
- iter=Name(id='it', ctx=Load()),
+ iter=Name(id='it'),
ifs=[
Compare(
- left=Name(id='n', ctx=Load()),
+ left=Name(id='n'),
ops=[
Gt()],
comparators=[
Constant(value=5)]),
Compare(
- left=Name(id='n', ctx=Load()),
+ left=Name(id='n'),
ops=[
Lt()],
comparators=[
@@ -842,11 +834,11 @@ Comprehensions
... indent=4)) # Async comprehension
Expression(
body=ListComp(
- elt=Name(id='i', ctx=Load()),
+ elt=Name(id='i'),
generators=[
comprehension(
target=Name(id='i', ctx=Store()),
- iter=Name(id='soc', ctx=Load()),
+ iter=Name(id='soc'),
is_async=1)]))
@@ -888,7 +880,7 @@ Statements
Name(id='a', ctx=Store()),
Name(id='b', ctx=Store())],
ctx=Store())],
- value=Name(id='c', ctx=Load()))])
+ value=Name(id='c'))])
.. class:: AnnAssign(target, annotation, value, simple)
@@ -911,7 +903,7 @@ Statements
body=[
AnnAssign(
target=Name(id='c', ctx=Store()),
- annotation=Name(id='int', ctx=Load()),
+ annotation=Name(id='int'),
simple=1)])
>>> print(ast.dump(ast.parse('(a): int = 1'), indent=4)) # Annotation with parenthesis
@@ -919,7 +911,7 @@ Statements
body=[
AnnAssign(
target=Name(id='a', ctx=Store()),
- annotation=Name(id='int', ctx=Load()),
+ annotation=Name(id='int'),
value=Constant(value=1),
simple=0)])
@@ -928,10 +920,10 @@ Statements
body=[
AnnAssign(
target=Attribute(
- value=Name(id='a', ctx=Load()),
+ value=Name(id='a'),
attr='b',
ctx=Store()),
- annotation=Name(id='int', ctx=Load()),
+ annotation=Name(id='int'),
simple=0)])
>>> print(ast.dump(ast.parse('a[1]: int'), indent=4)) # Subscript annotation
@@ -939,10 +931,10 @@ Statements
body=[
AnnAssign(
target=Subscript(
- value=Name(id='a', ctx=Load()),
+ value=Name(id='a'),
slice=Constant(value=1),
ctx=Store()),
- annotation=Name(id='int', ctx=Load()),
+ annotation=Name(id='int'),
simple=0)])
@@ -979,8 +971,8 @@ Statements
Module(
body=[
Raise(
- exc=Name(id='x', ctx=Load()),
- cause=Name(id='y', ctx=Load()))])
+ exc=Name(id='x'),
+ cause=Name(id='y'))])
.. class:: Assert(test, msg)
@@ -994,8 +986,8 @@ Statements
Module(
body=[
Assert(
- test=Name(id='x', ctx=Load()),
- msg=Name(id='y', ctx=Load()))])
+ test=Name(id='x'),
+ msg=Name(id='y'))])
.. class:: Delete(targets)
@@ -1041,7 +1033,7 @@ Statements
body=[
TypeAlias(
name=Name(id='Alias', ctx=Store()),
- value=Name(id='int', ctx=Load()))])
+ value=Name(id='int'))])
.. versionadded:: 3.12
@@ -1134,13 +1126,13 @@ Control flow
Module(
body=[
If(
- test=Name(id='x', ctx=Load()),
+ test=Name(id='x'),
body=[
Expr(
value=Constant(value=Ellipsis))],
orelse=[
If(
- test=Name(id='y', ctx=Load()),
+ test=Name(id='y'),
body=[
Expr(
value=Constant(value=Ellipsis))],
@@ -1174,7 +1166,7 @@ Control flow
body=[
For(
target=Name(id='x', ctx=Store()),
- iter=Name(id='y', ctx=Load()),
+ iter=Name(id='y'),
body=[
Expr(
value=Constant(value=Ellipsis))],
@@ -1199,7 +1191,7 @@ Control flow
Module(
body=[
While(
- test=Name(id='x', ctx=Load()),
+ test=Name(id='x'),
body=[
Expr(
value=Constant(value=Ellipsis))],
@@ -1227,11 +1219,11 @@ Control flow
body=[
For(
target=Name(id='a', ctx=Store()),
- iter=Name(id='b', ctx=Load()),
+ iter=Name(id='b'),
body=[
If(
test=Compare(
- left=Name(id='a', ctx=Load()),
+ left=Name(id='a'),
ops=[
Gt()],
comparators=[
@@ -1269,12 +1261,12 @@ Control flow
value=Constant(value=Ellipsis))],
handlers=[
ExceptHandler(
- type=Name(id='Exception', ctx=Load()),
+ type=Name(id='Exception'),
body=[
Expr(
value=Constant(value=Ellipsis))]),
ExceptHandler(
- type=Name(id='OtherException', ctx=Load()),
+ type=Name(id='OtherException'),
name='e',
body=[
Expr(
@@ -1309,7 +1301,7 @@ Control flow
value=Constant(value=Ellipsis))],
handlers=[
ExceptHandler(
- type=Name(id='Exception', ctx=Load()),
+ type=Name(id='Exception'),
body=[
Expr(
value=Constant(value=Ellipsis))])])])
@@ -1337,12 +1329,12 @@ Control flow
body=[
Expr(
value=BinOp(
- left=Name(id='a', ctx=Load()),
+ left=Name(id='a'),
op=Add(),
right=Constant(value=1)))],
handlers=[
ExceptHandler(
- type=Name(id='TypeError', ctx=Load()),
+ type=Name(id='TypeError'),
body=[
Pass()])])])
@@ -1375,18 +1367,18 @@ Control flow
With(
items=[
withitem(
- context_expr=Name(id='a', ctx=Load()),
+ context_expr=Name(id='a'),
optional_vars=Name(id='b', ctx=Store())),
withitem(
- context_expr=Name(id='c', ctx=Load()),
+ context_expr=Name(id='c'),
optional_vars=Name(id='d', ctx=Store()))],
body=[
Expr(
value=Call(
- func=Name(id='something', ctx=Load()),
+ func=Name(id='something'),
args=[
- Name(id='b', ctx=Load()),
- Name(id='d', ctx=Load())]))])])
+ Name(id='b'),
+ Name(id='d')]))])])
Pattern matching
@@ -1426,14 +1418,14 @@ Pattern matching
Module(
body=[
Match(
- subject=Name(id='x', ctx=Load()),
+ subject=Name(id='x'),
cases=[
match_case(
pattern=MatchSequence(
patterns=[
MatchAs(name='x')]),
guard=Compare(
- left=Name(id='x', ctx=Load()),
+ left=Name(id='x'),
ops=[
Gt()],
comparators=[
@@ -1443,7 +1435,7 @@ Pattern matching
value=Constant(value=Ellipsis))]),
match_case(
pattern=MatchClass(
- cls=Name(id='tuple', ctx=Load())),
+ cls=Name(id='tuple')),
body=[
Expr(
value=Constant(value=Ellipsis))])])])
@@ -1467,7 +1459,7 @@ Pattern matching
Module(
body=[
Match(
- subject=Name(id='x', ctx=Load()),
+ subject=Name(id='x'),
cases=[
match_case(
pattern=MatchValue(
@@ -1494,7 +1486,7 @@ Pattern matching
Module(
body=[
Match(
- subject=Name(id='x', ctx=Load()),
+ subject=Name(id='x'),
cases=[
match_case(
pattern=MatchSingleton(value=None),
@@ -1521,7 +1513,7 @@ Pattern matching
Module(
body=[
Match(
- subject=Name(id='x', ctx=Load()),
+ subject=Name(id='x'),
cases=[
match_case(
pattern=MatchSequence(
@@ -1554,7 +1546,7 @@ Pattern matching
Module(
body=[
Match(
- subject=Name(id='x', ctx=Load()),
+ subject=Name(id='x'),
cases=[
match_case(
pattern=MatchSequence(
@@ -1603,7 +1595,7 @@ Pattern matching
Module(
body=[
Match(
- subject=Name(id='x', ctx=Load()),
+ subject=Name(id='x'),
cases=[
match_case(
pattern=MatchMapping(
@@ -1653,11 +1645,11 @@ Pattern matching
Module(
body=[
Match(
- subject=Name(id='x', ctx=Load()),
+ subject=Name(id='x'),
cases=[
match_case(
pattern=MatchClass(
- cls=Name(id='Point2D', ctx=Load()),
+ cls=Name(id='Point2D'),
patterns=[
MatchValue(
value=Constant(value=0)),
@@ -1668,7 +1660,7 @@ Pattern matching
value=Constant(value=Ellipsis))]),
match_case(
pattern=MatchClass(
- cls=Name(id='Point3D', ctx=Load()),
+ cls=Name(id='Point3D'),
kwd_attrs=[
'x',
'y',
@@ -1709,7 +1701,7 @@ Pattern matching
Module(
body=[
Match(
- subject=Name(id='x', ctx=Load()),
+ subject=Name(id='x'),
cases=[
match_case(
pattern=MatchAs(
@@ -1746,7 +1738,7 @@ Pattern matching
Module(
body=[
Match(
- subject=Name(id='x', ctx=Load()),
+ subject=Name(id='x'),
cases=[
match_case(
pattern=MatchOr(
@@ -1786,7 +1778,7 @@ Type annotations
body=[
AnnAssign(
target=Name(id='x', ctx=Store()),
- annotation=Name(id='bool', ctx=Load()),
+ annotation=Name(id='bool'),
value=Constant(value=1),
simple=1)],
type_ignores=[
@@ -1824,12 +1816,11 @@ aliases.
type_params=[
TypeVar(
name='T',
- bound=Name(id='int', ctx=Load()),
- default_value=Name(id='bool', ctx=Load()))],
+ bound=Name(id='int'),
+ default_value=Name(id='bool'))],
value=Subscript(
- value=Name(id='list', ctx=Load()),
- slice=Name(id='T', ctx=Load()),
- ctx=Load()))])
+ value=Name(id='list'),
+ slice=Name(id='T')))])
.. versionadded:: 3.12
@@ -1854,17 +1845,14 @@ aliases.
name='P',
default_value=List(
elts=[
- Name(id='int', ctx=Load()),
- Name(id='str', ctx=Load())],
- ctx=Load()))],
+ Name(id='int'),
+ Name(id='str')]))],
value=Subscript(
- value=Name(id='Callable', ctx=Load()),
+ value=Name(id='Callable'),
slice=Tuple(
elts=[
- Name(id='P', ctx=Load()),
- Name(id='int', ctx=Load())],
- ctx=Load()),
- ctx=Load()))])
+ Name(id='P'),
+ Name(id='int')])))])
.. versionadded:: 3.12
@@ -1885,18 +1873,13 @@ aliases.
TypeAlias(
name=Name(id='Alias', ctx=Store()),
type_params=[
- TypeVarTuple(
- name='Ts',
- default_value=Tuple(ctx=Load()))],
+ TypeVarTuple(name='Ts', default_value=Tuple())],
value=Subscript(
- value=Name(id='tuple', ctx=Load()),
+ value=Name(id='tuple'),
slice=Tuple(
elts=[
Starred(
- value=Name(id='Ts', ctx=Load()),
- ctx=Load())],
- ctx=Load()),
- ctx=Load()))])
+ value=Name(id='Ts'))])))])
.. versionadded:: 3.12
@@ -2001,8 +1984,8 @@ Function and class definitions
body=[
Pass()],
decorator_list=[
- Name(id='decorator1', ctx=Load()),
- Name(id='decorator2', ctx=Load())],
+ Name(id='decorator1'),
+ Name(id='decorator2')],
returns=Constant(value='return annotation'))])
@@ -2032,14 +2015,14 @@ Function and class definitions
body=[
Expr(
value=Yield(
- value=Name(id='x', ctx=Load())))])
+ value=Name(id='x')))])
>>> print(ast.dump(ast.parse('yield from x'), indent=4))
Module(
body=[
Expr(
value=YieldFrom(
- value=Name(id='x', ctx=Load())))])
+ value=Name(id='x')))])
.. class:: Global(names)
@@ -2094,17 +2077,17 @@ Function and class definitions
ClassDef(
name='Foo',
bases=[
- Name(id='base1', ctx=Load()),
- Name(id='base2', ctx=Load())],
+ Name(id='base1'),
+ Name(id='base2')],
keywords=[
keyword(
arg='metaclass',
- value=Name(id='meta', ctx=Load()))],
+ value=Name(id='meta'))],
body=[
Pass()],
decorator_list=[
- Name(id='decorator1', ctx=Load()),
- Name(id='decorator2', ctx=Load())])])
+ Name(id='decorator1'),
+ Name(id='decorator2')])])
.. versionchanged:: 3.12
Added ``type_params``.
@@ -2141,7 +2124,7 @@ Async and await
Expr(
value=Await(
value=Call(
- func=Name(id='other_func', ctx=Load()))))])])
+ func=Name(id='other_func'))))])])
.. class:: AsyncFor(target, iter, body, orelse, type_comment)
@@ -2402,7 +2385,7 @@ and classes for traversing abstract syntax trees:
def visit_Name(self, node):
return Subscript(
- value=Name(id='data', ctx=Load()),
+ value=Name(id='data'),
slice=Constant(value=node.id),
ctx=node.ctx
)
@@ -2445,8 +2428,26 @@ and classes for traversing abstract syntax trees:
indents that many spaces per level. If *indent* is a string (such as ``"\t"``),
that string is used to indent each level.
- If *show_empty* is ``False`` (the default), empty lists and fields that are ``None``
- will be omitted from the output.
+ If *show_empty* is false (the default), optional empty lists and
+ ``Load()`` values will be omitted from the output.
+ Optional ``None`` values are always omitted.
+
+ .. doctest::
+
+ >>> tree = ast.parse('print(None)', '?', 'eval')
+ >>> print(ast.dump(tree, indent=4))
+ Expression(
+ body=Call(
+ func=Name(id='print'),
+ args=[
+ Constant(value=None)]))
+ >>> print(ast.dump(tree, indent=4, show_empty=True))
+ Expression(
+ body=Call(
+ func=Name(id='print', ctx=Load()),
+ args=[
+ Constant(value=None)],
+ keywords=[]))
.. versionchanged:: 3.9
Added the *indent* option.
@@ -2454,32 +2455,8 @@ and classes for traversing abstract syntax trees:
.. versionchanged:: 3.13
Added the *show_empty* option.
- .. doctest::
-
- >>> print(ast.dump(ast.parse("""\
- ... async def f():
- ... await other_func()
- ... """), indent=4, show_empty=True))
- Module(
- body=[
- AsyncFunctionDef(
- name='f',
- args=arguments(
- posonlyargs=[],
- args=[],
- kwonlyargs=[],
- kw_defaults=[],
- defaults=[]),
- body=[
- Expr(
- value=Await(
- value=Call(
- func=Name(id='other_func', ctx=Load()),
- args=[],
- keywords=[])))],
- decorator_list=[],
- type_params=[])],
- type_ignores=[])
+ .. versionchanged:: next
+ Omit optional ``Load()`` values by default.
.. _ast-compiler-flags:
diff --git a/Doc/library/asyncio-dev.rst b/Doc/library/asyncio-dev.rst
index 44b507a9811..7831b613bd4 100644
--- a/Doc/library/asyncio-dev.rst
+++ b/Doc/library/asyncio-dev.rst
@@ -46,10 +46,6 @@ In addition to enabling the debug mode, consider also:
When the debug mode is enabled:
-* asyncio checks for :ref:`coroutines that were not awaited
- <asyncio-coroutine-not-scheduled>` and logs them; this mitigates
- the "forgotten await" pitfall.
-
* Many non-threadsafe asyncio APIs (such as :meth:`loop.call_soon` and
:meth:`loop.call_at` methods) raise an exception if they are called
from a wrong thread.
diff --git a/Doc/library/asyncio-eventloop.rst b/Doc/library/asyncio-eventloop.rst
index 21f7d0547af..91970c28239 100644
--- a/Doc/library/asyncio-eventloop.rst
+++ b/Doc/library/asyncio-eventloop.rst
@@ -361,7 +361,7 @@ Creating Futures and Tasks
.. versionadded:: 3.5.2
-.. method:: loop.create_task(coro, *, name=None, context=None, eager_start=None)
+.. method:: loop.create_task(coro, *, name=None, context=None, eager_start=None, **kwargs)
Schedule the execution of :ref:`coroutine <coroutine>` *coro*.
Return a :class:`Task` object.
@@ -370,6 +370,10 @@ Creating Futures and Tasks
for interoperability. In this case, the result type is a subclass
of :class:`Task`.
+ The full function signature is largely the same as that of the
+ :class:`Task` constructor (or factory) - all of the keyword arguments to
+ this function are passed through to that interface.
+
If the *name* argument is provided and not ``None``, it is set as
the name of the task using :meth:`Task.set_name`.
@@ -388,8 +392,15 @@ Creating Futures and Tasks
.. versionchanged:: 3.11
Added the *context* parameter.
+ .. versionchanged:: 3.13.3
+ Added ``kwargs`` which passes on arbitrary extra parameters, including ``name`` and ``context``.
+
+ .. versionchanged:: 3.13.4
+ Rolled back the change that passes on *name* and *context* (if it is None),
+ while still passing on other arbitrary keyword arguments (to avoid breaking backwards compatibility with 3.13.3).
+
.. versionchanged:: 3.14
- Added the *eager_start* parameter.
+ All *kwargs* are now passed on. The *eager_start* parameter works with eager task factories.
.. method:: loop.set_task_factory(factory)
@@ -402,6 +413,16 @@ Creating Futures and Tasks
event loop, and *coro* is a coroutine object. The callable
must pass on all *kwargs*, and return a :class:`asyncio.Task`-compatible object.
+ .. versionchanged:: 3.13.3
+ Required that all *kwargs* are passed on to :class:`asyncio.Task`.
+
+ .. versionchanged:: 3.13.4
+ *name* is no longer passed to task factories. *context* is no longer passed
+ to task factories if it is ``None``.
+
+ .. versionchanged:: 3.14
+ *name* and *context* are now unconditionally passed on to task factories again.
+
.. method:: loop.get_task_factory()
Return a task factory or ``None`` if the default one is in use.
diff --git a/Doc/library/asyncio-stream.rst b/Doc/library/asyncio-stream.rst
index c56166cabb9..90c90862ca1 100644
--- a/Doc/library/asyncio-stream.rst
+++ b/Doc/library/asyncio-stream.rst
@@ -171,13 +171,17 @@ and work with streams:
.. function:: start_unix_server(client_connected_cb, path=None, \
*, limit=None, sock=None, backlog=100, ssl=None, \
ssl_handshake_timeout=None, \
- ssl_shutdown_timeout=None, start_serving=True)
+ ssl_shutdown_timeout=None, start_serving=True, cleanup_socket=True)
:async:
Start a Unix socket server.
Similar to :func:`start_server` but works with Unix sockets.
+ If *cleanup_socket* is true then the Unix socket will automatically
+ be removed from the filesystem when the server is closed, unless the
+ socket has been replaced after the server has been created.
+
See also the documentation of :meth:`loop.create_unix_server`.
.. note::
@@ -198,6 +202,9 @@ and work with streams:
.. versionchanged:: 3.11
Added the *ssl_shutdown_timeout* parameter.
+ .. versionchanged:: 3.13
+ Added the *cleanup_socket* parameter.
+
StreamReader
============
diff --git a/Doc/library/asyncio-task.rst b/Doc/library/asyncio-task.rst
index 59acce1990a..b19ffa8213a 100644
--- a/Doc/library/asyncio-task.rst
+++ b/Doc/library/asyncio-task.rst
@@ -238,18 +238,24 @@ Creating Tasks
-----------------------------------------------
-.. function:: create_task(coro, *, name=None, context=None)
+.. function:: create_task(coro, *, name=None, context=None, eager_start=None, **kwargs)
Wrap the *coro* :ref:`coroutine <coroutine>` into a :class:`Task`
and schedule its execution. Return the Task object.
- If *name* is not ``None``, it is set as the name of the task using
- :meth:`Task.set_name`.
+ The full function signature is largely the same as that of the
+ :class:`Task` constructor (or factory) - all of the keyword arguments to
+ this function are passed through to that interface.
An optional keyword-only *context* argument allows specifying a
custom :class:`contextvars.Context` for the *coro* to run in.
The current context copy is created when no *context* is provided.
+ An optional keyword-only *eager_start* argument allows specifying
+ if the task should execute eagerly during the call to create_task,
+ or be scheduled later. If *eager_start* is not passed the mode set
+ by :meth:`loop.set_task_factory` will be used.
+
The task is executed in the loop returned by :func:`get_running_loop`,
:exc:`RuntimeError` is raised if there is no running loop in
current thread.
@@ -290,6 +296,9 @@ Creating Tasks
.. versionchanged:: 3.11
Added the *context* parameter.
+ .. versionchanged:: 3.14
+ Added the *eager_start* parameter by passing on all *kwargs*.
+
Task Cancellation
=================
@@ -330,7 +339,7 @@ and reliable way to wait for all tasks in the group to finish.
.. versionadded:: 3.11
- .. method:: create_task(coro, *, name=None, context=None)
+ .. method:: create_task(coro, *, name=None, context=None, eager_start=None, **kwargs)
Create a task in this task group.
The signature matches that of :func:`asyncio.create_task`.
@@ -342,6 +351,10 @@ and reliable way to wait for all tasks in the group to finish.
Close the given coroutine if the task group is not active.
+ .. versionchanged:: 3.14
+
+ Passes on all *kwargs* to :meth:`loop.create_task`
+
Example::
async def main():
diff --git a/Doc/library/base64.rst b/Doc/library/base64.rst
index 834ab2536e6..529a7242443 100644
--- a/Doc/library/base64.rst
+++ b/Doc/library/base64.rst
@@ -15,14 +15,9 @@
This module provides functions for encoding binary data to printable
ASCII characters and decoding such encodings back to binary data.
-It provides encoding and decoding functions for the encodings specified in
-:rfc:`4648`, which defines the Base16, Base32, and Base64 algorithms,
-and for the de-facto standard Ascii85 and Base85 encodings.
-
-The :rfc:`4648` encodings are suitable for encoding binary data so that it can be
-safely sent by email, used as parts of URLs, or included as part of an HTTP
-POST request. The encoding algorithm is not the same as the
-:program:`uuencode` program.
+This includes the :ref:`encodings specified in <base64-rfc-4648>`
+:rfc:`4648` (Base64, Base32 and Base16)
+and the non-standard :ref:`Base85 encodings <base64-base-85>`.
There are two interfaces provided by this module. The modern interface
supports encoding :term:`bytes-like objects <bytes-like object>` to ASCII
@@ -30,7 +25,7 @@ supports encoding :term:`bytes-like objects <bytes-like object>` to ASCII
strings containing ASCII to :class:`bytes`. Both base-64 alphabets
defined in :rfc:`4648` (normal, and URL- and filesystem-safe) are supported.
-The legacy interface does not support decoding from strings, but it does
+The :ref:`legacy interface <base64-legacy>` does not support decoding from strings, but it does
provide functions for encoding and decoding to and from :term:`file objects
<file object>`. It only supports the Base64 standard alphabet, and it adds
newlines every 76 characters as per :rfc:`2045`. Note that if you are looking
@@ -46,7 +41,15 @@ package instead.
Any :term:`bytes-like objects <bytes-like object>` are now accepted by all
encoding and decoding functions in this module. Ascii85/Base85 support added.
-The modern interface provides:
+
+.. _base64-rfc-4648:
+
+RFC 4648 Encodings
+------------------
+
+The :rfc:`4648` encodings are suitable for encoding binary data so that it can be
+safely sent by email, used as parts of URLs, or included as part of an HTTP
+POST request.
.. function:: b64encode(s, altchars=None)
@@ -181,6 +184,26 @@ The modern interface provides:
incorrectly padded or if there are non-alphabet characters present in the
input.
+.. _base64-base-85:
+
+Base85 Encodings
+-----------------
+
+Base85 encoding is not formally specified but rather a de facto standard,
+thus different systems perform the encoding differently.
+
+The :func:`a85encode` and :func:`b85encode` functions in this module are two implementations of
+the de facto standard. You should call the function with the Base85
+implementation used by the software you intend to work with.
+
+The two functions present in this module differ in how they handle the following:
+
+* Whether to include enclosing ``<~`` and ``~>`` markers
+* Whether to include newline characters
+* The set of ASCII characters used for encoding
+* Handling of null bytes
+
+Refer to the documentation of the individual functions for more information.
.. function:: a85encode(b, *, foldspaces=False, wrapcol=0, pad=False, adobe=False)
@@ -262,7 +285,10 @@ The modern interface provides:
.. versionadded:: 3.13
-The legacy interface:
+.. _base64-legacy:
+
+Legacy Interface
+----------------
.. function:: decode(input, output)
diff --git a/Doc/library/calendar.rst b/Doc/library/calendar.rst
index 39090e36ed9..b292d828841 100644
--- a/Doc/library/calendar.rst
+++ b/Doc/library/calendar.rst
@@ -251,7 +251,7 @@ interpreted as prescribed by the ISO 8601 standard. Year 0 is 1 BC, year -1 is
3) specifies the number of months per row. *css* is the name for the
cascading style sheet to be used. :const:`None` can be passed if no style
sheet should be used. *encoding* specifies the encoding to be used for the
- output (defaulting to the system default encoding).
+ output (defaulting to ``'utf-8'``).
.. method:: formatmonthname(theyear, themonth, withyear=True)
diff --git a/Doc/library/code.rst b/Doc/library/code.rst
index 8f7692df9fb..52587c4dd8f 100644
--- a/Doc/library/code.rst
+++ b/Doc/library/code.rst
@@ -22,6 +22,12 @@ build applications which provide an interactive interpreter prompt.
it defaults to a newly created dictionary with key ``'__name__'`` set to
``'__console__'`` and key ``'__doc__'`` set to ``None``.
+ Note that functions and classes objects created under an
+ :class:`!InteractiveInterpreter` instance will belong to the namespace
+ specified by *locals*.
+ They are only pickleable if *locals* is the namespace of an existing
+ module.
+
.. class:: InteractiveConsole(locals=None, filename="<console>", local_exit=False)
diff --git a/Doc/library/codecs.rst b/Doc/library/codecs.rst
index 86511602fa5..b231fa568cf 100644
--- a/Doc/library/codecs.rst
+++ b/Doc/library/codecs.rst
@@ -53,6 +53,14 @@ any codec:
:exc:`UnicodeDecodeError`). Refer to :ref:`codec-base-classes` for more
information on codec error handling.
+.. function:: charmap_build(string)
+
+ Return a mapping suitable for encoding with a custom single-byte encoding.
+ Given a :class:`str` *string* of up to 256 characters representing a
+ decoding table, returns either a compact internal mapping object
+ ``EncodingMap`` or a :class:`dictionary <dict>` mapping character ordinals
+ to byte values. Raises a :exc:`TypeError` on invalid input.
+
The full details for each codec can also be looked up directly:
.. function:: lookup(encoding, /)
diff --git a/Doc/library/compileall.rst b/Doc/library/compileall.rst
index c42288419c4..ebbbf857e71 100644
--- a/Doc/library/compileall.rst
+++ b/Doc/library/compileall.rst
@@ -56,11 +56,18 @@ compile Python sources.
executed.
.. option:: -s strip_prefix
+
+ Remove the given prefix from paths recorded in the ``.pyc`` files.
+ Paths are made relative to the prefix.
+
+ This option can be used with ``-p`` but not with ``-d``.
+
.. option:: -p prepend_prefix
- Remove (``-s``) or append (``-p``) the given prefix of paths
- recorded in the ``.pyc`` files.
- Cannot be combined with ``-d``.
+ Prepend the given prefix to paths recorded in the ``.pyc`` files.
+ Use ``-p /`` to make the paths absolute.
+
+ This option can be used with ``-s`` but not with ``-d``.
.. option:: -x regex
diff --git a/Doc/library/compression.rst b/Doc/library/compression.rst
new file mode 100644
index 00000000000..618b4a3c2bd
--- /dev/null
+++ b/Doc/library/compression.rst
@@ -0,0 +1,18 @@
+The :mod:`!compression` package
+===============================
+
+.. versionadded:: 3.14
+
+The :mod:`!compression` package contains the canonical compression modules
+containing interfaces to several different compression algorithms. Some of
+these modules have historically been available as separate modules; those will
+continue to be available under their original names for compatibility reasons,
+and will not be removed without a deprecation cycle. The use of modules in
+:mod:`!compression` is encouraged where practical.
+
+* :mod:`!compression.bz2` -- Re-exports :mod:`bz2`
+* :mod:`!compression.gzip` -- Re-exports :mod:`gzip`
+* :mod:`!compression.lzma` -- Re-exports :mod:`lzma`
+* :mod:`!compression.zlib` -- Re-exports :mod:`zlib`
+* :mod:`compression.zstd` -- Wrapper for the Zstandard compression library
+
diff --git a/Doc/library/compression.zstd.rst b/Doc/library/compression.zstd.rst
new file mode 100644
index 00000000000..57ad8e3377f
--- /dev/null
+++ b/Doc/library/compression.zstd.rst
@@ -0,0 +1,891 @@
+:mod:`!compression.zstd` --- Compression compatible with the Zstandard format
+=============================================================================
+
+.. module:: compression.zstd
+ :synopsis: Low-level interface to compression and decompression routines in
+ the zstd library.
+
+.. versionadded:: 3.14
+
+**Source code:** :source:`Lib/compression/zstd/__init__.py`
+
+--------------
+
+This module provides classes and functions for compressing and decompressing
+data using the Zstandard (or *zstd*) compression algorithm. The
+`zstd manual <https://facebook.github.io/zstd/doc/api_manual_latest.html>`__
+describes Zstandard as "a fast lossless compression algorithm, targeting
+real-time compression scenarios at zlib-level and better compression ratios."
+Also included is a file interface that supports reading and writing the
+contents of ``.zst`` files created by the :program:`zstd` utility, as well as
+raw zstd compressed streams.
+
+The :mod:`!compression.zstd` module contains:
+
+* The :func:`.open` function and :class:`ZstdFile` class for reading and
+ writing compressed files.
+* The :class:`ZstdCompressor` and :class:`ZstdDecompressor` classes for
+ incremental (de)compression.
+* The :func:`compress` and :func:`decompress` functions for one-shot
+ (de)compression.
+* The :func:`train_dict` and :func:`finalize_dict` functions and the
+ :class:`ZstdDict` class to train and manage Zstandard dictionaries.
+* The :class:`CompressionParameter`, :class:`DecompressionParameter`, and
+ :class:`Strategy` classes for setting advanced (de)compression parameters.
+
+
+Exceptions
+----------
+
+.. exception:: ZstdError
+
+ This exception is raised when an error occurs during compression or
+ decompression, or while initializing the (de)compressor state.
+
+
+Reading and writing compressed files
+------------------------------------
+
+.. function:: open(file, /, mode='rb', *, level=None, options=None, \
+ zstd_dict=None, encoding=None, errors=None, newline=None)
+
+ Open a Zstandard-compressed file in binary or text mode, returning a
+ :term:`file object`.
+
+ The *file* argument can be either a file name (given as a
+ :class:`str`, :class:`bytes` or :term:`path-like <path-like object>`
+ object), in which case the named file is opened, or it can be an existing
+ file object to read from or write to.
+
+ The mode argument can be either ``'rb'`` for reading (default), ``'wb'`` for
+ overwriting, ``'ab'`` for appending, or ``'xb'`` for exclusive creation.
+ These can equivalently be given as ``'r'``, ``'w'``, ``'a'``, and ``'x'``
+ respectively. You may also open in text mode with ``'rt'``, ``'wt'``,
+ ``'at'``, and ``'xt'`` respectively.
+
+ When reading, the *options* argument can be a dictionary providing advanced
+ decompression parameters; see :class:`DecompressionParameter` for detailed
+ information about supported
+ parameters. The *zstd_dict* argument is a :class:`ZstdDict` instance to be
+ used during decompression. When reading, if the *level*
+ argument is not None, a :exc:`!TypeError` will be raised.
+
+ When writing, the *options* argument can be a dictionary
+ providing advanced decompression parameters; see
+ :class:`CompressionParameter` for detailed information about supported
+ parameters. The *level* argument is the compression level to use when
+ writing compressed data. Only one of *level* or *options* may be non-None.
+ The *zstd_dict* argument is a :class:`ZstdDict` instance to be used during
+ compression.
+
+ In binary mode, this function is equivalent to the :class:`ZstdFile`
+ constructor: ``ZstdFile(file, mode, ...)``. In this case, the
+ *encoding*, *errors*, and *newline* parameters must not be provided.
+
+ In text mode, a :class:`ZstdFile` object is created, and wrapped in an
+ :class:`io.TextIOWrapper` instance with the specified encoding, error
+ handling behavior, and line endings.
+
+
+.. class:: ZstdFile(file, /, mode='rb', *, level=None, options=None, \
+ zstd_dict=None)
+
+ Open a Zstandard-compressed file in binary mode.
+
+ A :class:`ZstdFile` can wrap an already-open :term:`file object`, or operate
+ directly on a named file. The *file* argument specifies either the file
+ object to wrap, or the name of the file to open (as a :class:`str`,
+ :class:`bytes` or :term:`path-like <path-like object>` object). If
+ wrapping an existing file object, the wrapped file will not be closed when
+ the :class:`ZstdFile` is closed.
+
+ The *mode* argument can be either ``'rb'`` for reading (default), ``'wb'``
+ for overwriting, ``'xb'`` for exclusive creation, or ``'ab'`` for appending.
+ These can equivalently be given as ``'r'``, ``'w'``, ``'x'`` and ``'a'``
+ respectively.
+
+ If *file* is a file object (rather than an actual file name), a mode of
+ ``'w'`` does not truncate the file, and is instead equivalent to ``'a'``.
+
+ When reading, the *options* argument can be a dictionary
+ providing advanced decompression parameters; see
+ :class:`DecompressionParameter` for detailed information about supported
+ parameters. The *zstd_dict* argument is a :class:`ZstdDict` instance to be
+ used during decompression. When reading, if the *level*
+ argument is not None, a :exc:`!TypeError` will be raised.
+
+ When writing, the *options* argument can be a dictionary
+ providing advanced decompression parameters; see
+ :class:`CompressionParameter` for detailed information about supported
+ parameters. The *level* argument is the compression level to use when
+ writing compressed data. Only one of *level* or *options* may be passed. The
+ *zstd_dict* argument is a :class:`ZstdDict` instance to be used during
+ compression.
+
+ :class:`!ZstdFile` supports all the members specified by
+ :class:`io.BufferedIOBase`, except for :meth:`~io.BufferedIOBase.detach`
+ and :meth:`~io.IOBase.truncate`.
+ Iteration and the :keyword:`with` statement are supported.
+
+ The following method and attributes are also provided:
+
+ .. method:: peek(size=-1)
+
+ Return buffered data without advancing the file position. At least one
+ byte of data will be returned, unless EOF has been reached. The exact
+ number of bytes returned is unspecified (the *size* argument is ignored).
+
+ .. note:: While calling :meth:`peek` does not change the file position of
+ the :class:`ZstdFile`, it may change the position of the underlying
+ file object (for example, if the :class:`ZstdFile` was constructed by
+ passing a file object for *file*).
+
+ .. attribute:: mode
+
+ ``'rb'`` for reading and ``'wb'`` for writing.
+
+ .. attribute:: name
+
+ The name of the Zstandard file. Equivalent to the :attr:`~io.FileIO.name`
+ attribute of the underlying :term:`file object`.
+
+
+Compressing and decompressing data in memory
+--------------------------------------------
+
+.. function:: compress(data, level=None, options=None, zstd_dict=None)
+
+ Compress *data* (a :term:`bytes-like object`), returning the compressed
+ data as a :class:`bytes` object.
+
+ The *level* argument is an integer controlling the level of
+ compression. *level* is an alternative to setting
+ :attr:`CompressionParameter.compression_level` in *options*. Use
+ :meth:`~CompressionParameter.bounds` on
+ :attr:`~CompressionParameter.compression_level` to get the values that can
+ be passed for *level*. If advanced compression options are needed, the
+ *level* argument must be omitted and in the *options* dictionary the
+ :attr:`!CompressionParameter.compression_level` parameter should be set.
+
+ The *options* argument is a Python dictionary containing advanced
+ compression parameters. The valid keys and values for compression parameters
+ are documented as part of the :class:`CompressionParameter` documentation.
+
+ The *zstd_dict* argument is an instance of :class:`ZstdDict`
+ containing trained data to improve compression efficiency. The
+ function :func:`train_dict` can be used to generate a Zstandard dictionary.
+
+
+.. function:: decompress(data, zstd_dict=None, options=None)
+
+ Decompress *data* (a :term:`bytes-like object`), returning the uncompressed
+ data as a :class:`bytes` object.
+
+ The *options* argument is a Python dictionary containing advanced
+ decompression parameters. The valid keys and values for compression
+ parameters are documented as part of the :class:`DecompressionParameter`
+ documentation.
+
+ The *zstd_dict* argument is an instance of :class:`ZstdDict`
+ containing trained data used during compression. This must be
+ the same Zstandard dictionary used during compression.
+
+ If *data* is the concatenation of multiple distinct compressed frames,
+ decompress all of these frames, and return the concatenation of the results.
+
+
+.. class:: ZstdCompressor(level=None, options=None, zstd_dict=None)
+
+ Create a compressor object, which can be used to compress data
+ incrementally.
+
+ For a more convenient way of compressing a single chunk of data, see the
+ module-level function :func:`compress`.
+
+ The *level* argument is an integer controlling the level of
+ compression. *level* is an alternative to setting
+ :attr:`CompressionParameter.compression_level` in *options*. Use
+ :meth:`~CompressionParameter.bounds` on
+ :attr:`~CompressionParameter.compression_level` to get the values that can
+ be passed for *level*. If advanced compression options are needed, the
+ *level* argument must be omitted and in the *options* dictionary the
+ :attr:`!CompressionParameter.compression_level` parameter should be set.
+
+ The *options* argument is a Python dictionary containing advanced
+ compression parameters. The valid keys and values for compression parameters
+ are documented as part of the :class:`CompressionParameter` documentation.
+
+ The *zstd_dict* argument is an optional instance of :class:`ZstdDict`
+ containing trained data to improve compression efficiency. The
+ function :func:`train_dict` can be used to generate a Zstandard dictionary.
+
+
+ .. method:: compress(data, mode=ZstdCompressor.CONTINUE)
+
+ Compress *data* (a :term:`bytes-like object`), returning a :class:`bytes`
+ object with compressed data if possible, or otherwise an empty
+ :class:`!bytes` object. Some of *data* may be buffered internally, for
+ use in later calls to :meth:`!compress` and :meth:`~.flush`. The returned
+ data should be concatenated with the output of any previous calls to
+ :meth:`~.compress`.
+
+ The *mode* argument is a :class:`ZstdCompressor` attribute, either
+ :attr:`~.CONTINUE`, :attr:`~.FLUSH_BLOCK`,
+ or :attr:`~.FLUSH_FRAME`.
+
+ When all data has been provided to the compressor, call the
+ :meth:`~.flush` method to finish the compression process. If
+ :meth:`~.compress` is called with *mode* set to :attr:`~.FLUSH_FRAME`,
+ :meth:`~.flush` should not be called, as it would write out a new empty
+ frame.
+
+ .. method:: flush(mode=ZstdCompressor.FLUSH_FRAME)
+
+ Finish the compression process, returning a :class:`bytes` object
+ containing any data stored in the compressor's internal buffers.
+
+ The *mode* argument is a :class:`ZstdCompressor` attribute, either
+ :attr:`~.FLUSH_BLOCK`, or :attr:`~.FLUSH_FRAME`.
+
+ .. method:: set_pledged_input_size(size)
+
+ Specify the amount of uncompressed data *size* that will be provided for
+ the next frame. *size* will be written into the frame header of the next
+ frame unless :attr:`CompressionParameter.content_size_flag` is ``False``
+ or ``0``. A size of ``0`` means that the frame is empty. If *size* is
+ ``None``, the frame header will omit the frame size. Frames that include
+ the uncompressed data size require less memory to decompress, especially
+ at higher compression levels.
+
+ If :attr:`last_mode` is not :attr:`FLUSH_FRAME`, a
+ :exc:`ValueError` is raised as the compressor is not at the start of
+ a frame. If the pledged size does not match the actual size of data
+ provided to :meth:`.compress`, future calls to :meth:`!compress` or
+ :meth:`flush` may raise :exc:`ZstdError` and the last chunk of data may
+ be lost.
+
+ After :meth:`flush` or :meth:`.compress` are called with mode
+ :attr:`FLUSH_FRAME`, the next frame will not include the frame size into
+ the header unless :meth:`!set_pledged_input_size` is called again.
+
+ .. attribute:: CONTINUE
+
+ Collect more data for compression, which may or may not generate output
+ immediately. This mode optimizes the compression ratio by maximizing the
+ amount of data per block and frame.
+
+ .. attribute:: FLUSH_BLOCK
+
+ Complete and write a block to the data stream. The data returned so far
+ can be immediately decompressed. Past data can still be referenced in
+ future blocks generated by calls to :meth:`~.compress`,
+ improving compression.
+
+ .. attribute:: FLUSH_FRAME
+
+ Complete and write out a frame. Future data provided to
+ :meth:`~.compress` will be written into a new frame and
+ *cannot* reference past data.
+
+ .. attribute:: last_mode
+
+ The last mode passed to either :meth:`~.compress` or :meth:`~.flush`.
+ The value can be one of :attr:`~.CONTINUE`, :attr:`~.FLUSH_BLOCK`, or
+ :attr:`~.FLUSH_FRAME`. The initial value is :attr:`~.FLUSH_FRAME`,
+ signifying that the compressor is at the start of a new frame.
+
+
+.. class:: ZstdDecompressor(zstd_dict=None, options=None)
+
+ Create a decompressor object, which can be used to decompress data
+ incrementally.
+
+ For a more convenient way of decompressing an entire compressed stream at
+ once, see the module-level function :func:`decompress`.
+
+ The *options* argument is a Python dictionary containing advanced
+ decompression parameters. The valid keys and values for compression
+ parameters are documented as part of the :class:`DecompressionParameter`
+ documentation.
+
+ The *zstd_dict* argument is an instance of :class:`ZstdDict`
+ containing trained data used during compression. This must be
+ the same Zstandard dictionary used during compression.
+
+ .. note::
+ This class does not transparently handle inputs containing multiple
+ compressed frames, unlike the :func:`decompress` function and
+ :class:`ZstdFile` class. To decompress a multi-frame input, you should
+ use :func:`decompress`, :class:`ZstdFile` if working with a
+ :term:`file object`, or multiple :class:`!ZstdDecompressor` instances.
+
+ .. method:: decompress(data, max_length=-1)
+
+ Decompress *data* (a :term:`bytes-like object`), returning
+ uncompressed data as bytes. Some of *data* may be buffered
+ internally, for use in later calls to :meth:`!decompress`.
+ The returned data should be concatenated with the output of any previous
+ calls to :meth:`!decompress`.
+
+ If *max_length* is non-negative, the method returns at most *max_length*
+ bytes of decompressed data. If this limit is reached and further
+ output can be produced, the :attr:`~.needs_input` attribute will
+ be set to ``False``. In this case, the next call to
+ :meth:`~.decompress` may provide *data* as ``b''`` to obtain
+ more of the output.
+
+ If all of the input data was decompressed and returned (either
+ because this was less than *max_length* bytes, or because
+ *max_length* was negative), the :attr:`~.needs_input` attribute
+ will be set to ``True``.
+
+ Attempting to decompress data after the end of a frame will raise a
+ :exc:`ZstdError`. Any data found after the end of the frame is ignored
+ and saved in the :attr:`~.unused_data` attribute.
+
+ .. attribute:: eof
+
+ ``True`` if the end-of-stream marker has been reached.
+
+ .. attribute:: unused_data
+
+ Data found after the end of the compressed stream.
+
+ Before the end of the stream is reached, this will be ``b''``.
+
+ .. attribute:: needs_input
+
+ ``False`` if the :meth:`.decompress` method can provide more
+ decompressed data before requiring new compressed input.
+
+
+Zstandard dictionaries
+----------------------
+
+
+.. function:: train_dict(samples, dict_size)
+
+ Train a Zstandard dictionary, returning a :class:`ZstdDict` instance.
+ Zstandard dictionaries enable more efficient compression of smaller sizes
+ of data, which is traditionally difficult to compress due to less
+ repetition. If you are compressing multiple similar groups of data (such as
+ similar files), Zstandard dictionaries can improve compression ratios and
+ speed significantly.
+
+ The *samples* argument (an iterable of :class:`bytes` objects), is the
+ population of samples used to train the Zstandard dictionary.
+
+ The *dict_size* argument, an integer, is the maximum size (in bytes) the
+ Zstandard dictionary should be. The Zstandard documentation suggests an
+ absolute maximum of no more than 100 KB, but the maximum can often be smaller
+ depending on the data. Larger dictionaries generally slow down compression,
+ but improve compression ratios. Smaller dictionaries lead to faster
+ compression, but reduce the compression ratio.
+
+
+.. function:: finalize_dict(zstd_dict, /, samples, dict_size, level)
+
+ An advanced function for converting a "raw content" Zstandard dictionary into
+ a regular Zstandard dictionary. "Raw content" dictionaries are a sequence of
+ bytes that do not need to follow the structure of a normal Zstandard
+ dictionary.
+
+ The *zstd_dict* argument is a :class:`ZstdDict` instance with
+ the :attr:`~ZstdDict.dict_content` containing the raw dictionary contents.
+
+ The *samples* argument (an iterable of :class:`bytes` objects), contains
+ sample data for generating the Zstandard dictionary.
+
+ The *dict_size* argument, an integer, is the maximum size (in bytes) the
+ Zstandard dictionary should be. See :func:`train_dict` for
+ suggestions on the maximum dictionary size.
+
+ The *level* argument (an integer) is the compression level expected to be
+ passed to the compressors using this dictionary. The dictionary information
+ varies for each compression level, so tuning for the proper compression
+ level can make compression more efficient.
+
+
+.. class:: ZstdDict(dict_content, /, *, is_raw=False)
+
+ A wrapper around Zstandard dictionaries. Dictionaries can be used to improve
+ the compression of many small chunks of data. Use :func:`train_dict` if you
+ need to train a new dictionary from sample data.
+
+ The *dict_content* argument (a :term:`bytes-like object`), is the already
+ trained dictionary information.
+
+ The *is_raw* argument, a boolean, is an advanced parameter controlling the
+ meaning of *dict_content*. ``True`` means *dict_content* is a "raw content"
+ dictionary, without any format restrictions. ``False`` means *dict_content*
+ is an ordinary Zstandard dictionary, created from Zstandard functions,
+ for example, :func:`train_dict` or the external :program:`zstd` CLI.
+
+ When passing a :class:`!ZstdDict` to a function, the
+ :attr:`!as_digested_dict` and :attr:`!as_undigested_dict` attributes can
+ control how the dictionary is loaded by passing them as the ``zstd_dict``
+ argument, for example, ``compress(data, zstd_dict=zd.as_digested_dict)``.
+ Digesting a dictionary is a costly operation that occurs when loading a
+ Zstandard dictionary. When making multiple calls to compression or
+ decompression, passing a digested dictionary will reduce the overhead of
+ loading the dictionary.
+
+ .. list-table:: Difference for compression
+ :widths: 10 14 10
+ :header-rows: 1
+
+ * -
+ - Digested dictionary
+ - Undigested dictionary
+ * - Advanced parameters of the compressor which may be overridden by
+ the dictionary's parameters
+ - ``window_log``, ``hash_log``, ``chain_log``, ``search_log``,
+ ``min_match``, ``target_length``, ``strategy``,
+ ``enable_long_distance_matching``, ``ldm_hash_log``,
+ ``ldm_min_match``, ``ldm_bucket_size_log``, ``ldm_hash_rate_log``,
+ and some non-public parameters.
+ - None
+ * - :class:`!ZstdDict` internally caches the dictionary
+ - Yes. It's faster when loading a digested dictionary again with the
+ same compression level.
+ - No. If you wish to load an undigested dictionary multiple times,
+ consider reusing a compressor object.
+
+ If passing a :class:`!ZstdDict` without any attribute, an undigested
+ dictionary is passed by default when compressing and a digested dictionary
+ is generated if necessary and passed by default when decompressing.
+
+ .. attribute:: dict_content
+
+ The content of the Zstandard dictionary, a ``bytes`` object. It's the
+ same as the *dict_content* argument in the ``__init__`` method. It can
+ be used with other programs, such as the ``zstd`` CLI program.
+
+ .. attribute:: dict_id
+
+ Identifier of the Zstandard dictionary, a non-negative int value.
+
+ Non-zero means the dictionary is ordinary, created by Zstandard
+ functions and following the Zstandard format.
+
+ ``0`` means a "raw content" dictionary, free of any format restriction,
+ used for advanced users.
+
+ .. note::
+
+ The meaning of ``0`` for :attr:`!ZstdDict.dict_id` is different
+ from the ``dictionary_id`` attribute to the :func:`get_frame_info`
+ function.
+
+ .. attribute:: as_digested_dict
+
+ Load as a digested dictionary.
+
+ .. attribute:: as_undigested_dict
+
+ Load as an undigested dictionary.
+
+
+Advanced parameter control
+--------------------------
+
+.. class:: CompressionParameter()
+
+ An :class:`~enum.IntEnum` containing the advanced compression parameter
+ keys that can be used when compressing data.
+
+ The :meth:`~.bounds` method can be used on any attribute to get the valid
+ values for that parameter.
+
+ Parameters are optional; any omitted parameter will have it's value selected
+ automatically.
+
+ Example getting the lower and upper bound of :attr:`~.compression_level`::
+
+ lower, upper = CompressionParameter.compression_level.bounds()
+
+ Example setting the :attr:`~.window_log` to the maximum size::
+
+ _lower, upper = CompressionParameter.window_log.bounds()
+ options = {CompressionParameter.window_log: upper}
+ compress(b'venezuelan beaver cheese', options=options)
+
+ .. method:: bounds()
+
+ Return the tuple of int bounds, ``(lower, upper)``, of a compression
+ parameter. This method should be called on the attribute you wish to
+ retrieve the bounds of. For example, to get the valid values for
+ :attr:`~.compression_level`, one may check the result of
+ ``CompressionParameter.compression_level.bounds()``.
+
+ Both the lower and upper bounds are inclusive.
+
+ .. attribute:: compression_level
+
+ A high-level means of setting other compression parameters that affect
+ the speed and ratio of compressing data. Setting the level to zero uses
+ :attr:`COMPRESSION_LEVEL_DEFAULT`.
+
+ .. attribute:: window_log
+
+ Maximum allowed back-reference distance the compressor can use when
+ compressing data, expressed as power of two, ``1 << window_log`` bytes.
+ This parameter greatly influences the memory usage of compression. Higher
+ values require more memory but gain better compression values.
+
+ A value of zero causes the value to be selected automatically.
+
+ .. attribute:: hash_log
+
+ Size of the initial probe table, as a power of two. The resulting memory
+ usage is ``1 << (hash_log+2)`` bytes. Larger tables improve compression
+ ratio of strategies <= :attr:`~Strategy.dfast`, and improve compression
+ speed of strategies > :attr:`~Strategy.dfast`.
+
+ A value of zero causes the value to be selected automatically.
+
+ .. attribute:: chain_log
+
+ Size of the multi-probe search table, as a power of two. The resulting
+ memory usage is ``1 << (chain_log+2)`` bytes. Larger tables result in
+ better and slower compression. This parameter has no effect for the
+ :attr:`~Strategy.fast` strategy. It's still useful when using
+ :attr:`~Strategy.dfast` strategy, in which case it defines a secondary
+ probe table.
+
+ A value of zero causes the value to be selected automatically.
+
+ .. attribute:: search_log
+
+ Number of search attempts, as a power of two. More attempts result in
+ better and slower compression. This parameter is useless for
+ :attr:`~Strategy.fast` and :attr:`~Strategy.dfast` strategies.
+
+ A value of zero causes the value to be selected automatically.
+
+ .. attribute:: min_match
+
+ Minimum size of searched matches. Larger values increase compression and
+ decompression speed, but decrease ratio. Note that Zstandard can still
+ find matches of smaller size, it just tweaks its search algorithm to look
+ for this size and larger. For all strategies < :attr:`~Strategy.btopt`,
+ the effective minimum is ``4``; for all strategies
+ > :attr:`~Strategy.fast`, the effective maximum is ``6``.
+
+ A value of zero causes the value to be selected automatically.
+
+ .. attribute:: target_length
+
+ The impact of this field depends on the selected :class:`Strategy`.
+
+ For strategies :attr:`~Strategy.btopt`, :attr:`~Strategy.btultra` and
+ :attr:`~Strategy.btultra2`, the value is the length of a match
+ considered "good enough" to stop searching. Larger values make
+ compression ratios better, but compresses slower.
+
+ For strategy :attr:`~Strategy.fast`, it is the distance between match
+ sampling. Larger values make compression faster, but with a worse
+ compression ratio.
+
+ A value of zero causes the value to be selected automatically.
+
+ .. attribute:: strategy
+
+ The higher the value of selected strategy, the more complex the
+ compression technique used by zstd, resulting in higher compression
+ ratios but slower compression.
+
+ .. seealso:: :class:`Strategy`
+
+ .. attribute:: enable_long_distance_matching
+
+ Long distance matching can be used to improve compression for large
+ inputs by finding large matches at greater distances. It increases memory
+ usage and window size.
+
+ ``True`` or ``1`` enable long distance matching while ``False`` or ``0``
+ disable it.
+
+ Enabling this parameter increases default
+ :attr:`~CompressionParameter.window_log` to 128 MiB except when expressly
+ set to a different value. This setting is enabled by default if
+ :attr:`!window_log` >= 128 MiB and the compression
+ strategy >= :attr:`~Strategy.btopt` (compression level 16+).
+
+ .. attribute:: ldm_hash_log
+
+ Size of the table for long distance matching, as a power of two. Larger
+ values increase memory usage and compression ratio, but decrease
+ compression speed.
+
+ A value of zero causes the value to be selected automatically.
+
+ .. attribute:: ldm_min_match
+
+ Minimum match size for long distance matcher. Larger or too small values
+ can often decrease the compression ratio.
+
+ A value of zero causes the value to be selected automatically.
+
+ .. attribute:: ldm_bucket_size_log
+
+ Log size of each bucket in the long distance matcher hash table for
+ collision resolution. Larger values improve collision resolution but
+ decrease compression speed.
+
+ A value of zero causes the value to be selected automatically.
+
+ .. attribute:: ldm_hash_rate_log
+
+ Frequency of inserting/looking up entries into the long distance matcher
+ hash table. Larger values improve compression speed. Deviating far from
+ the default value will likely result in a compression ratio decrease.
+
+ A value of zero causes the value to be selected automatically.
+
+ .. attribute:: content_size_flag
+
+ Write the size of the data to be compressed into the Zstandard frame
+ header when known prior to compressing.
+
+ This flag only takes effect under the following scenarios:
+
+ * Calling :func:`compress` for one-shot compression
+ * Providing all of the data to be compressed in the frame in a single
+ :meth:`ZstdCompressor.compress` call, with the
+ :attr:`ZstdCompressor.FLUSH_FRAME` mode.
+ * Calling :meth:`ZstdCompressor.set_pledged_input_size` with the exact
+ amount of data that will be provided to the compressor prior to any
+ calls to :meth:`ZstdCompressor.compress` for the current frame.
+ :meth:`!ZstdCompressor.set_pledged_input_size` must be called for each
+ new frame.
+
+ All other compression calls may not write the size information into the
+ frame header.
+
+ ``True`` or ``1`` enable the content size flag while ``False`` or ``0``
+ disable it.
+
+ .. attribute:: checksum_flag
+
+ A four-byte checksum using XXHash64 of the uncompressed content is
+ written at the end of each frame. Zstandard's decompression code verifies
+ the checksum. If there is a mismatch a :class:`ZstdError` exception is
+ raised.
+
+ ``True`` or ``1`` enable checksum generation while ``False`` or ``0``
+ disable it.
+
+ .. attribute:: dict_id_flag
+
+ When compressing with a :class:`ZstdDict`, the dictionary's ID is written
+ into the frame header.
+
+ ``True`` or ``1`` enable storing the dictionary ID while ``False`` or
+ ``0`` disable it.
+
+ .. attribute:: nb_workers
+
+ Select how many threads will be spawned to compress in parallel. When
+ :attr:`!nb_workers` > 0, enables multi-threaded compression, a value of
+ ``1`` means "one-thread multi-threaded mode". More workers improve speed,
+ but also increase memory usage and slightly reduce compression ratio.
+
+ A value of zero disables multi-threading.
+
+ .. attribute:: job_size
+
+ Size of a compression job, in bytes. This value is enforced only when
+ :attr:`~CompressionParameter.nb_workers` >= 1. Each compression job is
+ completed in parallel, so this value can indirectly impact the number of
+ active threads.
+
+ A value of zero causes the value to be selected automatically.
+
+ .. attribute:: overlap_log
+
+ Sets how much data is reloaded from previous jobs (threads) for new jobs
+ to be used by the look behind window during compression. This value is
+ only used when :attr:`~CompressionParameter.nb_workers` >= 1. Acceptable
+ values vary from 0 to 9.
+
+ * 0 means dynamically set the overlap amount
+ * 1 means no overlap
+ * 9 means use a full window size from the previous job
+
+ Each increment halves/doubles the overlap size. "8" means an overlap of
+ ``window_size/2``, "7" means an overlap of ``window_size/4``, etc.
+
+.. class:: DecompressionParameter()
+
+ An :class:`~enum.IntEnum` containing the advanced decompression parameter
+ keys that can be used when decompressing data. Parameters are optional; any
+ omitted parameter will have it's value selected automatically.
+
+ The :meth:`~.bounds` method can be used on any attribute to get the valid
+ values for that parameter.
+
+ Example setting the :attr:`~.window_log_max` to the maximum size::
+
+ data = compress(b'Some very long buffer of bytes...')
+
+ _lower, upper = DecompressionParameter.window_log_max.bounds()
+
+ options = {DecompressionParameter.window_log_max: upper}
+ decompress(data, options=options)
+
+ .. method:: bounds()
+
+ Return the tuple of int bounds, ``(lower, upper)``, of a decompression
+ parameter. This method should be called on the attribute you wish to
+ retrieve the bounds of.
+
+ Both the lower and upper bounds are inclusive.
+
+ .. attribute:: window_log_max
+
+ The base-two logarithm of the maximum size of the window used during
+ decompression. This can be useful to limit the amount of memory used when
+ decompressing data. A larger maximum window size leads to faster
+ decompression.
+
+ A value of zero causes the value to be selected automatically.
+
+
+.. class:: Strategy()
+
+ An :class:`~enum.IntEnum` containing strategies for compression.
+ Higher-numbered strategies correspond to more complex and slower
+ compression.
+
+ .. note::
+
+ The values of attributes of :class:`!Strategy` are not necessarily stable
+ across zstd versions. Only the ordering of the attributes may be relied
+ upon. The attributes are listed below in order.
+
+ The following strategies are available:
+
+ .. attribute:: fast
+
+ .. attribute:: dfast
+
+ .. attribute:: greedy
+
+ .. attribute:: lazy
+
+ .. attribute:: lazy2
+
+ .. attribute:: btlazy2
+
+ .. attribute:: btopt
+
+ .. attribute:: btultra
+
+ .. attribute:: btultra2
+
+
+Miscellaneous
+-------------
+
+.. function:: get_frame_info(frame_buffer)
+
+ Retrieve a :class:`FrameInfo` object containing metadata about a Zstandard
+ frame. Frames contain metadata related to the compressed data they hold.
+
+
+.. class:: FrameInfo
+
+ Metadata related to a Zstandard frame.
+
+ .. attribute:: decompressed_size
+
+ The size of the decompressed contents of the frame.
+
+ .. attribute:: dictionary_id
+
+ An integer representing the Zstandard dictionary ID needed for
+ decompressing the frame. ``0`` means the dictionary ID was not
+ recorded in the frame header. This may mean that a Zstandard dictionary
+ is not needed, or that the ID of a required dictionary was not recorded.
+
+
+.. attribute:: COMPRESSION_LEVEL_DEFAULT
+
+ The default compression level for Zstandard: ``3``.
+
+
+.. attribute:: zstd_version_info
+
+ Version number of the runtime zstd library as a tuple of integers
+ (major, minor, release).
+
+
+Examples
+--------
+
+Reading in a compressed file:
+
+.. code-block:: python
+
+ from compression import zstd
+
+ with zstd.open("file.zst") as f:
+ file_content = f.read()
+
+Creating a compressed file:
+
+.. code-block:: python
+
+ from compression import zstd
+
+ data = b"Insert Data Here"
+ with zstd.open("file.zst", "w") as f:
+ f.write(data)
+
+Compressing data in memory:
+
+.. code-block:: python
+
+ from compression import zstd
+
+ data_in = b"Insert Data Here"
+ data_out = zstd.compress(data_in)
+
+Incremental compression:
+
+.. code-block:: python
+
+ from compression import zstd
+
+ comp = zstd.ZstdCompressor()
+ out1 = comp.compress(b"Some data\n")
+ out2 = comp.compress(b"Another piece of data\n")
+ out3 = comp.compress(b"Even more data\n")
+ out4 = comp.flush()
+ # Concatenate all the partial results:
+ result = b"".join([out1, out2, out3, out4])
+
+Writing compressed data to an already-open file:
+
+.. code-block:: python
+
+ from compression import zstd
+
+ with open("myfile", "wb") as f:
+ f.write(b"This data will not be compressed\n")
+ with zstd.open(f, "w") as zstf:
+ zstf.write(b"This *will* be compressed\n")
+ f.write(b"Not compressed\n")
+
+Creating a compressed file using compression parameters:
+
+.. code-block:: python
+
+ from compression import zstd
+
+ options = {
+ zstd.CompressionParameter.checksum_flag: 1
+ }
+ with zstd.open("file.zst", "w", options=options) as f:
+ f.write(b"Mind if I squeeze in?")
diff --git a/Doc/library/concurrency.rst b/Doc/library/concurrency.rst
index 5be1a1106b0..18f9443cbfe 100644
--- a/Doc/library/concurrency.rst
+++ b/Doc/library/concurrency.rst
@@ -18,6 +18,7 @@ multitasking). Here's an overview:
multiprocessing.shared_memory.rst
concurrent.rst
concurrent.futures.rst
+ concurrent.interpreters.rst
subprocess.rst
sched.rst
queue.rst
diff --git a/Doc/library/concurrent.futures.rst b/Doc/library/concurrent.futures.rst
index 3c8d9ab111e..dd92765038c 100644
--- a/Doc/library/concurrent.futures.rst
+++ b/Doc/library/concurrent.futures.rst
@@ -265,7 +265,7 @@ Each worker's interpreter is isolated from all the other interpreters.
"Isolated" means each interpreter has its own runtime state and
operates completely independently. For example, if you redirect
:data:`sys.stdout` in one interpreter, it will not be automatically
-redirected any other interpreter. If you import a module in one
+redirected to any other interpreter. If you import a module in one
interpreter, it is not automatically imported in any other. You
would need to import the module separately in interpreter where
you need it. In fact, each module imported in an interpreter is
@@ -287,7 +287,7 @@ efficient alternative is to serialize with :mod:`pickle` and then send
the bytes over a shared :mod:`socket <socket>` or
:func:`pipe <os.pipe>`.
-.. class:: InterpreterPoolExecutor(max_workers=None, thread_name_prefix='', initializer=None, initargs=(), shared=None)
+.. class:: InterpreterPoolExecutor(max_workers=None, thread_name_prefix='', initializer=None, initargs=())
A :class:`ThreadPoolExecutor` subclass that executes calls asynchronously
using a pool of at most *max_workers* threads. Each thread runs
@@ -305,20 +305,9 @@ the bytes over a shared :mod:`socket <socket>` or
interpreter.
.. note::
- Functions defined in the ``__main__`` module cannot be pickled
- and thus cannot be used.
-
- .. note::
The executor may replace uncaught exceptions from *initializer*
with :class:`~concurrent.futures.interpreter.ExecutionFailed`.
- The optional *shared* argument is a :class:`dict` of objects that all
- interpreters in the pool share. The *shared* items are added to each
- interpreter's ``__main__`` module. Not all objects are shareable.
- Shareable objects include the builtin singletons, :class:`str`
- and :class:`bytes`, and :class:`memoryview`. See :pep:`734`
- for more info.
-
Other caveats from parent :class:`ThreadPoolExecutor` apply here.
:meth:`~Executor.submit` and :meth:`~Executor.map` work like normal,
@@ -326,10 +315,6 @@ except the worker serializes the callable and arguments using
:mod:`pickle` when sending them to its interpreter. The worker
likewise serializes the return value when sending it back.
-.. note::
- Functions defined in the ``__main__`` module cannot be pickled
- and thus cannot be used.
-
When a worker's current task raises an uncaught exception, the worker
always tries to preserve the exception as-is. If that is successful
then it also sets the ``__cause__`` to a corresponding
diff --git a/Doc/library/concurrent.interpreters.rst b/Doc/library/concurrent.interpreters.rst
new file mode 100644
index 00000000000..524d505bcf1
--- /dev/null
+++ b/Doc/library/concurrent.interpreters.rst
@@ -0,0 +1,387 @@
+:mod:`!concurrent.interpreters` --- Multiple interpreters in the same process
+=============================================================================
+
+.. module:: concurrent.interpreters
+ :synopsis: Multiple interpreters in the same process
+
+.. moduleauthor:: Eric Snow <ericsnowcurrently@gmail.com>
+.. sectionauthor:: Eric Snow <ericsnowcurrently@gmail.com>
+
+.. versionadded:: 3.14
+
+**Source code:** :source:`Lib/concurrent/interpreters.py`
+
+--------------
+
+The :mod:`!concurrent.interpreters` module constructs higher-level
+interfaces on top of the lower level :mod:`!_interpreters` module.
+
+The module is primarily meant to provide a basic API for managing
+interpreters (AKA "subinterpreters") and running things in them.
+Running mostly involves switching to an interpreter (in the current
+thread) and calling a function in that execution context.
+
+For concurrency, interpreters themselves (and this module) don't
+provide much more than isolation, which on its own isn't useful.
+Actual concurrency is available separately through
+:mod:`threads <threading>` See `below <interp-concurrency_>`_
+
+.. seealso::
+
+ :class:`~concurrent.futures.InterpreterPoolExecutor`
+ combines threads with interpreters in a familiar interface.
+
+ .. XXX Add references to the upcoming HOWTO docs in the seealso block.
+
+ :ref:`isolating-extensions-howto`
+ how to update an extension module to support multiple interpreters
+
+ :pep:`554`
+
+ :pep:`734`
+
+ :pep:`684`
+
+.. XXX Why do we disallow multiple interpreters on WASM?
+
+.. include:: ../includes/wasm-notavail.rst
+
+
+Key details
+-----------
+
+Before we dive in further, there are a small number of details
+to keep in mind about using multiple interpreters:
+
+* `isolated <interp-isolation_>`_, by default
+* no implicit threads
+* not all PyPI packages support use in multiple interpreters yet
+
+.. XXX Are there other relevant details to list?
+
+
+.. _interpreters-intro:
+
+Introduction
+------------
+
+An "interpreter" is effectively the execution context of the Python
+runtime. It contains all of the state the runtime needs to execute
+a program. This includes things like the import state and builtins.
+(Each thread, even if there's only the main thread, has some extra
+runtime state, in addition to the current interpreter, related to
+the current exception and the bytecode eval loop.)
+
+The concept and functionality of the interpreter have been a part of
+Python since version 2.2, but the feature was only available through
+the C-API and not well known, and the `isolation <interp-isolation_>`_
+was relatively incomplete until version 3.12.
+
+.. _interp-isolation:
+
+Multiple Interpreters and Isolation
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+A Python implementation may support using multiple interpreters in the
+same process. CPython has this support. Each interpreter is
+effectively isolated from the others (with a limited number of
+carefully managed process-global exceptions to the rule).
+
+That isolation is primarily useful as a strong separation between
+distinct logical components of a program, where you want to have
+careful control of how those components interact.
+
+.. note::
+
+ Interpreters in the same process can technically never be strictly
+ isolated from one another since there are few restrictions on memory
+ access within the same process. The Python runtime makes a best
+ effort at isolation but extension modules may easily violate that.
+ Therefore, do not use multiple interpreters in security-sensitive
+ situations, where they shouldn't have access to each other's data.
+
+Running in an Interpreter
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Running in a different interpreter involves switching to it in the
+current thread and then calling some function. The runtime will
+execute the function using the current interpreter's state. The
+:mod:`!concurrent.interpreters` module provides a basic API for
+creating and managing interpreters, as well as the switch-and-call
+operation.
+
+No other threads are automatically started for the operation.
+There is `a helper <interp-call-in-thread_>`_ for that though.
+There is another dedicated helper for calling the builtin
+:func:`exec` in an interpreter.
+
+When :func:`exec` (or :func:`eval`) are called in an interpreter,
+they run using the interpreter's :mod:`!__main__` module as the
+"globals" namespace. The same is true for functions that aren't
+associated with any module. This is the same as how scripts invoked
+from the command-line run in the :mod:`!__main__` module.
+
+
+.. _interp-concurrency:
+
+Concurrency and Parallelism
+^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+As noted earlier, interpreters do not provide any concurrency
+on their own. They strictly represent the isolated execution
+context the runtime will use *in the current thread*. That isolation
+makes them similar to processes, but they still enjoy in-process
+efficiency, like threads.
+
+All that said, interpreters do naturally support certain flavors of
+concurrency, as a powerful side effect of that isolation.
+There's a powerful side effect of that isolation. It enables a
+different approach to concurrency than you can take with async or
+threads. It's a similar concurrency model to CSP or the actor model,
+a model which is relatively easy to reason about.
+
+You can take advantage of that concurrency model in a single thread,
+switching back and forth between interpreters, Stackless-style.
+However, this model is more useful when you combine interpreters
+with multiple threads. This mostly involves starting a new thread,
+where you switch to another interpreter and run what you want there.
+
+Each actual thread in Python, even if you're only running in the main
+thread, has its own *current* execution context. Multiple threads can
+use the same interpreter or different ones.
+
+At a high level, you can think of the combination of threads and
+interpreters as threads with opt-in sharing.
+
+As a significant bonus, interpreters are sufficiently isolated that
+they do not share the :term:`GIL`, which means combining threads with
+multiple interpreters enables full multi-core parallelism.
+(This has been the case since Python 3.12.)
+
+Communication Between Interpreters
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+In practice, multiple interpreters are useful only if we have a way
+to communicate between them. This usually involves some form of
+message passing, but can even mean sharing data in some carefully
+managed way.
+
+With this in mind, the :mod:`!concurrent.interpreters` module provides
+a :class:`queue.Queue` implementation, available through
+:func:`create_queue`.
+
+.. _interp-object-sharing:
+
+"Sharing" Objects
+^^^^^^^^^^^^^^^^^
+
+Any data actually shared between interpreters loses the thread-safety
+provided by the :term:`GIL`. There are various options for dealing with
+this in extension modules. However, from Python code the lack of
+thread-safety means objects can't actually be shared, with a few
+exceptions. Instead, a copy must be created, which means mutable
+objects won't stay in sync.
+
+By default, most objects are copied with :mod:`pickle` when they are
+passed to another interpreter. Nearly all of the immutable builtin
+objects are either directly shared or copied efficiently. For example:
+
+* :const:`None`
+* :class:`bool` (:const:`True` and :const:`False`)
+* :class:`bytes`
+* :class:`str`
+* :class:`int`
+* :class:`float`
+* :class:`tuple` (of similarly supported objects)
+
+There is a small number of Python types that actually share mutable
+data between interpreters:
+
+* :class:`memoryview`
+* :class:`Queue`
+
+
+Reference
+---------
+
+This module defines the following functions:
+
+.. function:: list_all()
+
+ Return a :class:`list` of :class:`Interpreter` objects,
+ one for each existing interpreter.
+
+.. function:: get_current()
+
+ Return an :class:`Interpreter` object for the currently running
+ interpreter.
+
+.. function:: get_main()
+
+ Return an :class:`Interpreter` object for the main interpreter.
+ This is the interpreter the runtime created to run the :term:`REPL`
+ or the script given at the command-line. It is usually the only one.
+
+.. function:: create()
+
+ Initialize a new (idle) Python interpreter
+ and return a :class:`Interpreter` object for it.
+
+.. function:: create_queue()
+
+ Initialize a new cross-interpreter queue and return a :class:`Queue`
+ object for it.
+
+
+Interpreter objects
+^^^^^^^^^^^^^^^^^^^
+
+.. class:: Interpreter(id)
+
+ A single interpreter in the current process.
+
+ Generally, :class:`Interpreter` shouldn't be called directly.
+ Instead, use :func:`create` or one of the other module functions.
+
+ .. attribute:: id
+
+ (read-only)
+
+ The underlying interpreter's ID.
+
+ .. attribute:: whence
+
+ (read-only)
+
+ A string describing where the interpreter came from.
+
+ .. method:: is_running()
+
+ Return ``True`` if the interpreter is currently executing code
+ in its :mod:`!__main__` module and ``False`` otherwise.
+
+ .. method:: close()
+
+ Finalize and destroy the interpreter.
+
+ .. method:: prepare_main(ns=None, **kwargs)
+
+ Bind objects in the interpreter's :mod:`!__main__` module.
+
+ Some objects are actually shared and some are copied efficiently,
+ but most are copied via :mod:`pickle`. See :ref:`interp-object-sharing`.
+
+ .. method:: exec(code, /, dedent=True)
+
+ Run the given source code in the interpreter (in the current thread).
+
+ .. method:: call(callable, /, *args, **kwargs)
+
+ Return the result of calling running the given function in the
+ interpreter (in the current thread).
+
+ .. _interp-call-in-thread:
+
+ .. method:: call_in_thread(callable, /, *args, **kwargs)
+
+ Run the given function in the interpreter (in a new thread).
+
+Exceptions
+^^^^^^^^^^
+
+.. exception:: InterpreterError
+
+ This exception, a subclass of :exc:`Exception`, is raised when
+ an interpreter-related error happens.
+
+.. exception:: InterpreterNotFoundError
+
+ This exception, a subclass of :exc:`InterpreterError`, is raised when
+ the targeted interpreter no longer exists.
+
+.. exception:: ExecutionFailed
+
+ This exception, a subclass of :exc:`InterpreterError`, is raised when
+ the running code raised an uncaught exception.
+
+ .. attribute:: excinfo
+
+ A basic snapshot of the exception raised in the other interpreter.
+
+.. XXX Document the excinfoattrs?
+
+.. exception:: NotShareableError
+
+ This exception, a subclass of :exc:`TypeError`, is raised when
+ an object cannot be sent to another interpreter.
+
+
+Communicating Between Interpreters
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. class:: Queue(id)
+
+ A wrapper around a low-level, cross-interpreter queue, which
+ implements the :class:`queue.Queue` interface. The underlying queue
+ can only be created through :func:`create_queue`.
+
+ Some objects are actually shared and some are copied efficiently,
+ but most are copied via :mod:`pickle`. See :ref:`interp-object-sharing`.
+
+ .. attribute:: id
+
+ (read-only)
+
+ The queue's ID.
+
+
+.. exception:: QueueEmptyError
+
+ This exception, a subclass of :exc:`queue.Empty`, is raised from
+ :meth:`!Queue.get` and :meth:`!Queue.get_nowait` when the queue
+ is empty.
+
+.. exception:: QueueFullError
+
+ This exception, a subclass of :exc:`queue.Full`, is raised from
+ :meth:`!Queue.put` and :meth:`!Queue.put_nowait` when the queue
+ is full.
+
+
+Basic usage
+-----------
+
+Creating an interpreter and running code in it::
+
+ from concurrent import interpreters
+
+ interp = interpreters.create()
+
+ # Run in the current OS thread.
+
+ interp.exec('print("spam!")')
+
+ interp.exec("""if True:
+ print('spam!')
+ """)
+
+ from textwrap import dedent
+ interp.exec(dedent("""
+ print('spam!')
+ """))
+
+ def run(arg):
+ return arg
+
+ res = interp.call(run, 'spam!')
+ print(res)
+
+ def run():
+ print('spam!')
+
+ interp.call(run)
+
+ # Run in new OS thread.
+
+ t = interp.call_in_thread(run)
+ t.join()
diff --git a/Doc/library/concurrent.rst b/Doc/library/concurrent.rst
index 8caea78bbb5..748c72c733b 100644
--- a/Doc/library/concurrent.rst
+++ b/Doc/library/concurrent.rst
@@ -1,6 +1,7 @@
The :mod:`!concurrent` package
==============================
-Currently, there is only one module in this package:
+This package contains the following modules:
* :mod:`concurrent.futures` -- Launching parallel tasks
+* :mod:`concurrent.interpreters` -- Multiple interpreters in the same process
diff --git a/Doc/library/copy.rst b/Doc/library/copy.rst
index 95b41f988a0..210ad718800 100644
--- a/Doc/library/copy.rst
+++ b/Doc/library/copy.rst
@@ -122,6 +122,8 @@ and only supports named tuples created by :func:`~collections.namedtuple`,
This method should create a new object of the same type,
replacing fields with values from *changes*.
+ .. versionadded:: 3.13
+
.. seealso::
diff --git a/Doc/library/csv.rst b/Doc/library/csv.rst
index 533cdf13974..d39c4ca4a58 100644
--- a/Doc/library/csv.rst
+++ b/Doc/library/csv.rst
@@ -53,7 +53,7 @@ The :mod:`csv` module defines the following functions:
.. index::
single: universal newlines; csv.reader function
-.. function:: reader(csvfile, dialect='excel', **fmtparams)
+.. function:: reader(csvfile, /, dialect='excel', **fmtparams)
Return a :ref:`reader object <reader-objects>` that will process
lines from the given *csvfile*. A csvfile must be an iterable of
@@ -70,7 +70,7 @@ The :mod:`csv` module defines the following functions:
section :ref:`csv-fmt-params`.
Each row read from the csv file is returned as a list of strings. No
- automatic data type conversion is performed unless the ``QUOTE_NONNUMERIC`` format
+ automatic data type conversion is performed unless the :data:`QUOTE_NONNUMERIC` format
option is specified (in which case unquoted fields are transformed into floats).
A short usage example::
@@ -84,7 +84,7 @@ The :mod:`csv` module defines the following functions:
Spam, Lovely Spam, Wonderful Spam
-.. function:: writer(csvfile, dialect='excel', **fmtparams)
+.. function:: writer(csvfile, /, dialect='excel', **fmtparams)
Return a writer object responsible for converting the user's data into delimited
strings on the given file-like object. *csvfile* can be any object with a
@@ -323,23 +323,32 @@ The :mod:`csv` module defines the following constants:
.. data:: QUOTE_MINIMAL
Instructs :class:`writer` objects to only quote those fields which contain
- special characters such as *delimiter*, *quotechar* or any of the characters in
- *lineterminator*.
+ special characters such as *delimiter*, *quotechar*, ``'\r'``, ``'\n'``
+ or any of the characters in *lineterminator*.
.. data:: QUOTE_NONNUMERIC
Instructs :class:`writer` objects to quote all non-numeric fields.
- Instructs :class:`reader` objects to convert all non-quoted fields to type *float*.
+ Instructs :class:`reader` objects to convert all non-quoted fields to type :class:`float`.
+ .. note::
+ Some numeric types, such as :class:`bool`, :class:`~fractions.Fraction`,
+ or :class:`~enum.IntEnum`, have a string representation that cannot be
+ converted to :class:`float`.
+ They cannot be read in the :data:`QUOTE_NONNUMERIC` and
+ :data:`QUOTE_STRINGS` modes.
.. data:: QUOTE_NONE
- Instructs :class:`writer` objects to never quote fields. When the current
- *delimiter* occurs in output data it is preceded by the current *escapechar*
- character. If *escapechar* is not set, the writer will raise :exc:`Error` if
+ Instructs :class:`writer` objects to never quote fields.
+ When the current *delimiter*, *quotechar*, *escapechar*, ``'\r'``, ``'\n'``
+ or any of the characters in *lineterminator* occurs in output data
+ it is preceded by the current *escapechar* character.
+ If *escapechar* is not set, the writer will raise :exc:`Error` if
any characters that require escaping are encountered.
+ Set *quotechar* to ``None`` to prevent its escaping.
Instructs :class:`reader` objects to perform no special processing of quote characters.
@@ -408,9 +417,16 @@ Dialects support the following attributes:
.. attribute:: Dialect.escapechar
- A one-character string used by the writer to escape the *delimiter* if *quoting*
- is set to :const:`QUOTE_NONE` and the *quotechar* if *doublequote* is
- :const:`False`. On reading, the *escapechar* removes any special meaning from
+ A one-character string used by the writer to escape characters that
+ require escaping:
+
+ * the *delimiter*, the *quotechar*, ``'\r'``, ``'\n'`` and any of the
+ characters in *lineterminator* are escaped if *quoting* is set to
+ :const:`QUOTE_NONE`;
+ * the *quotechar* is escaped if *doublequote* is :const:`False`;
+ * the *escapechar* itself.
+
+ On reading, the *escapechar* removes any special meaning from
the following character. It defaults to :const:`None`, which disables escaping.
.. versionchanged:: 3.11
@@ -430,9 +446,12 @@ Dialects support the following attributes:
.. attribute:: Dialect.quotechar
- A one-character string used to quote fields containing special characters, such
- as the *delimiter* or *quotechar*, or which contain new-line characters. It
- defaults to ``'"'``.
+ A one-character string used to quote fields containing special characters,
+ such as the *delimiter* or the *quotechar*, or which contain new-line
+ characters (``'\r'``, ``'\n'`` or any of the characters in *lineterminator*).
+ It defaults to ``'"'``.
+ Can be set to ``None`` to prevent escaping ``'"'`` if *quoting* is set
+ to :const:`QUOTE_NONE`.
.. versionchanged:: 3.11
An empty *quotechar* is not allowed.
@@ -441,7 +460,8 @@ Dialects support the following attributes:
Controls when quotes should be generated by the writer and recognised by the
reader. It can take on any of the :ref:`QUOTE_\* constants <csv-constants>`
- and defaults to :const:`QUOTE_MINIMAL`.
+ and defaults to :const:`QUOTE_MINIMAL` if *quotechar* is not ``None``,
+ and :const:`QUOTE_NONE` otherwise.
.. attribute:: Dialect.skipinitialspace
@@ -603,7 +623,7 @@ A slightly more advanced use of the reader --- catching and reporting errors::
for row in reader:
print(row)
except csv.Error as e:
- sys.exit('file {}, line {}: {}'.format(filename, reader.line_num, e))
+ sys.exit(f'file {filename}, line {reader.line_num}: {e}')
And while the module doesn't directly support parsing strings, it can easily be
done::
diff --git a/Doc/library/ctypes.rst b/Doc/library/ctypes.rst
index 5b733d5321e..846cece3761 100644
--- a/Doc/library/ctypes.rst
+++ b/Doc/library/ctypes.rst
@@ -714,10 +714,16 @@ item in the :attr:`~Structure._fields_` tuples::
... ("second_16", c_int, 16)]
...
>>> print(Int.first_16)
- <Field type=c_long, ofs=0:0, bits=16>
+ <ctypes.CField 'first_16' type=c_int, ofs=0, bit_size=16, bit_offset=0>
>>> print(Int.second_16)
- <Field type=c_long, ofs=0:16, bits=16>
- >>>
+ <ctypes.CField 'second_16' type=c_int, ofs=0, bit_size=16, bit_offset=16>
+
+It is important to note that bit field allocation and layout in memory are not
+defined as a C standard; their implementation is compiler-specific.
+By default, Python will attempt to match the behavior of a "native" compiler
+for the current platform.
+See the :attr:`~Structure._layout_` attribute for details on the default
+behavior and how to change it.
.. _ctypes-arrays:
@@ -876,7 +882,7 @@ invalid non-\ ``NULL`` pointers would crash Python)::
Thread safety without the GIL
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-In Python 3.13, the :term:`GIL` may be disabled on :term:`experimental free threaded <free threading>` builds.
+From Python 3.13 onward, the :term:`GIL` can be disabled on :term:`free threaded <free threading>` builds.
In ctypes, reads and writes to a single object concurrently is safe, but not across multiple objects:
.. code-block:: pycon
@@ -2031,35 +2037,55 @@ Utility functions
pointer.
-.. function:: create_string_buffer(init_or_size, size=None)
+.. function:: create_string_buffer(init, size=None)
+ create_string_buffer(size)
This function creates a mutable character buffer. The returned object is a
ctypes array of :class:`c_char`.
- *init_or_size* must be an integer which specifies the size of the array, or a
- bytes object which will be used to initialize the array items.
+ If *size* is given (and not ``None``), it must be an :class:`int`.
+ It specifies the size of the returned array.
+
+ If the *init* argument is given, it must be :class:`bytes`. It is used
+ to initialize the array items. Bytes not initialized this way are
+ set to zero (NUL).
+
+ If *size* is not given (or if it is ``None``), the buffer is made one element
+ larger than *init*, effectively adding a NUL terminator.
+
+ If both arguments are given, *size* must not be less than ``len(init)``.
- If a bytes object is specified as first argument, the buffer is made one item
- larger than its length so that the last element in the array is a NUL
- termination character. An integer can be passed as second argument which allows
- specifying the size of the array if the length of the bytes should not be used.
+ .. warning::
+
+ If *size* is equal to ``len(init)``, a NUL terminator is
+ not added. Do not treat such a buffer as a C string.
+
+ For example::
+
+ >>> bytes(create_string_buffer(2))
+ b'\x00\x00'
+ >>> bytes(create_string_buffer(b'ab'))
+ b'ab\x00'
+ >>> bytes(create_string_buffer(b'ab', 2))
+ b'ab'
+ >>> bytes(create_string_buffer(b'ab', 4))
+ b'ab\x00\x00'
+ >>> bytes(create_string_buffer(b'abcdef', 2))
+ Traceback (most recent call last):
+ ...
+ ValueError: byte string too long
.. audit-event:: ctypes.create_string_buffer init,size ctypes.create_string_buffer
-.. function:: create_unicode_buffer(init_or_size, size=None)
+.. function:: create_unicode_buffer(init, size=None)
+ create_unicode_buffer(size)
This function creates a mutable unicode character buffer. The returned object is
a ctypes array of :class:`c_wchar`.
- *init_or_size* must be an integer which specifies the size of the array, or a
- string which will be used to initialize the array items.
-
- If a string is specified as first argument, the buffer is made one item
- larger than the length of the string so that the last element in the array is a
- NUL termination character. An integer can be passed as second argument which
- allows specifying the size of the array if the length of the string should not
- be used.
+ The function takes the same arguments as :func:`~create_string_buffer` except
+ *init* must be a string and *size* counts :class:`c_wchar`.
.. audit-event:: ctypes.create_unicode_buffer init,size ctypes.create_unicode_buffer
@@ -2939,7 +2965,7 @@ fields, or any other data types containing pointer type fields.
.. attribute:: is_anonymous
True if this field is anonymous, that is, it contains nested sub-fields
- that should be be merged into a containing structure or union.
+ that should be merged into a containing structure or union.
.. _ctypes-arrays-pointers:
diff --git a/Doc/library/curses.rst b/Doc/library/curses.rst
index 137504c51b4..0b13c559295 100644
--- a/Doc/library/curses.rst
+++ b/Doc/library/curses.rst
@@ -68,7 +68,7 @@ The module :mod:`curses` defines the following exception:
The module :mod:`curses` defines the following functions:
-.. function:: assume_default_colors(fg, bg)
+.. function:: assume_default_colors(fg, bg, /)
Allow use of default values for colors on terminals supporting this feature.
Use this to support transparency in your application.
@@ -988,6 +988,10 @@ the following methods and attributes:
window.getstr(y, x, n)
Read a bytes object from the user, with primitive line editing capacity.
+ The maximum value for *n* is 2047.
+
+ .. versionchanged:: 3.14
+ The maximum value for *n* was increased from 1023 to 2047.
.. method:: window.getyx()
@@ -1079,6 +1083,10 @@ the following methods and attributes:
current cursor position, or at *y*, *x* if specified. Attributes are stripped
from the characters. If *n* is specified, :meth:`instr` returns a string
at most *n* characters long (exclusive of the trailing NUL).
+ The maximum value for *n* is 2047.
+
+ .. versionchanged:: 3.14
+ The maximum value for *n* was increased from 1023 to 2047.
.. method:: window.is_linetouched(line)
diff --git a/Doc/library/dataclasses.rst b/Doc/library/dataclasses.rst
index 72612211b43..299c8aa399c 100644
--- a/Doc/library/dataclasses.rst
+++ b/Doc/library/dataclasses.rst
@@ -121,8 +121,11 @@ Module contents
:meth:`!__le__`, :meth:`!__gt__`, or :meth:`!__ge__`, then
:exc:`TypeError` is raised.
- - *unsafe_hash*: If ``False`` (the default), a :meth:`~object.__hash__` method
- is generated according to how *eq* and *frozen* are set.
+ - *unsafe_hash*: If true, force ``dataclasses`` to create a
+ :meth:`~object.__hash__` method, even though it may not be safe to do so.
+ Otherwise, generate a :meth:`~object.__hash__` method according to how
+ *eq* and *frozen* are set.
+ The default value is ``False``.
:meth:`!__hash__` is used by built-in :meth:`hash`, and when objects are
added to hashed collections such as dictionaries and sets. Having a
@@ -304,9 +307,9 @@ Module contents
.. versionadded:: 3.10
- - ``doc``: optional docstring for this field.
+ - *doc*: optional docstring for this field.
- .. versionadded:: 3.13
+ .. versionadded:: 3.14
If the default value of a field is specified by a call to
:func:`!field`, then the class attribute for this field will be
diff --git a/Doc/library/datetime.rst b/Doc/library/datetime.rst
index 3470f42a6c6..16ed3215bc2 100644
--- a/Doc/library/datetime.rst
+++ b/Doc/library/datetime.rst
@@ -1502,11 +1502,11 @@ Instance methods:
returned by :func:`time.time`.
Naive :class:`.datetime` instances are assumed to represent local
- time and this method relies on the platform C :c:func:`mktime`
- function to perform the conversion. Since :class:`.datetime`
- supports wider range of values than :c:func:`mktime` on many
- platforms, this method may raise :exc:`OverflowError` or :exc:`OSError`
- for times far in the past or far in the future.
+ time and this method relies on platform C functions to perform
+ the conversion. Since :class:`.datetime` supports a wider range of
+ values than the platform C functions on many platforms, this
+ method may raise :exc:`OverflowError` or :exc:`OSError` for times
+ far in the past or far in the future.
For aware :class:`.datetime` instances, the return value is computed
as::
@@ -1519,6 +1519,10 @@ Instance methods:
The :meth:`timestamp` method uses the :attr:`.fold` attribute to
disambiguate the times during a repeated interval.
+ .. versionchanged:: 3.6
+ This method no longer relies on the platform C :c:func:`mktime`
+ function to perform conversions.
+
.. note::
There is no method to obtain the POSIX timestamp directly from a
diff --git a/Doc/library/dbm.rst b/Doc/library/dbm.rst
index 36221c026d6..39e287b1521 100644
--- a/Doc/library/dbm.rst
+++ b/Doc/library/dbm.rst
@@ -15,10 +15,16 @@
* :mod:`dbm.ndbm`
If none of these modules are installed, the
-slow-but-simple implementation in module :mod:`dbm.dumb` will be used. There
+slow-but-simple implementation in module :mod:`dbm.dumb` will be used. There
is a `third party interface <https://www.jcea.es/programacion/pybsddb.htm>`_ to
the Oracle Berkeley DB.
+.. note::
+ None of the underlying modules will automatically shrink the disk space used by
+ the database file. However, :mod:`dbm.sqlite3`, :mod:`dbm.gnu` and :mod:`dbm.dumb`
+ provide a :meth:`!reorganize` method that can be used for this purpose.
+
+
.. exception:: error
A tuple containing the exceptions that can be raised by each of the supported
@@ -186,6 +192,17 @@ or any other SQLite browser, including the SQLite CLI.
The Unix file access mode of the file (default: octal ``0o666``),
used only when the database has to be created.
+ .. method:: sqlite3.reorganize()
+
+ If you have carried out a lot of deletions and would like to shrink the space
+ used on disk, this method will reorganize the database; otherwise, deleted file
+ space will be kept and reused as new (key, value) pairs are added.
+
+ .. note::
+ While reorganizing, as much as two times the size of the original database is required
+ in free disk space. However, be aware that this factor changes for each :mod:`dbm` submodule.
+
+ .. versionadded:: next
:mod:`dbm.gnu` --- GNU database manager
---------------------------------------
@@ -237,6 +254,9 @@ functionality like crash tolerance.
* ``'s'``: Synchronized mode.
Changes to the database will be written immediately to the file.
* ``'u'``: Do not lock database.
+ * ``'m'``: Do not use :manpage:`mmap(2)`.
+ This may harm performance, but improve crash tolerance.
+ .. versionadded:: next
Not all flags are valid for all versions of GDBM.
See the :data:`open_flags` member for a list of supported flag characters.
@@ -284,6 +304,10 @@ functionality like crash tolerance.
reorganization; otherwise, deleted file space will be kept and reused as new
(key, value) pairs are added.
+ .. note::
+ While reorganizing, as much as one time the size of the original database is required
+ in free disk space. However, be aware that this factor changes for each :mod:`dbm` submodule.
+
.. method:: gdbm.sync()
When the database has been opened in fast mode, this method forces any
@@ -438,6 +462,11 @@ The :mod:`!dbm.dumb` module defines the following:
with a sufficiently large/complex entry due to stack depth limitations in
Python's AST compiler.
+ .. warning::
+ :mod:`dbm.dumb` does not support concurrent read/write access. (Multiple
+ simultaneous read accesses are safe.) When a program has the database open
+ for writing, no other program should have it open for reading or writing.
+
.. versionchanged:: 3.5
:func:`~dbm.dumb.open` always creates a new database when *flag* is ``'n'``.
@@ -460,3 +489,15 @@ The :mod:`!dbm.dumb` module defines the following:
.. method:: dumbdbm.close()
Close the database.
+
+ .. method:: dumbdbm.reorganize()
+
+ If you have carried out a lot of deletions and would like to shrink the space
+ used on disk, this method will reorganize the database; otherwise, deleted file
+ space will not be reused.
+
+ .. note::
+ While reorganizing, no additional free disk space is required. However, be aware
+ that this factor changes for each :mod:`dbm` submodule.
+
+ .. versionadded:: next
diff --git a/Doc/library/decimal.rst b/Doc/library/decimal.rst
index f53c1f34670..10ddfa02b43 100644
--- a/Doc/library/decimal.rst
+++ b/Doc/library/decimal.rst
@@ -2,7 +2,7 @@
=====================================================================
.. module:: decimal
- :synopsis: Implementation of the General Decimal Arithmetic Specification.
+ :synopsis: Implementation of the General Decimal Arithmetic Specification.
.. moduleauthor:: Eric Price <eprice at tjhsst.edu>
.. moduleauthor:: Facundo Batista <facundo at taniquetil.com.ar>
@@ -121,7 +121,7 @@ reset them before monitoring a calculation.
.. _decimal-tutorial:
-Quick-start Tutorial
+Quick-start tutorial
--------------------
The usual start to using decimals is importing the module, viewing the current
@@ -1096,40 +1096,52 @@ In addition to the three supplied contexts, new contexts can be created with the
default values are copied from the :const:`DefaultContext`. If the *flags*
field is not specified or is :const:`None`, all flags are cleared.
- *prec* is an integer in the range [``1``, :const:`MAX_PREC`] that sets
- the precision for arithmetic operations in the context.
+ .. attribute:: prec
- The *rounding* option is one of the constants listed in the section
- `Rounding Modes`_.
+ An integer in the range [``1``, :const:`MAX_PREC`] that sets
+ the precision for arithmetic operations in the context.
- The *traps* and *flags* fields list any signals to be set. Generally, new
- contexts should only set traps and leave the flags clear.
+ .. attribute:: rounding
- The *Emin* and *Emax* fields are integers specifying the outer limits allowable
- for exponents. *Emin* must be in the range [:const:`MIN_EMIN`, ``0``],
- *Emax* in the range [``0``, :const:`MAX_EMAX`].
+ One of the constants listed in the section `Rounding Modes`_.
- The *capitals* field is either ``0`` or ``1`` (the default). If set to
- ``1``, exponents are printed with a capital ``E``; otherwise, a
- lowercase ``e`` is used: ``Decimal('6.02e+23')``.
+ .. attribute:: traps
+ flags
- The *clamp* field is either ``0`` (the default) or ``1``.
- If set to ``1``, the exponent ``e`` of a :class:`Decimal`
- instance representable in this context is strictly limited to the
- range ``Emin - prec + 1 <= e <= Emax - prec + 1``. If *clamp* is
- ``0`` then a weaker condition holds: the adjusted exponent of
- the :class:`Decimal` instance is at most :attr:`~Context.Emax`. When *clamp* is
- ``1``, a large normal number will, where possible, have its
- exponent reduced and a corresponding number of zeros added to its
- coefficient, in order to fit the exponent constraints; this
- preserves the value of the number but loses information about
- significant trailing zeros. For example::
+ Lists of any signals to be set. Generally, new contexts should only set
+ traps and leave the flags clear.
- >>> Context(prec=6, Emax=999, clamp=1).create_decimal('1.23e999')
- Decimal('1.23000E+999')
+ .. attribute:: Emin
+ Emax
- A *clamp* value of ``1`` allows compatibility with the
- fixed-width decimal interchange formats specified in IEEE 754.
+ Integers specifying the outer limits allowable for exponents. *Emin* must
+ be in the range [:const:`MIN_EMIN`, ``0``], *Emax* in the range
+ [``0``, :const:`MAX_EMAX`].
+
+ .. attribute:: capitals
+
+ Either ``0`` or ``1`` (the default). If set to
+ ``1``, exponents are printed with a capital ``E``; otherwise, a
+ lowercase ``e`` is used: ``Decimal('6.02e+23')``.
+
+ .. attribute:: clamp
+
+ Either ``0`` (the default) or ``1``. If set to ``1``, the exponent ``e``
+ of a :class:`Decimal` instance representable in this context is strictly
+ limited to the range ``Emin - prec + 1 <= e <= Emax - prec + 1``.
+ If *clamp* is ``0`` then a weaker condition holds: the adjusted exponent of
+ the :class:`Decimal` instance is at most :attr:`~Context.Emax`. When *clamp* is
+ ``1``, a large normal number will, where possible, have its
+ exponent reduced and a corresponding number of zeros added to its
+ coefficient, in order to fit the exponent constraints; this
+ preserves the value of the number but loses information about
+ significant trailing zeros. For example::
+
+ >>> Context(prec=6, Emax=999, clamp=1).create_decimal('1.23e999')
+ Decimal('1.23000E+999')
+
+ A *clamp* value of ``1`` allows compatibility with the
+ fixed-width decimal interchange formats specified in IEEE 754.
The :class:`Context` class defines several general purpose methods as well as
a large number of methods for doing arithmetic directly in a given context.
@@ -1769,7 +1781,7 @@ The following table summarizes the hierarchy of signals::
.. _decimal-notes:
-Floating-Point Notes
+Floating-point notes
--------------------
diff --git a/Doc/library/dialog.rst b/Doc/library/dialog.rst
index 191e0da1210..e0693e8eb6e 100644
--- a/Doc/library/dialog.rst
+++ b/Doc/library/dialog.rst
@@ -220,7 +220,7 @@ is the base class for dialogs defined in other supporting modules.
.. class:: Dialog(master=None, **options)
- .. method:: show(color=None, **options)
+ .. method:: show(**options)
Render the Dialog window.
diff --git a/Doc/library/dis.rst b/Doc/library/dis.rst
index 44767b5dd2d..11685a32f48 100644
--- a/Doc/library/dis.rst
+++ b/Doc/library/dis.rst
@@ -1094,14 +1094,6 @@ iterations of the loop.
.. versionadded:: 3.14
-.. opcode:: LOAD_CONST_IMMORTAL (consti)
-
- Pushes ``co_consts[consti]`` onto the stack.
- Can be used when the constant value is known to be immortal.
-
- .. versionadded:: 3.14
-
-
.. opcode:: LOAD_NAME (namei)
Pushes the value associated with ``co_names[namei]`` onto the stack.
diff --git a/Doc/library/doctest.rst b/Doc/library/doctest.rst
index b86fef9fd6f..fb43cf918b8 100644
--- a/Doc/library/doctest.rst
+++ b/Doc/library/doctest.rst
@@ -174,7 +174,7 @@ with assorted summaries at the end.
You can force verbose mode by passing ``verbose=True`` to :func:`testmod`, or
prohibit it by passing ``verbose=False``. In either of those cases,
-``sys.argv`` is not examined by :func:`testmod` (so passing ``-v`` or not
+:data:`sys.argv` is not examined by :func:`testmod` (so passing ``-v`` or not
has no effect).
There is also a command line shortcut for running :func:`testmod`, see section
@@ -231,7 +231,7 @@ documentation::
As with :func:`testmod`, :func:`testfile` won't display anything unless an
example fails. If an example does fail, then the failing example(s) and the
cause(s) of the failure(s) are printed to stdout, using the same format as
-:func:`testmod`.
+:func:`!testmod`.
By default, :func:`testfile` looks for files in the calling module's directory.
See section :ref:`doctest-basic-api` for a description of the optional arguments
@@ -311,6 +311,9 @@ Which Docstrings Are Examined?
The module docstring, and all function, class and method docstrings are
searched. Objects imported into the module are not searched.
+.. attribute:: module.__test__
+ :no-typesetting:
+
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
@@ -533,7 +536,7 @@ Some details you should read once, but won't need to remember:
* The interactive shell omits the traceback header line for some
:exc:`SyntaxError`\ s. But doctest uses the traceback header line to
distinguish exceptions from non-exceptions. So in the rare case where you need
- to test a :exc:`SyntaxError` that omits the traceback header, you will need to
+ to test a :exc:`!SyntaxError` that omits the traceback header, you will need to
manually add the traceback header line to your test example.
.. index:: single: ^ (caret); marker
@@ -860,15 +863,15 @@ The :const:`ELLIPSIS` directive gives a nice approach for the last example:
<C object at 0x...>
Floating-point numbers are also subject to small output variations across
-platforms, because Python defers to the platform C library for float formatting,
-and C libraries vary widely in quality here. ::
+platforms, because Python defers to the platform C library for some
+floating-point calculations, and C libraries vary widely in quality here. ::
- >>> 1./7 # risky
- 0.14285714285714285
- >>> print(1./7) # safer
- 0.142857142857
- >>> print(round(1./7, 6)) # much safer
- 0.142857
+ >>> 1000**0.1 # risky
+ 1.9952623149688797
+ >>> round(1000**0.1, 9) # safer
+ 1.995262315
+ >>> print(f'{1000**0.1:.4f}') # much safer
+ 1.9953
Numbers of the form ``I/2.**J`` are safe across all platforms, and I often
contrive doctest examples to produce numbers of that form::
@@ -938,13 +941,13 @@ and :ref:`doctest-simple-testfile`.
Optional argument *verbose* prints lots of stuff if true, and prints only
failures if false; by default, or if ``None``, it's true if and only if ``'-v'``
- is in ``sys.argv``.
+ is in :data:`sys.argv`.
Optional argument *report* prints a summary at the end when true, else prints
nothing at the end. In verbose mode, the summary is detailed, else the summary
is very brief (in fact, empty if all tests passed).
- Optional argument *optionflags* (default value 0) takes the
+ Optional argument *optionflags* (default value ``0``) takes the
:ref:`bitwise OR <bitwise>` of option flags.
See section :ref:`doctest-options`.
@@ -1043,12 +1046,15 @@ from text files and modules with doctests:
Convert doctest tests from one or more text files to a
:class:`unittest.TestSuite`.
- The returned :class:`unittest.TestSuite` is to be run by the unittest framework
- and runs the interactive examples in each file. If an example in any file
- fails, then the synthesized unit test fails, and a :exc:`failureException`
- exception is raised showing the name of the file containing the test and a
- (sometimes approximate) line number. If all the examples in a file are
- skipped, then the synthesized unit test is also marked as skipped.
+ The returned :class:`unittest.TestSuite` is to be run by the unittest
+ framework and runs the interactive examples in each file.
+ Each file is run as a separate unit test, and each example in a file
+ is run as a :ref:`subtest <subtests>`.
+ If any example in a file fails, then the synthesized unit test fails.
+ The traceback for failure or error contains the name of the file
+ containing the test and a (sometimes approximate) line number.
+ If all the examples in a file are skipped, then the synthesized unit
+ test is also marked as skipped.
Pass one or more paths (as strings) to text files to be examined.
@@ -1078,13 +1084,14 @@ from text files and modules with doctests:
Optional argument *setUp* specifies a set-up function for the test suite.
This is called before running the tests in each file. The *setUp* function
- will be passed a :class:`DocTest` object. The setUp function can access the
- test globals as the *globs* attribute of the test passed.
+ will be passed a :class:`DocTest` object. The *setUp* function can access the
+ test globals as the :attr:`~DocTest.globs` attribute of the test passed.
Optional argument *tearDown* specifies a tear-down function for the test
suite. This is called after running the tests in each file. The *tearDown*
- function will be passed a :class:`DocTest` object. The setUp function can
- access the test globals as the *globs* attribute of the test passed.
+ function will be passed a :class:`DocTest` object. The *tearDown* function can
+ access the test globals as the :attr:`~DocTest.globs` attribute of the test
+ passed.
Optional argument *globs* is a dictionary containing the initial global
variables for the tests. A new copy of this dictionary is created for each
@@ -1105,16 +1112,22 @@ from text files and modules with doctests:
The global ``__file__`` is added to the globals provided to doctests loaded
from a text file using :func:`DocFileSuite`.
+ .. versionchanged:: next
+ Run each example as a :ref:`subtest <subtests>`.
+
.. function:: DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None, setUp=None, tearDown=None, optionflags=0, checker=None)
Convert doctest tests for a module to a :class:`unittest.TestSuite`.
- The returned :class:`unittest.TestSuite` is to be run by the unittest framework
- and runs each doctest in the module. If any of the doctests fail, then the
- synthesized unit test fails, and a :exc:`failureException` exception is raised
- showing the name of the file containing the test and a (sometimes approximate)
- line number. If all the examples in a docstring are skipped, then the
+ The returned :class:`unittest.TestSuite` is to be run by the unittest
+ framework and runs each doctest in the module.
+ Each docstring is run as a separate unit test, and each example in
+ a docstring is run as a :ref:`subtest <subtests>`.
+ If any of the doctests fail, then the synthesized unit test fails.
+ The traceback for failure or error contains the name of the file
+ containing the test and a (sometimes approximate) line number.
+ If all the examples in a docstring are skipped, then the
synthesized unit test is also marked as skipped.
Optional argument *module* provides the module to be tested. It can be a module
@@ -1123,7 +1136,7 @@ from text files and modules with doctests:
Optional argument *globs* is a dictionary containing the initial global
variables for the tests. A new copy of this dictionary is created for each
- test. By default, *globs* is a new empty dictionary.
+ test. By default, *globs* is the module's :attr:`~module.__dict__`.
Optional argument *extraglobs* specifies an extra set of global variables, which
is merged into *globs*. By default, no extra globals are used.
@@ -1132,7 +1145,7 @@ from text files and modules with doctests:
drop-in replacement) that is used to extract doctests from the module.
Optional arguments *setUp*, *tearDown*, and *optionflags* are the same as for
- function :func:`DocFileSuite` above.
+ function :func:`DocFileSuite` above, but they are called for each docstring.
This function uses the same search technique as :func:`testmod`.
@@ -1140,11 +1153,8 @@ 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.
+ .. versionchanged:: next
+ Run each example as a :ref:`subtest <subtests>`.
Under the covers, :func:`DocTestSuite` creates a :class:`unittest.TestSuite` out
of :class:`!doctest.DocTestCase` instances, and :class:`!DocTestCase` is a
@@ -1158,15 +1168,15 @@ 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
-: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
+: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
when and how tests get run. The framework author typically wants to control
-:mod:`doctest` reporting options (perhaps, e.g., specified by command line
-options), but there's no way to pass options through :mod:`unittest` to
-:mod:`doctest` test runners.
+:mod:`!doctest` reporting options (perhaps, e.g., specified by command line
+options), but there's no way to pass options through :mod:`!unittest` to
+:mod:`!doctest` test runners.
-For this reason, :mod:`doctest` also supports a notion of :mod:`doctest`
+For this reason, :mod:`doctest` also supports a notion of :mod:`!doctest`
reporting flags specific to :mod:`unittest` support, via this function:
@@ -1181,12 +1191,12 @@ reporting flags specific to :mod:`unittest` support, via this function:
: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
- :mod:`unittest` reporting flags are ignored.
+ :mod:`!unittest` reporting flags are ignored.
The value of the :mod:`unittest` reporting flags in effect before the function
was called is returned by the function.
@@ -1279,7 +1289,7 @@ DocTest Objects
.. attribute:: filename
The name of the file that this :class:`DocTest` was extracted from; or
- ``None`` if the filename is unknown, or if the :class:`DocTest` was not
+ ``None`` if the filename is unknown, or if the :class:`!DocTest` was not
extracted from a file.
@@ -1419,10 +1429,10 @@ DocTestFinder objects
The globals for each :class:`DocTest` is formed by combining *globs* and
*extraglobs* (bindings in *extraglobs* override bindings in *globs*). A new
- shallow copy of the globals dictionary is created for each :class:`DocTest`.
- If *globs* is not specified, then it defaults to the module's *__dict__*, if
- specified, or ``{}`` otherwise. If *extraglobs* is not specified, then it
- defaults to ``{}``.
+ shallow copy of the globals dictionary is created for each :class:`!DocTest`.
+ If *globs* is not specified, then it defaults to the module's
+ :attr:`~module.__dict__`, if specified, or ``{}`` otherwise.
+ If *extraglobs* is not specified, then it defaults to ``{}``.
.. _doctest-doctestparser:
@@ -1446,7 +1456,7 @@ DocTestParser objects
:class:`DocTest` object.
*globs*, *name*, *filename*, and *lineno* are attributes for the new
- :class:`DocTest` object. See the documentation for :class:`DocTest` for more
+ :class:`!DocTest` object. See the documentation for :class:`DocTest` for more
information.
@@ -1461,7 +1471,7 @@ DocTestParser objects
Divide the given string into examples and intervening text, and return them as
a list of alternating :class:`Example`\ s and strings. Line numbers for the
- :class:`Example`\ s are 0-based. The optional argument *name* is a name
+ :class:`!Example`\ s are 0-based. The optional argument *name* is a name
identifying this string, and is only used for error messages.
@@ -1501,14 +1511,14 @@ DocTestRunner objects
:class:`OutputChecker`. This comparison may be customized with a number of
option flags; see section :ref:`doctest-options` for more information. If the
option flags are insufficient, then the comparison may also be customized by
- passing a subclass of :class:`OutputChecker` to the constructor.
+ passing a subclass of :class:`!OutputChecker` to the constructor.
The test runner's display output can be controlled in two ways. First, an output
function can be passed to :meth:`run`; this function will be called
with strings that should be displayed. It defaults to ``sys.stdout.write``. If
capturing the output is not sufficient, then the display output can be also
customized by subclassing DocTestRunner, and overriding the methods
- :meth:`report_start`, :meth:`report_success`,
+ :meth:`report_skip`, :meth:`report_start`, :meth:`report_success`,
:meth:`report_unexpected_exception`, and :meth:`report_failure`.
The optional keyword argument *checker* specifies the :class:`OutputChecker`
@@ -1533,6 +1543,19 @@ DocTestRunner objects
:class:`DocTestRunner` defines the following methods:
+ .. method:: report_skip(out, test, example)
+
+ Report that the given example was skipped. This method is provided to
+ allow subclasses of :class:`DocTestRunner` to customize their output; it
+ should not be called directly.
+
+ *example* is the example about to be processed. *test* is the test
+ containing *example*. *out* is the output function that was passed to
+ :meth:`DocTestRunner.run`.
+
+ .. versionadded:: next
+
+
.. method:: report_start(out, test, example)
Report that the test runner is about to process the given example. This method
@@ -1540,7 +1563,7 @@ DocTestRunner objects
output; it should not be called directly.
*example* is the example about to be processed. *test* is the test
- *containing example*. *out* is the output function that was passed to
+ containing *example*. *out* is the output function that was passed to
:meth:`DocTestRunner.run`.
@@ -1940,7 +1963,7 @@ several options for organizing tests:
containing test cases for the named topics. These functions can be included in
the same file as the module, or separated out into a separate test file.
-* Define a ``__test__`` dictionary mapping from regression test topics to
+* Define a :attr:`~module.__test__` dictionary mapping from regression test topics to
docstrings containing test cases.
When you have placed your tests in a module, the module can itself be the test
diff --git a/Doc/library/email.header.rst b/Doc/library/email.header.rst
index 219fad0d2f6..f49885b8785 100644
--- a/Doc/library/email.header.rst
+++ b/Doc/library/email.header.rst
@@ -178,16 +178,36 @@ The :mod:`email.header` module also provides the following convenient functions.
Decode a message header value without converting the character set. The header
value is in *header*.
- This function returns a list of ``(decoded_string, charset)`` pairs containing
- each of the decoded parts of the header. *charset* is ``None`` for non-encoded
- parts of the header, otherwise a lower case string containing the name of the
- character set specified in the encoded string.
+ For historical reasons, this function may return either:
- Here's an example::
+ 1. A list of pairs containing each of the decoded parts of the header,
+ ``(decoded_bytes, charset)``, where *decoded_bytes* is always an instance of
+ :class:`bytes`, and *charset* is either:
+
+ - A lower case string containing the name of the character set specified.
+
+ - ``None`` for non-encoded parts of the header.
+
+ 2. A list of length 1 containing a pair ``(string, None)``, where
+ *string* is always an instance of :class:`str`.
+
+ An :exc:`email.errors.HeaderParseError` may be raised when certain decoding
+ errors occur (e.g. a base64 decoding exception).
+
+ Here are examples:
>>> from email.header import decode_header
>>> decode_header('=?iso-8859-1?q?p=F6stal?=')
[(b'p\xf6stal', 'iso-8859-1')]
+ >>> decode_header('unencoded_string')
+ [('unencoded_string', None)]
+ >>> decode_header('bar =?utf-8?B?ZsOzbw==?=')
+ [(b'bar ', None), (b'f\xc3\xb3o', 'utf-8')]
+
+ .. note::
+
+ This function exists for backwards compatibility only. For
+ new code, we recommend using :class:`email.headerregistry.HeaderRegistry`.
.. function:: make_header(decoded_seq, maxlinelen=None, header_name=None, continuation_ws=' ')
@@ -203,3 +223,7 @@ The :mod:`email.header` module also provides the following convenient functions.
:class:`Header` instance. Optional *maxlinelen*, *header_name*, and
*continuation_ws* are as in the :class:`Header` constructor.
+ .. note::
+
+ This function exists for backwards compatibility only, and is
+ not recommended for use in new code.
diff --git a/Doc/library/exceptions.rst b/Doc/library/exceptions.rst
index bb72032891e..9806ae80905 100644
--- a/Doc/library/exceptions.rst
+++ b/Doc/library/exceptions.rst
@@ -1048,7 +1048,7 @@ their subgroups based on the types of the contained exceptions.
subclasses that need a different constructor signature need to
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. ::
+ constructs the group's message from it. ::
class Errors(ExceptionGroup):
def __new__(cls, errors, exit_code):
diff --git a/Doc/library/faulthandler.rst b/Doc/library/faulthandler.rst
index 5058b85bffb..677966a8b2e 100644
--- a/Doc/library/faulthandler.rst
+++ b/Doc/library/faulthandler.rst
@@ -90,7 +90,7 @@ An error will be printed instead of the stack.
Additionally, some compilers do not support :term:`CPython's <CPython>`
implementation of C stack dumps. As a result, a different error may be printed
-instead of the stack, even if the the operating system supports dumping stacks.
+instead of the stack, even if the operating system supports dumping stacks.
.. note::
@@ -228,6 +228,41 @@ handler:
Fatal Python error: Segmentation fault
Current thread 0x00007fb899f39700 (most recent call first):
- File "/home/python/cpython/Lib/ctypes/__init__.py", line 486 in string_at
+ File "/opt/python/Lib/ctypes/__init__.py", line 486 in string_at
File "<stdin>", line 1 in <module>
+
+ Current thread's C stack trace (most recent call first):
+ Binary file "/opt/python/python", at _Py_DumpStack+0x42 [0x5b27f7d7147e]
+ Binary file "/opt/python/python", at +0x32dcbd [0x5b27f7d85cbd]
+ Binary file "/opt/python/python", at +0x32df8a [0x5b27f7d85f8a]
+ Binary file "/usr/lib/libc.so.6", at +0x3def0 [0x77b73226bef0]
+ Binary file "/usr/lib/libc.so.6", at +0x17ef9c [0x77b7323acf9c]
+ Binary file "/opt/python/build/lib.linux-x86_64-3.15/_ctypes.cpython-315d-x86_64-linux-gnu.so", at +0xcdf6 [0x77b7315dddf6]
+ Binary file "/usr/lib/libffi.so.8", at +0x7976 [0x77b73158f976]
+ Binary file "/usr/lib/libffi.so.8", at +0x413c [0x77b73158c13c]
+ Binary file "/usr/lib/libffi.so.8", at ffi_call+0x12e [0x77b73158ef0e]
+ Binary file "/opt/python/build/lib.linux-x86_64-3.15/_ctypes.cpython-315d-x86_64-linux-gnu.so", at +0x15a33 [0x77b7315e6a33]
+ Binary file "/opt/python/build/lib.linux-x86_64-3.15/_ctypes.cpython-315d-x86_64-linux-gnu.so", at +0x164fa [0x77b7315e74fa]
+ Binary file "/opt/python/build/lib.linux-x86_64-3.15/_ctypes.cpython-315d-x86_64-linux-gnu.so", at +0xc624 [0x77b7315dd624]
+ Binary file "/opt/python/python", at _PyObject_MakeTpCall+0xce [0x5b27f7b73883]
+ Binary file "/opt/python/python", at +0x11bab6 [0x5b27f7b73ab6]
+ Binary file "/opt/python/python", at PyObject_Vectorcall+0x23 [0x5b27f7b73b04]
+ Binary file "/opt/python/python", at _PyEval_EvalFrameDefault+0x490c [0x5b27f7cbb302]
+ Binary file "/opt/python/python", at +0x2818e6 [0x5b27f7cd98e6]
+ Binary file "/opt/python/python", at +0x281aab [0x5b27f7cd9aab]
+ Binary file "/opt/python/python", at PyEval_EvalCode+0xc5 [0x5b27f7cd9ba3]
+ Binary file "/opt/python/python", at +0x255957 [0x5b27f7cad957]
+ Binary file "/opt/python/python", at +0x255ab4 [0x5b27f7cadab4]
+ Binary file "/opt/python/python", at _PyEval_EvalFrameDefault+0x6c3e [0x5b27f7cbd634]
+ Binary file "/opt/python/python", at +0x2818e6 [0x5b27f7cd98e6]
+ Binary file "/opt/python/python", at +0x281aab [0x5b27f7cd9aab]
+ Binary file "/opt/python/python", at +0x11b6e1 [0x5b27f7b736e1]
+ Binary file "/opt/python/python", at +0x11d348 [0x5b27f7b75348]
+ Binary file "/opt/python/python", at +0x11d626 [0x5b27f7b75626]
+ Binary file "/opt/python/python", at PyObject_Call+0x20 [0x5b27f7b7565e]
+ Binary file "/opt/python/python", at +0x32a67a [0x5b27f7d8267a]
+ Binary file "/opt/python/python", at +0x32a7f8 [0x5b27f7d827f8]
+ Binary file "/opt/python/python", at +0x32ac1b [0x5b27f7d82c1b]
+ Binary file "/opt/python/python", at Py_RunMain+0x31 [0x5b27f7d82ebe]
+ <truncated rest of calls>
Segmentation fault
diff --git a/Doc/library/functions.rst b/Doc/library/functions.rst
index 7e367a0f2b6..80bd1275973 100644
--- a/Doc/library/functions.rst
+++ b/Doc/library/functions.rst
@@ -1154,44 +1154,44 @@ are always available. They are listed here in alphabetical order.
.. function:: locals()
- Return a mapping object representing the current local symbol table, with
- variable names as the keys, and their currently bound references as the
- values.
-
- At module scope, as well as when using :func:`exec` or :func:`eval` with
- a single namespace, this function returns the same namespace as
- :func:`globals`.
-
- At class scope, it returns the namespace that will be passed to the
- metaclass constructor.
-
- When using ``exec()`` or ``eval()`` with separate local and global
- arguments, it returns the local namespace passed in to the function call.
-
- In all of the above cases, each call to ``locals()`` in a given frame of
- execution will return the *same* mapping object. Changes made through
- the mapping object returned from ``locals()`` will be visible as assigned,
- reassigned, or deleted local variables, and assigning, reassigning, or
- deleting local variables will immediately affect the contents of the
- returned mapping object.
-
- In an :term:`optimized scope` (including functions, generators, and
- coroutines), each call to ``locals()`` instead returns a fresh dictionary
- containing the current bindings of the function's local variables and any
- nonlocal cell references. In this case, name binding changes made via the
- returned dict are *not* written back to the corresponding local variables
- or nonlocal cell references, and assigning, reassigning, or deleting local
- variables and nonlocal cell references does *not* affect the contents
- of previously returned dictionaries.
-
- Calling ``locals()`` as part of a comprehension in a function, generator, or
- coroutine is equivalent to calling it in the containing scope, except that
- the comprehension's initialised iteration variables will be included. In
- other scopes, it behaves as if the comprehension were running as a nested
- function.
-
- Calling ``locals()`` as part of a generator expression is equivalent to
- calling it in a nested generator function.
+ Return a mapping object representing the current local symbol table, with
+ variable names as the keys, and their currently bound references as the
+ values.
+
+ At module scope, as well as when using :func:`exec` or :func:`eval` with
+ a single namespace, this function returns the same namespace as
+ :func:`globals`.
+
+ At class scope, it returns the namespace that will be passed to the
+ metaclass constructor.
+
+ When using ``exec()`` or ``eval()`` with separate local and global
+ arguments, it returns the local namespace passed in to the function call.
+
+ In all of the above cases, each call to ``locals()`` in a given frame of
+ execution will return the *same* mapping object. Changes made through
+ the mapping object returned from ``locals()`` will be visible as assigned,
+ reassigned, or deleted local variables, and assigning, reassigning, or
+ deleting local variables will immediately affect the contents of the
+ returned mapping object.
+
+ In an :term:`optimized scope` (including functions, generators, and
+ coroutines), each call to ``locals()`` instead returns a fresh dictionary
+ containing the current bindings of the function's local variables and any
+ nonlocal cell references. In this case, name binding changes made via the
+ returned dict are *not* written back to the corresponding local variables
+ or nonlocal cell references, and assigning, reassigning, or deleting local
+ variables and nonlocal cell references does *not* affect the contents
+ of previously returned dictionaries.
+
+ Calling ``locals()`` as part of a comprehension in a function, generator, or
+ coroutine is equivalent to calling it in the containing scope, except that
+ the comprehension's initialised iteration variables will be included. In
+ other scopes, it behaves as if the comprehension were running as a nested
+ function.
+
+ Calling ``locals()`` as part of a generator expression is equivalent to
+ calling it in a nested generator function.
.. versionchanged:: 3.12
The behaviour of ``locals()`` in a comprehension has been updated as
@@ -1839,15 +1839,15 @@ are always available. They are listed here in alphabetical order.
``range(start, stop, step)``. The *start* and *step* arguments default to
``None``.
+ 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.
+
.. 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
diff --git a/Doc/library/hashlib.rst b/Doc/library/hashlib.rst
index bb2d2fad23b..8bba6700930 100644
--- a/Doc/library/hashlib.rst
+++ b/Doc/library/hashlib.rst
@@ -94,6 +94,13 @@ accessible by name via :func:`new`. See :data:`algorithms_available`.
OpenSSL does not provide we fall back to a verified implementation from
the `HACL\* project`_.
+.. deprecated-removed:: 3.15 3.19
+ The undocumented ``string`` keyword parameter in :func:`!_hashlib.new`
+ and hash-named constructors such as :func:`!_md5.md5` is deprecated.
+ Prefer passing the initial data as a positional argument for maximum
+ backwards compatibility.
+
+
Usage
-----
@@ -284,7 +291,7 @@ a file or file-like object.
Example:
>>> import io, hashlib, hmac
- >>> with open(hashlib.__file__, "rb") as f:
+ >>> with open("library/hashlib.rst", "rb") as f:
... digest = hashlib.file_digest(f, "sha256")
...
>>> digest.hexdigest() # doctest: +ELLIPSIS
diff --git a/Doc/library/http.server.rst b/Doc/library/http.server.rst
index 54df4a7e804..063344e0284 100644
--- a/Doc/library/http.server.rst
+++ b/Doc/library/http.server.rst
@@ -429,8 +429,7 @@ instantiation, of which this module provides three different variants:
``'Last-Modified:'`` header with the file's modification time.
Then follows a blank line signifying the end of the headers, and then the
- contents of the file are output. If the file's MIME type starts with
- ``text/`` the file is opened in text mode; otherwise binary mode is used.
+ contents of the file are output.
For example usage, see the implementation of the ``test`` function
in :source:`Lib/http/server.py`.
@@ -459,55 +458,6 @@ such as using different index file names by overriding the class attribute
:attr:`index_pages`.
-.. class:: CGIHTTPRequestHandler(request, client_address, server)
-
- This class is used to serve either files or output of CGI scripts from the
- current directory and below. Note that mapping HTTP hierarchic structure to
- local directory structure is exactly as in :class:`SimpleHTTPRequestHandler`.
-
- .. note::
-
- CGI scripts run by the :class:`CGIHTTPRequestHandler` class cannot execute
- redirects (HTTP code 302), because code 200 (script output follows) is
- sent prior to execution of the CGI script. This pre-empts the status
- code.
-
- The class will however, run the CGI script, instead of serving it as a file,
- if it guesses it to be a CGI script. Only directory-based CGI are used ---
- the other common server configuration is to treat special extensions as
- denoting CGI scripts.
-
- The :func:`do_GET` and :func:`do_HEAD` functions are modified to run CGI scripts
- and serve the output, instead of serving files, if the request leads to
- somewhere below the ``cgi_directories`` path.
-
- The :class:`CGIHTTPRequestHandler` defines the following data member:
-
- .. attribute:: cgi_directories
-
- This defaults to ``['/cgi-bin', '/htbin']`` and describes directories to
- treat as containing CGI scripts.
-
- The :class:`CGIHTTPRequestHandler` defines the following method:
-
- .. method:: do_POST()
-
- This method serves the ``'POST'`` request type, only allowed for CGI
- scripts. Error 501, "Can only POST to CGI scripts", is output when trying
- to POST to a non-CGI url.
-
- Note that CGI scripts will be run with UID of user nobody, for security
- reasons. Problems with the CGI script will be translated to error 403.
-
- .. deprecated-removed:: 3.13 3.15
-
- :class:`CGIHTTPRequestHandler` is being removed in 3.15. CGI has not
- been considered a good way to do things for well over a decade. This code
- has been unmaintained for a while now and sees very little practical use.
- Retaining it could lead to further :ref:`security considerations
- <http.server-security>`.
-
-
.. _http-server-cli:
Command-line interface
@@ -564,24 +514,6 @@ The following options are accepted:
.. versionadded:: 3.11
-.. option:: --cgi
-
- :class:`CGIHTTPRequestHandler` can be enabled in the command line by passing
- the ``--cgi`` option::
-
- python -m http.server --cgi
-
- .. deprecated-removed:: 3.13 3.15
-
- :mod:`http.server` command line ``--cgi`` support is being removed
- because :class:`CGIHTTPRequestHandler` is being removed.
-
-.. warning::
-
- :class:`CGIHTTPRequestHandler` and the ``--cgi`` command-line option
- are not intended for use by untrusted clients and may be vulnerable
- to exploitation. Always use within a secure environment.
-
.. option:: --tls-cert
Specifies a TLS certificate chain for HTTPS connections::
diff --git a/Doc/library/importlib.resources.abc.rst b/Doc/library/importlib.resources.abc.rst
index 7a77466bcba..8253a33f591 100644
--- a/Doc/library/importlib.resources.abc.rst
+++ b/Doc/library/importlib.resources.abc.rst
@@ -49,44 +49,44 @@
.. method:: open_resource(resource)
:abstractmethod:
- Returns an opened, :term:`file-like object` for binary reading
- of the *resource*.
+ Returns an opened, :term:`file-like object` for binary reading
+ of the *resource*.
- If the resource cannot be found, :exc:`FileNotFoundError` is
- raised.
+ If the resource cannot be found, :exc:`FileNotFoundError` is
+ raised.
.. method:: resource_path(resource)
:abstractmethod:
- Returns the file system path to the *resource*.
+ Returns the file system path to the *resource*.
- If the resource does not concretely exist on the file system,
- raise :exc:`FileNotFoundError`.
+ If the resource does not concretely exist on the file system,
+ raise :exc:`FileNotFoundError`.
.. method:: is_resource(name)
:abstractmethod:
- Returns ``True`` if the named *name* is considered a resource.
- :exc:`FileNotFoundError` is raised if *name* does not exist.
+ Returns ``True`` if the named *name* is considered a resource.
+ :exc:`FileNotFoundError` is raised if *name* does not exist.
.. method:: contents()
:abstractmethod:
- Returns an :term:`iterable` of strings over the contents of
- the package. Do note that it is not required that all names
- returned by the iterator be actual resources, e.g. it is
- acceptable to return names for which :meth:`is_resource` would
- be false.
-
- Allowing non-resource names to be returned is to allow for
- situations where how a package and its resources are stored
- are known a priori and the non-resource names would be useful.
- For instance, returning subdirectory names is allowed so that
- when it is known that the package and resources are stored on
- the file system then those subdirectory names can be used
- directly.
-
- The abstract method returns an iterable of no items.
+ Returns an :term:`iterable` of strings over the contents of
+ the package. Do note that it is not required that all names
+ returned by the iterator be actual resources, e.g. it is
+ acceptable to return names for which :meth:`is_resource` would
+ be false.
+
+ Allowing non-resource names to be returned is to allow for
+ situations where how a package and its resources are stored
+ are known a priori and the non-resource names would be useful.
+ For instance, returning subdirectory names is allowed so that
+ when it is known that the package and resources are stored on
+ the file system then those subdirectory names can be used
+ directly.
+
+ The abstract method returns an iterable of no items.
.. class:: Traversable
diff --git a/Doc/library/io.rst b/Doc/library/io.rst
index 3aa2f35f05e..de5cab5aee6 100644
--- a/Doc/library/io.rst
+++ b/Doc/library/io.rst
@@ -528,14 +528,13 @@ I/O Base Classes
It inherits from :class:`IOBase`.
The main difference with :class:`RawIOBase` is that methods :meth:`read`,
- :meth:`readinto` and :meth:`write` will try (respectively) to read as much
- input as requested or to consume all given output, at the expense of
- making perhaps more than one system call.
+ :meth:`readinto` and :meth:`write` will try (respectively) to read
+ as much input as requested or to emit all provided data.
- In addition, those methods can raise :exc:`BlockingIOError` if the
- underlying raw stream is in non-blocking mode and cannot take or give
- enough data; unlike their :class:`RawIOBase` counterparts, they will
- never return ``None``.
+ In addition, if the underlying raw stream is in non-blocking mode, when the
+ system returns would block :meth:`write` will raise :exc:`BlockingIOError`
+ with :attr:`BlockingIOError.characters_written` and :meth:`read` will return
+ data read so far or ``None`` if no data is available.
Besides, the :meth:`read` method does not have a default
implementation that defers to :meth:`readinto`.
@@ -568,29 +567,40 @@ I/O Base Classes
.. method:: read(size=-1, /)
- Read and return up to *size* bytes. If the argument is omitted, ``None``,
- or negative, data is read and returned until EOF is reached. An empty
- :class:`bytes` object is returned if the stream is already at EOF.
+ Read and return up to *size* bytes. If the argument is omitted, ``None``,
+ or negative read as much as possible.
- If the argument is positive, and the underlying raw stream is not
- interactive, multiple raw reads may be issued to satisfy the byte count
- (unless EOF is reached first). But for interactive raw streams, at most
- one raw read will be issued, and a short result does not imply that EOF is
- imminent.
+ Fewer bytes may be returned than requested. An empty :class:`bytes` object
+ is returned if the stream is already at EOF. More than one read may be
+ made and calls may be retried if specific errors are encountered, see
+ :meth:`os.read` and :pep:`475` for more details. Less than size bytes
+ being returned does not imply that EOF is imminent.
- A :exc:`BlockingIOError` is raised if the underlying raw stream is in
- non blocking-mode, and has no data available at the moment.
+ When reading as much as possible the default implementation will use
+ ``raw.readall`` if available (which should implement
+ :meth:`RawIOBase.readall`), otherwise will read in a loop until read
+ returns ``None``, an empty :class:`bytes`, or a non-retryable error. For
+ most streams this is to EOF, but for non-blocking streams more data may
+ become available.
+
+ .. note::
+
+ When the underlying raw stream is non-blocking, implementations may
+ either raise :exc:`BlockingIOError` or return ``None`` if no data is
+ available. :mod:`io` implementations return ``None``.
.. method:: read1(size=-1, /)
- Read and return up to *size* bytes, with at most one call to the
- underlying raw stream's :meth:`~RawIOBase.read` (or
- :meth:`~RawIOBase.readinto`) method. This can be useful if you are
- implementing your own buffering on top of a :class:`BufferedIOBase`
- object.
+ Read and return up to *size* bytes, calling :meth:`~RawIOBase.readinto`
+ which may retry if :py:const:`~errno.EINTR` is encountered per
+ :pep:`475`. If *size* is ``-1`` or not provided, the implementation will
+ choose an arbitrary value for *size*.
- If *size* is ``-1`` (the default), an arbitrary number of bytes are
- returned (more than zero unless EOF is reached).
+ .. note::
+
+ When the underlying raw stream is non-blocking, implementations may
+ either raise :exc:`BlockingIOError` or return ``None`` if no data is
+ available. :mod:`io` implementations return ``None``.
.. method:: readinto(b, /)
@@ -767,34 +777,21 @@ than raw I/O does.
.. method:: peek(size=0, /)
- Return bytes from the stream without advancing the position. At most one
- single read on the raw stream is done to satisfy the call. The number of
- bytes returned may be less or more than requested.
+ Return bytes from the stream without advancing the position. The number of
+ bytes returned may be less or more than requested. If the underlying raw
+ stream is non-blocking and the operation would block, returns empty bytes.
.. method:: read(size=-1, /)
- Read and return *size* bytes, or if *size* is not given or negative, until
- EOF or if the read call would block in non-blocking mode.
-
- .. note::
-
- When the underlying raw stream is non-blocking, a :exc:`BlockingIOError`
- may be raised if a read operation cannot be completed immediately.
+ In :class:`BufferedReader` this is the same as :meth:`io.BufferedIOBase.read`
.. method:: read1(size=-1, /)
- Read and return up to *size* bytes with only one call on the raw stream.
- If at least one byte is buffered, only buffered bytes are returned.
- Otherwise, one raw stream read call is made.
+ In :class:`BufferedReader` this is the same as :meth:`io.BufferedIOBase.read1`
.. versionchanged:: 3.7
The *size* argument is now optional.
- .. note::
-
- When the underlying raw stream is non-blocking, a :exc:`BlockingIOError`
- may be raised if a read operation cannot be completed immediately.
-
.. class:: BufferedWriter(raw, buffer_size=DEFAULT_BUFFER_SIZE)
A buffered binary stream providing higher-level access to a writeable, non
@@ -826,8 +823,8 @@ than raw I/O does.
Write the :term:`bytes-like object`, *b*, and return the
number of bytes written. When in non-blocking mode, a
- :exc:`BlockingIOError` is raised if the buffer needs to be written out but
- the raw stream blocks.
+ :exc:`BlockingIOError` with :attr:`BlockingIOError.characters_written` set
+ is raised if the buffer needs to be written out but the raw stream blocks.
.. class:: BufferedRandom(raw, buffer_size=DEFAULT_BUFFER_SIZE)
@@ -894,9 +891,10 @@ Text I/O
.. attribute:: buffer
- The underlying binary buffer (a :class:`BufferedIOBase` instance) that
- :class:`TextIOBase` deals with. This is not part of the
- :class:`TextIOBase` API and may not exist in some implementations.
+ The underlying binary buffer (a :class:`BufferedIOBase`
+ or :class:`RawIOBase` instance) that :class:`TextIOBase` deals with.
+ This is not part of the :class:`TextIOBase` API and may not exist
+ in some implementations.
.. method:: detach()
diff --git a/Doc/library/json.rst b/Doc/library/json.rst
index 26579ec6328..12a5a96a3c5 100644
--- a/Doc/library/json.rst
+++ b/Doc/library/json.rst
@@ -18,12 +18,17 @@ is a lightweight data interchange format inspired by
`JavaScript <https://en.wikipedia.org/wiki/JavaScript>`_ object literal syntax
(although it is not a strict subset of JavaScript [#rfc-errata]_ ).
+.. note::
+ The term "object" in the context of JSON processing in Python can be
+ ambiguous. All values in Python are objects. In JSON, an object refers to
+ any data wrapped in curly braces, similar to a Python dictionary.
+
.. warning::
Be cautious when parsing JSON data from untrusted sources. A malicious
JSON string may cause the decoder to consume considerable CPU and memory
resources. Limiting the size of data to be parsed is recommended.
-:mod:`json` exposes an API familiar to users of the standard library
+This module exposes an API familiar to users of the standard library
:mod:`marshal` and :mod:`pickle` modules.
Encoding basic Python object hierarchies::
@@ -60,7 +65,7 @@ Pretty printing::
"6": 7
}
-Specializing JSON object encoding::
+Customizing JSON object encoding::
>>> import json
>>> def custom_json(obj):
@@ -83,7 +88,7 @@ Decoding JSON::
>>> json.load(io)
['streaming API']
-Specializing JSON object decoding::
+Customizing JSON object decoding::
>>> import json
>>> def as_complex(dct):
@@ -279,7 +284,7 @@ Basic Usage
:param object_hook:
If set, a function that is called with the result of
- any object literal decoded (a :class:`dict`).
+ any JSON object literal decoded (a :class:`dict`).
The return value of this function will be used
instead of the :class:`dict`.
This feature can be used to implement custom decoders,
@@ -289,7 +294,7 @@ Basic Usage
:param object_pairs_hook:
If set, a function that is called with the result of
- any object literal decoded with an ordered list of pairs.
+ any JSON object literal decoded with an ordered list of pairs.
The return value of this function will be used
instead of the :class:`dict`.
This feature can be used to implement custom decoders.
diff --git a/Doc/library/logging.config.rst b/Doc/library/logging.config.rst
index 0e9dc33ae21..96cca3073fe 100644
--- a/Doc/library/logging.config.rst
+++ b/Doc/library/logging.config.rst
@@ -548,7 +548,7 @@ mnemonic that the corresponding value is a callable.
The ``filters`` member of ``handlers`` and ``loggers`` can take
filter instances in addition to ids.
-You can also specify a special key ``'.'`` whose value is a dictionary is a
+You can also specify a special key ``'.'`` whose value is a
mapping of attribute names to values. If found, the specified attributes will
be set on the user-defined object before it is returned. Thus, with the
following configuration::
@@ -586,7 +586,7 @@ configuration dictionary for the handler named ``foo``, and later (once that
handler has been configured) it points to the configured handler instance.
Thus, ``cfg://handlers.foo`` could resolve to either a dictionary or a handler
instance. In general, it is wise to name handlers in a way such that dependent
-handlers are configured _after_ any handlers they depend on; that allows
+handlers are configured *after* any handlers they depend on; that allows
something like ``cfg://handlers.foo`` to be used in configuring a handler that
depends on handler ``foo``. If that dependent handler were named ``bar``,
problems would result, because the configuration of ``bar`` would be attempted
diff --git a/Doc/library/logging.handlers.rst b/Doc/library/logging.handlers.rst
index 63ef533e82c..d74ef73ee28 100644
--- a/Doc/library/logging.handlers.rst
+++ b/Doc/library/logging.handlers.rst
@@ -352,6 +352,10 @@ module, supports rotation of disk log files.
Outputs the record to the file, catering for rollover as described
previously.
+ .. method:: shouldRollover(record)
+
+ See if the supplied record would cause the file to exceed the configured size limit.
+
.. _timed-rotating-file-handler:
TimedRotatingFileHandler
@@ -459,7 +463,11 @@ timed intervals.
.. method:: getFilesToDelete()
Returns a list of filenames which should be deleted as part of rollover. These
- are the absolute paths of the oldest backup log files written by the handler.
+
+ .. method:: shouldRollover(record)
+
+ See if enough time has passed for a rollover to occur and if it has, compute
+ the next rollover time.
.. _socket-handler:
@@ -1051,6 +1059,15 @@ possible, while any potentially slow operations (such as sending an email via
.. note:: If you are using :mod:`multiprocessing`, you should avoid using
:class:`~queue.SimpleQueue` and instead use :class:`multiprocessing.Queue`.
+ .. warning::
+
+ The :mod:`multiprocessing` module uses an internal logger created and
+ accessed via :meth:`~multiprocessing.get_logger`.
+ :class:`multiprocessing.Queue` will log ``DEBUG`` level messages upon
+ items being queued. If those log messages are processed by a
+ :class:`QueueHandler` using the same :class:`multiprocessing.Queue` instance,
+ it will cause a deadlock or infinite recursion.
+
.. method:: emit(record)
Enqueues the result of preparing the LogRecord. Should an exception
diff --git a/Doc/library/logging.rst b/Doc/library/logging.rst
index 72190e97240..4509da58916 100644
--- a/Doc/library/logging.rst
+++ b/Doc/library/logging.rst
@@ -1342,8 +1342,9 @@ functions.
.. function:: basicConfig(**kwargs)
- Does basic configuration for the logging system by creating a
- :class:`StreamHandler` with a default :class:`Formatter` and adding it to the
+ Does basic configuration for the logging system by either creating a
+ :class:`StreamHandler` with a default :class:`Formatter`
+ or using the given *formatter* instance, and adding it to the
root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
:func:`error` and :func:`critical` will call :func:`basicConfig` automatically
if no handlers are defined for the root logger.
@@ -1428,6 +1429,19 @@ functions.
| | which means that it will be treated the |
| | same as passing 'errors'. |
+--------------+---------------------------------------------+
+ | *formatter* | If specified, set this formatter instance |
+ | | (see :ref:`formatter-objects`) |
+ | | for all involved handlers. |
+ | | If not specified, the default is to create |
+ | | and use an instance of |
+ | | :class:`logging.Formatter` based on |
+ | | arguments *format*, *datefmt* and *style*. |
+ | | When *formatter* is specified together with |
+ | | any of the three arguments *format*, |
+ | | *datefmt* and *style*, a ``ValueError`` is |
+ | | raised to signal that these arguments would |
+ | | lose meaning otherwise. |
+ +--------------+---------------------------------------------+
.. versionchanged:: 3.2
The *style* argument was added.
@@ -1444,6 +1458,9 @@ functions.
.. versionchanged:: 3.9
The *encoding* and *errors* arguments were added.
+ .. versionchanged:: 3.15
+ The *formatter* argument was added.
+
.. function:: shutdown()
Informs the logging system to perform an orderly shutdown by flushing and
diff --git a/Doc/library/math.rst b/Doc/library/math.rst
index 394a462b946..bf7a00549fc 100644
--- a/Doc/library/math.rst
+++ b/Doc/library/math.rst
@@ -10,8 +10,8 @@
--------------
-This module provides access to the mathematical functions defined by the C
-standard.
+This module provides access to common mathematical functions and constants,
+including those defined by the C standard.
These functions cannot be used with complex numbers; use the functions of the
same name from the :mod:`cmath` module if you require support for complex
@@ -53,10 +53,13 @@ noted otherwise, all return values are floats.
:func:`frexp(x) <frexp>` Mantissa and exponent of *x*
:func:`isclose(a, b, rel_tol, abs_tol) <isclose>` Check if the values *a* and *b* are close to each other
:func:`isfinite(x) <isfinite>` Check if *x* is neither an infinity nor a NaN
+:func:`isnormal(x) <isnormal>` Check if *x* is a normal number
+:func:`issubnormal(x) <issubnormal>` Check if *x* is a subnormal number
:func:`isinf(x) <isinf>` Check if *x* is a positive or negative infinity
:func:`isnan(x) <isnan>` Check if *x* is a NaN (not a number)
:func:`ldexp(x, i) <ldexp>` ``x * (2**i)``, inverse of function :func:`frexp`
:func:`nextafter(x, y, steps) <nextafter>` Floating-point value *steps* steps after *x* towards *y*
+:func:`signbit(x) <signbit>` Check if *x* is a negative number
:func:`ulp(x) <ulp>` Value of the least significant bit of *x*
**Power, exponential and logarithmic functions**
@@ -373,6 +376,24 @@ Floating point manipulation functions
.. versionadded:: 3.2
+.. function:: isnormal(x)
+
+ Return ``True`` if *x* is a normal number, that is a finite
+ nonzero number that is not a subnormal (see :func:`issubnormal`).
+ Return ``False`` otherwise.
+
+ .. versionadded:: next
+
+
+.. function:: issubnormal(x)
+
+ Return ``True`` if *x* is a subnormal number, that is a finite
+ nonzero number with a magnitude smaller than :data:`sys.float_info.min`.
+ Return ``False`` otherwise.
+
+ .. versionadded:: next
+
+
.. function:: isinf(x)
Return ``True`` if *x* is a positive or negative infinity, and
@@ -411,6 +432,15 @@ Floating point manipulation functions
Added the *steps* argument.
+.. function:: signbit(x)
+
+ Return ``True`` if the sign of *x* is negative and ``False`` otherwise.
+
+ This is useful to detect the sign bit of zeroes, infinities and NaNs.
+
+ .. versionadded:: next
+
+
.. function:: ulp(x)
Return the value of the least significant bit of the float *x*:
@@ -774,7 +804,7 @@ Constants
The mathematical constant *τ* = 6.283185..., to available precision.
Tau is a circle constant equal to 2\ *π*, the ratio of a circle's circumference to
its radius. To learn more about Tau, check out Vi Hart's video `Pi is (still)
- Wrong <https://www.youtube.com/watch?v=jG7vhMMXagQ>`_, and start celebrating
+ Wrong <https://vimeo.com/147792667>`_, and start celebrating
`Tau day <https://tauday.com/>`_ by eating twice as much pie!
.. versionadded:: 3.6
diff --git a/Doc/library/mmap.rst b/Doc/library/mmap.rst
index 4e20c07331a..8fca79b23e4 100644
--- a/Doc/library/mmap.rst
+++ b/Doc/library/mmap.rst
@@ -269,7 +269,7 @@ To map anonymous memory, -1 should be passed as the fileno along with the length
Resizing a map created with *access* of :const:`ACCESS_READ` or
:const:`ACCESS_COPY`, will raise a :exc:`TypeError` exception.
- Resizing a map created with with *trackfd* set to ``False``,
+ Resizing a map created with *trackfd* set to ``False``,
will raise a :exc:`ValueError` exception.
**On Windows**: Resizing the map will raise an :exc:`OSError` if there are other
diff --git a/Doc/library/multiprocessing.rst b/Doc/library/multiprocessing.rst
index 6c43d5fe166..fc3c1134f97 100644
--- a/Doc/library/multiprocessing.rst
+++ b/Doc/library/multiprocessing.rst
@@ -1081,7 +1081,7 @@ Miscellaneous
.. function:: freeze_support()
Add support for when a program which uses :mod:`multiprocessing` has been
- frozen to produce a Windows executable. (Has been tested with **py2exe**,
+ frozen to produce an executable. (Has been tested with **py2exe**,
**PyInstaller** and **cx_Freeze**.)
One needs to call this function straight after the ``if __name__ ==
@@ -1099,10 +1099,10 @@ Miscellaneous
If the ``freeze_support()`` line is omitted then trying to run the frozen
executable will raise :exc:`RuntimeError`.
- Calling ``freeze_support()`` has no effect when invoked on any operating
- system other than Windows. In addition, if the module is being run
- normally by the Python interpreter on Windows (the program has not been
- frozen), then ``freeze_support()`` has no effect.
+ Calling ``freeze_support()`` has no effect when the start method is not
+ *spawn*. In addition, if the module is being run normally by the Python
+ interpreter (the program has not been frozen), then ``freeze_support()``
+ has no effect.
.. function:: get_all_start_methods()
@@ -1369,6 +1369,12 @@ object -- see :ref:`multiprocessing-managers`.
A solitary difference from its close analog exists: its ``acquire`` method's
first argument is named *block*, as is consistent with :meth:`Lock.acquire`.
+ .. method:: locked()
+
+ Return a boolean indicating whether this object is locked right now.
+
+ .. versionadded:: 3.14
+
.. note::
On macOS, this is indistinguishable from :class:`Semaphore` because
``sem_getvalue()`` is not implemented on that platform.
@@ -1521,6 +1527,12 @@ object -- see :ref:`multiprocessing-managers`.
A solitary difference from its close analog exists: its ``acquire`` method's
first argument is named *block*, as is consistent with :meth:`Lock.acquire`.
+ .. method:: locked()
+
+ Return a boolean indicating whether this object is locked right now.
+
+ .. versionadded:: 3.14
+
.. note::
On macOS, ``sem_timedwait`` is unsupported, so calling ``acquire()`` with
diff --git a/Doc/library/netrc.rst b/Doc/library/netrc.rst
index f6260383b2b..74c97e8c9a9 100644
--- a/Doc/library/netrc.rst
+++ b/Doc/library/netrc.rst
@@ -24,12 +24,14 @@ the Unix :program:`ftp` program and other FTP clients.
a :exc:`FileNotFoundError` exception will be raised.
Parse errors will raise :exc:`NetrcParseError` with diagnostic
information including the file name, line number, and terminating token.
+
If no argument is specified on a POSIX system, the presence of passwords in
the :file:`.netrc` file will raise a :exc:`NetrcParseError` if the file
ownership or permissions are insecure (owned by a user other than the user
running the process, or accessible for read or write by any other user).
This implements security behavior equivalent to that of ftp and other
- programs that use :file:`.netrc`.
+ programs that use :file:`.netrc`. Such security checks are not available
+ on platforms that do not support :func:`os.getuid`.
.. versionchanged:: 3.4 Added the POSIX permission check.
diff --git a/Doc/library/os.path.rst b/Doc/library/os.path.rst
index ecbbc1d7605..f72aee19d8f 100644
--- a/Doc/library/os.path.rst
+++ b/Doc/library/os.path.rst
@@ -408,9 +408,26 @@ the :mod:`glob` module.)
system). On Windows, this function will also resolve MS-DOS (also called 8.3)
style names such as ``C:\\PROGRA~1`` to ``C:\\Program Files``.
- If a path doesn't exist or a symlink loop is encountered, and *strict* is
- ``True``, :exc:`OSError` is raised. If *strict* is ``False`` these errors
- are ignored, and so the result might be missing or otherwise inaccessible.
+ By default, the path is evaluated up to the first component that does not
+ exist, is a symlink loop, or whose evaluation raises :exc:`OSError`.
+ All such components are appended unchanged to the existing part of the path.
+
+ Some errors that are handled this way include "access denied", "not a
+ directory", or "bad argument to internal function". Thus, the
+ resulting path may be missing or inaccessible, may still contain
+ links or loops, and may traverse non-directories.
+
+ This behavior can be modified by keyword arguments:
+
+ If *strict* is ``True``, the first error encountered when evaluating the path is
+ re-raised.
+ In particular, :exc:`FileNotFoundError` is raised if *path* does not exist,
+ or another :exc:`OSError` if it is otherwise inaccessible.
+
+ If *strict* is :py:data:`os.path.ALLOW_MISSING`, errors other than
+ :exc:`FileNotFoundError` are re-raised (as with ``strict=True``).
+ Thus, the returned path will not contain any symbolic links, but the named
+ file and some of its parent directories may be missing.
.. note::
This function emulates the operating system's procedure for making a path
@@ -429,6 +446,15 @@ the :mod:`glob` module.)
.. versionchanged:: 3.10
The *strict* parameter was added.
+ .. versionchanged:: next
+ The :py:data:`~os.path.ALLOW_MISSING` value for the *strict* parameter
+ was added.
+
+.. data:: ALLOW_MISSING
+
+ Special value used for the *strict* argument in :func:`realpath`.
+
+ .. versionadded:: next
.. function:: relpath(path, start=os.curdir)
diff --git a/Doc/library/pathlib.rst b/Doc/library/pathlib.rst
index 7d7692dea5c..47986a2d960 100644
--- a/Doc/library/pathlib.rst
+++ b/Doc/library/pathlib.rst
@@ -1781,9 +1781,12 @@ The following wildcards are supported in patterns for
``?``
Matches one non-separator character.
``[seq]``
- Matches one character in *seq*.
+ Matches one character in *seq*, where *seq* is a sequence of characters.
+ Range expressions are supported; for example, ``[a-z]`` matches any lowercase ASCII letter.
+ Multiple ranges can be combined: ``[a-zA-Z0-9_]`` matches any ASCII letter, digit, or underscore.
+
``[!seq]``
- Matches one character not in *seq*.
+ Matches one character not in *seq*, where *seq* follows the same rules as above.
For a literal match, wrap the meta-characters in brackets.
For example, ``"[?]"`` matches the character ``"?"``.
@@ -1982,7 +1985,7 @@ The :mod:`pathlib.types` module provides types for static type checking.
If *follow_symlinks* is ``False``, return ``True`` only if the path
is a file (without following symlinks); return ``False`` if the path
- is a directory or other other non-file, or if it doesn't exist.
+ is a directory or other non-file, or if it doesn't exist.
.. method:: is_symlink()
diff --git a/Doc/library/pdb.rst b/Doc/library/pdb.rst
index a0304edddf6..f4b51664545 100644
--- a/Doc/library/pdb.rst
+++ b/Doc/library/pdb.rst
@@ -80,7 +80,7 @@ The debugger's prompt is ``(Pdb)``, which is the indicator that you are in debug
You can also invoke :mod:`pdb` from the command line to debug other scripts. For
example::
- python -m pdb [-c command] (-m module | pyfile) [args ...]
+ python -m pdb [-c command] (-m module | -p pid | pyfile) [args ...]
When invoked as a module, pdb will automatically enter post-mortem debugging if
the program being debugged exits abnormally. After post-mortem debugging (or
@@ -104,6 +104,24 @@ useful than quitting the debugger upon program's exit.
.. versionchanged:: 3.7
Added the ``-m`` option.
+.. option:: -p, --pid <pid>
+
+ Attach to the process with the specified PID.
+
+ .. versionadded:: 3.14
+
+
+To attach to a running Python process for remote debugging, use the ``-p`` or
+``--pid`` option with the target process's PID::
+
+ python -m pdb -p 1234
+
+.. note::
+
+ Attaching to a process that is blocked in a system call or waiting for I/O
+ will only work once the next bytecode instruction is executed or when the
+ process receives a signal.
+
Typical usage to execute a statement under control of the debugger is::
>>> import pdb
diff --git a/Doc/library/pkgutil.rst b/Doc/library/pkgutil.rst
index 20b8f6bcf19..47d24b6f7d0 100644
--- a/Doc/library/pkgutil.rst
+++ b/Doc/library/pkgutil.rst
@@ -69,8 +69,8 @@ support.
Yield :term:`finder` objects for the given module name.
- If fullname contains a ``'.'``, the finders will be for the package
- containing fullname, otherwise they will be all registered top level
+ If *fullname* contains a ``'.'``, the finders will be for the package
+ containing *fullname*, otherwise they will be all registered top level
finders (i.e. those on both :data:`sys.meta_path` and :data:`sys.path_hooks`).
If the named module is in a package, that package is imported as a side
diff --git a/Doc/library/platform.rst b/Doc/library/platform.rst
index 5c999054323..06de152a742 100644
--- a/Doc/library/platform.rst
+++ b/Doc/library/platform.rst
@@ -188,24 +188,6 @@ Cross platform
:attr:`processor` is resolved late instead of immediately.
-Java platform
--------------
-
-
-.. function:: java_ver(release='', vendor='', vminfo=('','',''), osinfo=('','',''))
-
- Version interface for Jython.
-
- Returns a tuple ``(release, vendor, vminfo, osinfo)`` with *vminfo* being a
- tuple ``(vm_name, vm_release, vm_vendor)`` and *osinfo* being a tuple
- ``(os_name, os_version, os_arch)``. Values which cannot be determined are set to
- the defaults given as parameters (which all default to ``''``).
-
- .. deprecated-removed:: 3.13 3.15
- It was largely untested, had a confusing API,
- and was only useful for Jython support.
-
-
Windows platform
----------------
diff --git a/Doc/library/python.rst b/Doc/library/python.rst
index c2c231af7c3..c5c762e11b9 100644
--- a/Doc/library/python.rst
+++ b/Doc/library/python.rst
@@ -27,3 +27,8 @@ overview:
inspect.rst
annotationlib.rst
site.rst
+
+.. seealso::
+
+ * See the :mod:`concurrent.interpreters` module, which similarly
+ exposes core runtime functionality.
diff --git a/Doc/library/re.rst b/Doc/library/re.rst
index eb3b1e5549c..75ebbf11c8e 100644
--- a/Doc/library/re.rst
+++ b/Doc/library/re.rst
@@ -991,8 +991,8 @@ Functions
That way, separator components are always found at the same relative
indices within the result list.
- Empty matches for the pattern split the string only when not adjacent
- to a previous empty match.
+ Adjacent empty matches are not possible, but an empty match can occur
+ immediately after a non-empty match.
.. code:: pycon
@@ -1095,9 +1095,12 @@ Functions
The optional argument *count* is the maximum number of pattern occurrences to be
replaced; *count* must be a non-negative integer. If omitted or zero, all
- occurrences will be replaced. Empty matches for the pattern are replaced only
- when not adjacent to a previous empty match, so ``sub('x*', '-', 'abxd')`` returns
- ``'-a-b--d-'``.
+ occurrences will be replaced.
+
+ Adjacent empty matches are not possible, but an empty match can occur
+ immediately after a non-empty match.
+ As a result, ``sub('x*', '-', 'abxd')`` returns ``'-a-b--d-'``
+ instead of ``'-a-b-d-'``.
.. index:: single: \g; in regular expressions
@@ -1128,8 +1131,7 @@ Functions
.. versionchanged:: 3.7
Unknown escapes in *repl* consisting of ``'\'`` and an ASCII letter
now are errors.
- Empty matches for the pattern are replaced when adjacent to a previous
- non-empty match.
+ An empty match can occur immediately after a non-empty match.
.. versionchanged:: 3.12
Group *id* can only contain ASCII digits.
diff --git a/Doc/library/shelve.rst b/Doc/library/shelve.rst
index 6e74a59b82b..23a2e0c3d0c 100644
--- a/Doc/library/shelve.rst
+++ b/Doc/library/shelve.rst
@@ -75,8 +75,15 @@ Two additional methods are supported:
Write back all entries in the cache if the shelf was opened with *writeback*
set to :const:`True`. Also empty the cache and synchronize the persistent
- dictionary on disk, if feasible. This is called automatically when the shelf
- is closed with :meth:`close`.
+ dictionary on disk, if feasible. This is called automatically when
+ :meth:`reorganize` is called or the shelf is closed with :meth:`close`.
+
+.. method:: Shelf.reorganize()
+
+ Calls :meth:`sync` and attempts to shrink space used on disk by removing empty
+ space resulting from deletions.
+
+ .. versionadded:: next
.. method:: Shelf.close()
@@ -116,6 +123,11 @@ Restrictions
* 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.
+* :meth:`Shelf.reorganize` may not be available for all database packages and
+ may temporarely increase resource usage (especially disk space) when called.
+ Additionally, it will never run automatically and instead needs to be called
+ explicitly.
+
.. class:: Shelf(dict, protocol=None, writeback=False, keyencoding='utf-8')
diff --git a/Doc/library/shutil.rst b/Doc/library/shutil.rst
index c78dfe1aafa..2dde40c9d92 100644
--- a/Doc/library/shutil.rst
+++ b/Doc/library/shutil.rst
@@ -47,6 +47,13 @@ Directory and files operations
0, only the contents from the current file position to the end of the file will
be copied.
+ :func:`copyfileobj` will *not* guarantee that the destination stream has
+ been flushed on completion of the copy. If you want to read from the
+ destination at the completion of the copy operation (for example, reading
+ the contents of a temporary file that has been copied from a HTTP stream),
+ you must ensure that you have called :func:`~io.IOBase.flush` or
+ :func:`~io.IOBase.close` on the file-like object before attempting to read
+ the destination file.
.. function:: copyfile(src, dst, *, follow_symlinks=True)
@@ -327,6 +334,10 @@ Directory and files operations
The deprecated *onerror* is similar to *onexc*, except that the third
parameter it receives is the tuple returned from :func:`sys.exc_info`.
+ .. seealso::
+ :ref:`shutil-rmtree-example` for an example of handling the removal
+ of a directory tree that contains read-only files.
+
.. audit-event:: shutil.rmtree path,dir_fd shutil.rmtree
.. versionchanged:: 3.3
diff --git a/Doc/library/signal.rst b/Doc/library/signal.rst
index c28841dbb8c..b0307d3dea1 100644
--- a/Doc/library/signal.rst
+++ b/Doc/library/signal.rst
@@ -211,8 +211,8 @@ The variables defined in the :mod:`signal` module are:
.. data:: SIGSTKFLT
- Stack fault on coprocessor. The Linux kernel does not raise this signal: it
- can only be raised in user space.
+ Stack fault on coprocessor. The Linux kernel does not raise this signal: it
+ can only be raised in user space.
.. availability:: Linux.
diff --git a/Doc/library/socket.rst b/Doc/library/socket.rst
index 8fd5187e3a4..bc89a3228f0 100644
--- a/Doc/library/socket.rst
+++ b/Doc/library/socket.rst
@@ -362,10 +362,10 @@ Exceptions
Constants
^^^^^^^^^
- The AF_* and SOCK_* constants are now :class:`AddressFamily` and
- :class:`SocketKind` :class:`.IntEnum` collections.
+The AF_* and SOCK_* constants are now :class:`AddressFamily` and
+:class:`SocketKind` :class:`.IntEnum` collections.
- .. versionadded:: 3.4
+.. versionadded:: 3.4
.. data:: AF_UNIX
AF_INET
@@ -773,9 +773,9 @@ Constants
Constant to optimize CPU locality, to be used in conjunction with
:data:`SO_REUSEPORT`.
- .. versionadded:: 3.11
+ .. versionadded:: 3.11
- .. availability:: Linux >= 3.9
+ .. availability:: Linux >= 3.9
.. data:: SO_REUSEPORT_LB
@@ -1492,7 +1492,7 @@ The :mod:`socket` module also offers various network-related services:
The *fds* parameter is a sequence of file descriptors.
Consult :meth:`~socket.sendmsg` for the documentation of these parameters.
- .. availability:: Unix, Windows, not WASI.
+ .. availability:: Unix, not WASI.
Unix platforms supporting :meth:`~socket.sendmsg`
and :const:`SCM_RIGHTS` mechanism.
@@ -1506,9 +1506,9 @@ The :mod:`socket` module also offers various network-related services:
Return ``(msg, list(fds), flags, addr)``.
Consult :meth:`~socket.recvmsg` for the documentation of these parameters.
- .. availability:: Unix, Windows, not WASI.
+ .. availability:: Unix, not WASI.
- Unix platforms supporting :meth:`~socket.sendmsg`
+ Unix platforms supporting :meth:`~socket.recvmsg`
and :const:`SCM_RIGHTS` mechanism.
.. versionadded:: 3.9
diff --git a/Doc/library/socketserver.rst b/Doc/library/socketserver.rst
index 59cfa136a3b..7fb629f7d2f 100644
--- a/Doc/library/socketserver.rst
+++ b/Doc/library/socketserver.rst
@@ -24,6 +24,8 @@ There are four basic concrete server classes:
:meth:`~BaseServer.server_activate`. The other parameters are passed to
the :class:`BaseServer` base class.
+ .. versionchanged:: next
+ The default queue size is now ``socket.SOMAXCONN`` for :class:`socketserver.TCPServer`.
.. class:: UDPServer(server_address, RequestHandlerClass, bind_and_activate=True)
@@ -541,7 +543,7 @@ objects that simplify communication by providing the standard file interface)::
The difference is that the ``readline()`` call in the second handler will call
``recv()`` multiple times until it encounters a newline character, while the
-the first handler had to use a ``recv()`` loop to accumulate data until a
+first handler had to use a ``recv()`` loop to accumulate data until a
newline itself. If it had just used a single ``recv()`` without the loop it
would just have returned what has been received so far from the client.
TCP is stream based: data arrives in the order it was sent, but there no
diff --git a/Doc/library/sqlite3.rst b/Doc/library/sqlite3.rst
index 2d0f9a740c6..641e1f1de03 100644
--- a/Doc/library/sqlite3.rst
+++ b/Doc/library/sqlite3.rst
@@ -507,6 +507,15 @@ Module constants
Version number of the runtime SQLite library as a :class:`tuple` of
:class:`integers <int>`.
+.. data:: SQLITE_KEYWORDS
+
+ A :class:`tuple` containing all sqlite3 keywords.
+
+ This constant is only available if Python was compiled with SQLite
+ 3.24.0 or greater.
+
+ .. versionadded:: next
+
.. data:: threadsafety
Integer constant required by the DB-API 2.0, stating the level of thread
@@ -1482,7 +1491,9 @@ Cursor objects
:type parameters: :class:`dict` | :term:`sequence`
:raises ProgrammingError:
- If *sql* contains more than one SQL statement.
+ When *sql* contains more than one SQL statement.
+ When :ref:`named placeholders <sqlite3-placeholders>` are used
+ and *parameters* is a sequence instead of a :class:`dict`.
If :attr:`~Connection.autocommit` is
:data:`LEGACY_TRANSACTION_CONTROL`,
@@ -1491,13 +1502,11 @@ Cursor objects
and there is no open transaction,
a transaction is implicitly opened before executing *sql*.
- .. deprecated-removed:: 3.12 3.14
+ .. versionchanged:: 3.14
- :exc:`DeprecationWarning` is emitted if
+ :exc:`ProgrammingError` is emitted if
:ref:`named placeholders <sqlite3-placeholders>` are used
and *parameters* is a sequence instead of a :class:`dict`.
- Starting with Python 3.14, :exc:`ProgrammingError` will
- be raised instead.
Use :meth:`executescript` to execute multiple SQL statements.
@@ -1519,8 +1528,10 @@ Cursor objects
:type parameters: :term:`iterable`
:raises ProgrammingError:
- If *sql* contains more than one SQL statement,
- or is not a DML statement.
+ When *sql* contains more than one SQL statement
+ or is not a DML statement,
+ When :ref:`named placeholders <sqlite3-placeholders>` are used
+ and the items in *parameters* are sequences instead of :class:`dict`\s.
Example:
@@ -1544,14 +1555,12 @@ Cursor objects
.. _RETURNING clauses: https://www.sqlite.org/lang_returning.html
- .. deprecated-removed:: 3.12 3.14
+ .. versionchanged:: 3.14
- :exc:`DeprecationWarning` is emitted if
+ :exc:`ProgrammingError` is emitted if
:ref:`named placeholders <sqlite3-placeholders>` are used
and the items in *parameters* are sequences
instead of :class:`dict`\s.
- Starting with Python 3.14, :exc:`ProgrammingError` will
- be raised instead.
.. method:: executescript(sql_script, /)
diff --git a/Doc/library/stdtypes.rst b/Doc/library/stdtypes.rst
index 1d9a655c766..394c302fd35 100644
--- a/Doc/library/stdtypes.rst
+++ b/Doc/library/stdtypes.rst
@@ -1018,7 +1018,7 @@ operations have the same priority as the corresponding numeric operations. [3]_
| ``s * n`` or | equivalent to adding *s* to | (2)(7) |
| ``n * s`` | itself *n* times | |
+--------------------------+--------------------------------+----------+
-| ``s[i]`` | *i*\ th item of *s*, origin 0 | \(3) |
+| ``s[i]`` | *i*\ th item of *s*, origin 0 | (3)(9) |
+--------------------------+--------------------------------+----------+
| ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) |
+--------------------------+--------------------------------+----------+
@@ -1150,6 +1150,9 @@ Notes:
without copying any data and with the returned index being relative to
the start of the sequence rather than the start of the slice.
+(9)
+ An :exc:`IndexError` is raised if *i* is outside the sequence range.
+
.. _typesseq-immutable:
@@ -1214,6 +1217,8 @@ accepts integers that meet the value restriction ``0 <= x <= 255``).
| ``s[i] = x`` | item *i* of *s* is replaced by | |
| | *x* | |
+------------------------------+--------------------------------+---------------------+
+| ``del s[i]`` | removes item *i* of *s* | |
++------------------------------+--------------------------------+---------------------+
| ``s[i:j] = t`` | slice of *s* from *i* to *j* | |
| | is replaced by the contents of | |
| | the iterable *t* | |
@@ -1788,8 +1793,14 @@ expression support in the :mod:`re` module).
Return centered in a string of length *width*. Padding is done using the
specified *fillchar* (default is an ASCII space). The original string is
- returned if *width* is less than or equal to ``len(s)``.
+ returned if *width* is less than or equal to ``len(s)``. For example::
+ >>> 'Python'.center(10)
+ ' Python '
+ >>> 'Python'.center(10, '-')
+ '--Python--'
+ >>> 'Python'.center(4)
+ 'Python'
.. method:: str.count(sub[, start[, end]])
@@ -1799,8 +1810,18 @@ expression support in the :mod:`re` module).
interpreted as in slice notation.
If *sub* is empty, returns the number of empty strings between characters
- which is the length of the string plus one.
-
+ which is the length of the string plus one. For example::
+
+ >>> 'spam, spam, spam'.count('spam')
+ 3
+ >>> 'spam, spam, spam'.count('spam', 5)
+ 2
+ >>> 'spam, spam, spam'.count('spam', 5, 10)
+ 1
+ >>> 'spam, spam, spam'.count('eggs')
+ 0
+ >>> 'spam, spam, spam'.count('')
+ 17
.. method:: str.encode(encoding="utf-8", errors="strict")
@@ -1820,6 +1841,14 @@ expression support in the :mod:`re` module).
unless an encoding error actually occurs,
:ref:`devmode` is enabled
or a :ref:`debug build <debug-build>` is used.
+ For example::
+
+ >>> encoded_str_to_bytes = 'Python'.encode()
+ >>> type(encoded_str_to_bytes)
+ <class 'bytes'>
+ >>> encoded_str_to_bytes
+ b'Python'
+
.. versionchanged:: 3.1
Added support for keyword arguments.
@@ -1834,7 +1863,19 @@ expression support in the :mod:`re` module).
Return ``True`` if the string ends with the specified *suffix*, otherwise return
``False``. *suffix* can also be a tuple of suffixes to look for. With optional
*start*, test beginning at that position. With optional *end*, stop comparing
- at that position.
+ at that position. Using *start* and *end* is equivalent to
+ ``str[start:end].endswith(suffix)``. For example::
+
+ >>> 'Python'.endswith('on')
+ True
+ >>> 'a tuple of suffixes'.endswith(('at', 'in'))
+ False
+ >>> 'a tuple of suffixes'.endswith(('at', 'es'))
+ True
+ >>> 'Python is amazing'.endswith('is', 0, 9)
+ True
+
+ See also :meth:`startswith` and :meth:`removesuffix`.
.. method:: str.expandtabs(tabsize=8)
@@ -1850,12 +1891,15 @@ expression support in the :mod:`re` module).
(``\n``) or return (``\r``), it is copied and the current column is reset to
zero. Any other character is copied unchanged and the current column is
incremented by one regardless of how the character is represented when
- printed.
+ printed. For example::
>>> '01\t012\t0123\t01234'.expandtabs()
'01 012 0123 01234'
>>> '01\t012\t0123\t01234'.expandtabs(4)
'01 012 0123 01234'
+ >>> print('01\t012\n0123\t01234'.expandtabs(4))
+ 01 012
+ 0123 01234
.. method:: str.find(sub[, start[, end]])
@@ -2269,6 +2313,18 @@ expression support in the :mod:`re` module).
>>> ' 1 2 3 '.split()
['1', '2', '3']
+ If *sep* is not specified or is ``None`` and *maxsplit* is ``0``, only
+ leading runs of consecutive whitespace are considered.
+
+ For example::
+
+ >>> "".split(None, 0)
+ []
+ >>> " ".split(None, 0)
+ []
+ >>> " foo ".split(maxsplit=0)
+ ['foo ']
+
.. index::
single: universal newlines; str.splitlines method
diff --git a/Doc/library/string.rst b/Doc/library/string.rst
index c4012483a52..23e15780075 100644
--- a/Doc/library/string.rst
+++ b/Doc/library/string.rst
@@ -328,7 +328,7 @@ The general form of a *standard format specifier* is:
sign: "+" | "-" | " "
width_and_precision: [`width_with_grouping`][`precision_with_grouping`]
width_with_grouping: [`width`][`grouping`]
- precision_with_grouping: "." [`precision`][`grouping`]
+ precision_with_grouping: "." [`precision`][`grouping`] | "." `grouping`
width: `~python-grammar:digit`+
precision: `~python-grammar:digit`+
grouping: "," | "_"
diff --git a/Doc/library/sys.rst b/Doc/library/sys.rst
index 55e442b20ff..1626a89a073 100644
--- a/Doc/library/sys.rst
+++ b/Doc/library/sys.rst
@@ -1185,6 +1185,15 @@ always available. Unless explicitly noted otherwise, all variables are read-only
``cache_tag`` is set to ``None``, it indicates that module caching should
be disabled.
+ *supports_isolated_interpreters* is a boolean value, whether
+ this implementation supports multiple isolated interpreters.
+ It is ``True`` for CPython on most platforms. Platforms with
+ this support implement the low-level :mod:`!_interpreters` module.
+
+ .. seealso::
+
+ :pep:`684`, :pep:`734`, and :mod:`concurrent.interpreters`.
+
:data:`sys.implementation` may contain additional attributes specific to
the Python implementation. These non-standard attributes must start with
an underscore, and are not described here. Regardless of its contents,
@@ -1194,6 +1203,9 @@ always available. Unless explicitly noted otherwise, all variables are read-only
.. versionadded:: 3.3
+ .. versionchanged:: 3.14
+ Added ``supports_isolated_interpreters`` field.
+
.. note::
The addition of new required attributes must go through the normal PEP
@@ -1933,6 +1945,22 @@ always available. Unless explicitly noted otherwise, all variables are read-only
interpreter is pre-release (alpha, beta, or release candidate) then the
local and remote interpreters must be the same exact version.
+ .. audit-event:: sys.remote_exec pid script_path
+
+ When the code is executed in the remote process, an
+ :ref:`auditing event <auditing>` ``sys.remote_exec`` is raised with
+ the *pid* and the path to the script file.
+ This event is raised in the process that called :func:`sys.remote_exec`.
+
+ .. audit-event:: cpython.remote_debugger_script script_path
+
+ When the script is executed in the remote process, an
+ :ref:`auditing event <auditing>`
+ ``cpython.remote_debugger_script`` is raised
+ with the path in the remote process.
+ This event is raised in the remote process, not the one
+ that called :func:`sys.remote_exec`.
+
.. availability:: Unix, Windows.
.. versionadded:: 3.14
diff --git a/Doc/library/tarfile.rst b/Doc/library/tarfile.rst
index f9cb5495e60..7cec108a5bd 100644
--- a/Doc/library/tarfile.rst
+++ b/Doc/library/tarfile.rst
@@ -255,6 +255,15 @@ The :mod:`tarfile` module defines the following exceptions:
Raised to refuse extracting a symbolic link pointing outside the destination
directory.
+.. exception:: LinkFallbackError
+
+ Raised to refuse emulating a link (hard or symbolic) by extracting another
+ archive member, when that member would be rejected by the filter location.
+ The exception that was raised to reject the replacement member is available
+ as :attr:`!BaseException.__context__`.
+
+ .. versionadded:: next
+
The following constants are available at the module level:
@@ -1068,6 +1077,12 @@ reused in custom filters:
Implements the ``'data'`` filter.
In addition to what ``tar_filter`` does:
+ - Normalize link targets (:attr:`TarInfo.linkname`) using
+ :func:`os.path.normpath`.
+ Note that this removes internal ``..`` components, which may change the
+ meaning of the link if the path in :attr:`!TarInfo.linkname` traverses
+ symbolic links.
+
- :ref:`Refuse <tarfile-extraction-refuse>` to extract links (hard or soft)
that link to absolute paths, or ones that link outside the destination.
@@ -1099,6 +1114,10 @@ reused in custom filters:
Note that this filter does not block *all* dangerous archive features.
See :ref:`tarfile-further-verification` for details.
+ .. versionchanged:: next
+
+ Link targets are now normalized.
+
.. _tarfile-extraction-refuse:
@@ -1127,6 +1146,7 @@ Here is an incomplete list of things to consider:
* Extract to a :func:`new temporary directory <tempfile.mkdtemp>`
to prevent e.g. exploiting pre-existing links, and to make it easier to
clean up after a failed extraction.
+* Disallow symbolic links if you do not need the functionality.
* When working with untrusted data, use external (e.g. OS-level) limits on
disk, memory and CPU usage.
* Check filenames against an allow-list of characters
diff --git a/Doc/library/threading.rst b/Doc/library/threading.rst
index 249c0a5cb03..cabb41442f8 100644
--- a/Doc/library/threading.rst
+++ b/Doc/library/threading.rst
@@ -11,6 +11,52 @@
This module constructs higher-level threading interfaces on top of the lower
level :mod:`_thread` module.
+.. include:: ../includes/wasm-notavail.rst
+
+Introduction
+------------
+
+The :mod:`!threading` module provides a way to run multiple `threads
+<https://en.wikipedia.org/wiki/Thread_(computing)>`_ (smaller
+units of a process) concurrently within a single process. It allows for the
+creation and management of threads, making it possible to execute tasks in
+parallel, sharing memory space. Threads are particularly useful when tasks are
+I/O bound, such as file operations or making network requests,
+where much of the time is spent waiting for external resources.
+
+A typical use case for :mod:`!threading` includes managing a pool of worker
+threads that can process multiple tasks concurrently. Here's a basic example of
+creating and starting threads using :class:`~threading.Thread`::
+
+ import threading
+ import time
+
+ def crawl(link, delay=3):
+ print(f"crawl started for {link}")
+ time.sleep(delay) # Blocking I/O (simulating a network request)
+ print(f"crawl ended for {link}")
+
+ links = [
+ "https://python.org",
+ "https://docs.python.org",
+ "https://peps.python.org",
+ ]
+
+ # Start threads for each link
+ threads = []
+ for link in links:
+ # Using `args` to pass positional arguments and `kwargs` for keyword arguments
+ t = threading.Thread(target=crawl, args=(link,), kwargs={"delay": 2})
+ threads.append(t)
+
+ # Start each thread
+ for t in threads:
+ t.start()
+
+ # Wait for all threads to finish
+ for t in threads:
+ t.join()
+
.. versionchanged:: 3.7
This module used to be optional, it is now always available.
@@ -45,7 +91,25 @@ level :mod:`_thread` module.
However, threading is still an appropriate model if you want to run
multiple I/O-bound tasks simultaneously.
-.. include:: ../includes/wasm-notavail.rst
+GIL and performance considerations
+----------------------------------
+
+Unlike the :mod:`multiprocessing` module, which uses separate processes to
+bypass the :term:`global interpreter lock` (GIL), the threading module operates
+within a single process, meaning that all threads share the same memory space.
+However, the GIL limits the performance gains of threading when it comes to
+CPU-bound tasks, as only one thread can execute Python bytecode at a time.
+Despite this, threads remain a useful tool for achieving concurrency in many
+scenarios.
+
+As of Python 3.13, :term:`free-threaded <free threading>` builds
+can disable the GIL, enabling true parallel execution of threads, but this
+feature is not available by default (see :pep:`703`).
+
+.. TODO: At some point this feature will become available by default.
+
+Reference
+---------
This module defines the following functions:
@@ -62,7 +126,7 @@ This module defines the following functions:
Return the current :class:`Thread` object, corresponding to the caller's thread
of control. If the caller's thread of control was not created through the
- :mod:`threading` module, a dummy thread object with limited functionality is
+ :mod:`!threading` module, a dummy thread object with limited functionality is
returned.
The function ``currentThread`` is a deprecated alias for this function.
@@ -157,13 +221,13 @@ This module defines the following functions:
.. index:: single: trace function
- Set a trace function for all threads started from the :mod:`threading` module.
+ Set a trace function for all threads started from the :mod:`!threading` module.
The *func* will be passed to :func:`sys.settrace` for each thread, before its
:meth:`~Thread.run` method is called.
.. function:: settrace_all_threads(func)
- Set a trace function for all threads started from the :mod:`threading` module
+ Set a trace function for all threads started from the :mod:`!threading` module
and all Python threads that are currently executing.
The *func* will be passed to :func:`sys.settrace` for each thread, before its
@@ -186,13 +250,13 @@ This module defines the following functions:
.. index:: single: profile function
- Set a profile function for all threads started from the :mod:`threading` module.
+ Set a profile function for all threads started from the :mod:`!threading` module.
The *func* will be passed to :func:`sys.setprofile` for each thread, before its
:meth:`~Thread.run` method is called.
.. function:: setprofile_all_threads(func)
- Set a profile function for all threads started from the :mod:`threading` module
+ Set a profile function for all threads started from the :mod:`!threading` module
and all Python threads that are currently executing.
The *func* will be passed to :func:`sys.setprofile` for each thread, before its
@@ -257,8 +321,8 @@ when implemented, are mapped to module-level functions.
All of the methods described below are executed atomically.
-Thread-Local Data
------------------
+Thread-local data
+^^^^^^^^^^^^^^^^^
Thread-local data is data whose values are thread specific. If you
have data that you want to be local to a thread, create a
@@ -389,8 +453,8 @@ affects what we see::
.. _thread-objects:
-Thread Objects
---------------
+Thread objects
+^^^^^^^^^^^^^^
The :class:`Thread` class represents an activity that is run in a separate
thread of control. There are two ways to specify the activity: by passing a
@@ -557,7 +621,7 @@ since it is impossible to detect the termination of alien threads.
an error to :meth:`~Thread.join` a thread before it has been started
and attempts to do so raise the same exception.
- If an attempt is made to join a running daemonic thread in in late stages
+ If an attempt is made to join a running daemonic thread in late stages
of :term:`Python finalization <interpreter shutdown>` :meth:`!join`
raises a :exc:`PythonFinalizationError`.
@@ -645,8 +709,8 @@ since it is impossible to detect the termination of alien threads.
.. _lock-objects:
-Lock Objects
-------------
+Lock objects
+^^^^^^^^^^^^
A primitive lock is a synchronization primitive that is not owned by a
particular thread when locked. In Python, it is currently the lowest level
@@ -738,8 +802,8 @@ All methods are executed atomically.
.. _rlock-objects:
-RLock Objects
--------------
+RLock objects
+^^^^^^^^^^^^^
A reentrant lock is a synchronization primitive that may be acquired multiple
times by the same thread. Internally, it uses the concepts of "owning thread"
@@ -848,8 +912,8 @@ call release as many times the lock has been acquired can lead to deadlock.
.. _condition-objects:
-Condition Objects
------------------
+Condition objects
+^^^^^^^^^^^^^^^^^
A condition variable is always associated with some kind of lock; this can be
passed in or one will be created by default. Passing one in is useful when
@@ -1026,8 +1090,8 @@ item to the buffer only needs to wake up one consumer thread.
.. _semaphore-objects:
-Semaphore Objects
------------------
+Semaphore objects
+^^^^^^^^^^^^^^^^^
This is one of the oldest synchronization primitives in the history of computer
science, invented by the early Dutch computer scientist Edsger W. Dijkstra (he
@@ -1107,7 +1171,7 @@ Semaphores also support the :ref:`context management protocol <with-locks>`.
.. _semaphore-examples:
-:class:`Semaphore` Example
+:class:`Semaphore` example
^^^^^^^^^^^^^^^^^^^^^^^^^^
Semaphores are often used to guard resources with limited capacity, for example,
@@ -1135,8 +1199,8 @@ causes the semaphore to be released more than it's acquired will go undetected.
.. _event-objects:
-Event Objects
--------------
+Event objects
+^^^^^^^^^^^^^
This is one of the simplest mechanisms for communication between threads: one
thread signals an event and other threads wait for it.
@@ -1192,8 +1256,8 @@ method. The :meth:`~Event.wait` method blocks until the flag is true.
.. _timer-objects:
-Timer Objects
--------------
+Timer objects
+^^^^^^^^^^^^^
This class represents an action that should be run only after a certain amount
of time has passed --- a timer. :class:`Timer` is a subclass of :class:`Thread`
@@ -1230,8 +1294,8 @@ For example::
only work if the timer is still in its waiting stage.
-Barrier Objects
----------------
+Barrier objects
+^^^^^^^^^^^^^^^
.. versionadded:: 3.2
diff --git a/Doc/library/time.rst b/Doc/library/time.rst
index 542493a82af..29b695a9b19 100644
--- a/Doc/library/time.rst
+++ b/Doc/library/time.rst
@@ -712,13 +712,18 @@ Functions
Clock:
- * On Windows, call ``GetSystemTimeAsFileTime()``.
+ * On Windows, call ``GetSystemTimePreciseAsFileTime()``.
* Call ``clock_gettime(CLOCK_REALTIME)`` if available.
* Otherwise, call ``gettimeofday()``.
Use :func:`time_ns` to avoid the precision loss caused by the :class:`float`
type.
+.. versionchanged:: 3.13
+
+ On Windows, calls ``GetSystemTimePreciseAsFileTime()`` instead of
+ ``GetSystemTimeAsFileTime()``.
+
.. function:: time_ns() -> int
diff --git a/Doc/library/token.rst b/Doc/library/token.rst
index 1f92b5df430..c228006d4c1 100644
--- a/Doc/library/token.rst
+++ b/Doc/library/token.rst
@@ -51,7 +51,7 @@ The token constants are:
.. data:: NAME
Token value that indicates an :ref:`identifier <identifiers>`.
- Note that keywords are also initially tokenized an ``NAME`` tokens.
+ Note that keywords are also initially tokenized as ``NAME`` tokens.
.. data:: NUMBER
diff --git a/Doc/library/typing.rst b/Doc/library/typing.rst
index 54cc3ea3311..69df09c7795 100644
--- a/Doc/library/typing.rst
+++ b/Doc/library/typing.rst
@@ -3500,20 +3500,11 @@ Introspection helpers
Evaluate an :class:`annotationlib.ForwardRef` as a :term:`type hint`.
This is similar to calling :meth:`annotationlib.ForwardRef.evaluate`,
- but unlike that method, :func:`!evaluate_forward_ref` also:
-
- * Recursively evaluates forward references nested within the type hint.
- * Raises :exc:`TypeError` when it encounters certain objects that are
- not valid type hints.
- * Replaces type hints that evaluate to :const:`!None` with
- :class:`types.NoneType`.
- * Supports the :attr:`~annotationlib.Format.FORWARDREF` and
- :attr:`~annotationlib.Format.STRING` formats.
+ but unlike that method, :func:`!evaluate_forward_ref` also
+ recursively evaluates forward references nested within the type hint.
See the documentation for :meth:`annotationlib.ForwardRef.evaluate` for
- the meaning of the *owner*, *globals*, *locals*, and *type_params* parameters.
- *format* specifies the format of the annotation and is a member of
- the :class:`annotationlib.Format` enum.
+ the meaning of the *owner*, *globals*, *locals*, *type_params*, and *format* parameters.
.. versionadded:: 3.14
@@ -3539,28 +3530,32 @@ Constant
.. data:: TYPE_CHECKING
A special constant that is assumed to be ``True`` by 3rd party static
- type checkers. It is ``False`` at runtime.
+ type checkers. It's ``False`` at runtime.
+
+ A module which is expensive to import, and which only contain types
+ used for typing annotations, can be safely imported inside an
+ ``if TYPE_CHECKING:`` block. This prevents the module from actually
+ being imported at runtime; annotations aren't eagerly evaluated
+ (see :pep:`649`) so using undefined symbols in annotations is
+ harmless--as long as you don't later examine them.
+ Your static type analysis tool will set ``TYPE_CHECKING`` to
+ ``True`` during static type analysis, which means the module will
+ be imported and the types will be checked properly during such analysis.
Usage::
if TYPE_CHECKING:
import expensive_mod
- def fun(arg: 'expensive_mod.SomeType') -> None:
+ def fun(arg: expensive_mod.SomeType) -> None:
local_var: expensive_mod.AnotherType = other_fun()
- The first type annotation must be enclosed in quotes, making it a
- "forward reference", to hide the ``expensive_mod`` reference from the
- interpreter runtime. Type annotations for local variables are not
- evaluated, so the second annotation does not need to be enclosed in quotes.
-
- .. note::
-
- If ``from __future__ import annotations`` is used,
- annotations are not evaluated at function definition time.
- Instead, they are stored as strings in ``__annotations__``.
- This makes it unnecessary to use quotes around the annotation
- (see :pep:`563`).
+ If you occasionally need to examine type annotations at runtime
+ which may contain undefined symbols, use
+ :meth:`annotationlib.get_annotations` with a ``format`` parameter
+ of :attr:`annotationlib.Format.STRING` or
+ :attr:`annotationlib.Format.FORWARDREF` to safely retrieve the
+ annotations without raising :exc:`NameError`.
.. versionadded:: 3.5.2
diff --git a/Doc/library/unittest.rst b/Doc/library/unittest.rst
index 61022fe052c..dcdda1719bf 100644
--- a/Doc/library/unittest.rst
+++ b/Doc/library/unittest.rst
@@ -109,7 +109,7 @@ Here is a short script to test three string methods::
unittest.main()
-A testcase is created by subclassing :class:`unittest.TestCase`. The three
+A test case is created by subclassing :class:`unittest.TestCase`. The three
individual tests are defined with methods whose names start with the letters
``test``. This naming convention informs the test runner about which methods
represent tests.
diff --git a/Doc/library/uuid.rst b/Doc/library/uuid.rst
index 8cce6b98cbc..6698e6d3f43 100644
--- a/Doc/library/uuid.rst
+++ b/Doc/library/uuid.rst
@@ -193,43 +193,52 @@ The :mod:`uuid` module defines the following functions:
.. function:: uuid1(node=None, clock_seq=None)
- Generate a UUID from a host ID, sequence number, and the current time. If *node*
- is not given, :func:`getnode` is used to obtain the hardware address. If
- *clock_seq* is given, it is used as the sequence number; otherwise a random
- 14-bit sequence number is chosen.
+ Generate a UUID from a host ID, sequence number, and the current time
+ according to :rfc:`RFC 9562, §5.1 <9562#section-5.1>`.
+
+ When *node* is not specified, :func:`getnode` is used to obtain the hardware
+ address as a 48-bit positive integer. When a sequence number *clock_seq* is
+ not specified, a pseudo-random 14-bit positive integer is generated.
+
+ If *node* or *clock_seq* exceed their expected bit count,
+ only their least significant bits are kept.
.. function:: uuid3(namespace, name)
Generate a UUID based on the MD5 hash of a namespace identifier (which is a
UUID) and a name (which is a :class:`bytes` object or a string
- that will be encoded using UTF-8).
+ that will be encoded using UTF-8)
+ according to :rfc:`RFC 9562, §5.3 <9562#section-5.3>`.
.. function:: uuid4()
- Generate a random UUID.
+ Generate a random UUID in a cryptographically-secure method
+ according to :rfc:`RFC 9562, §5.4 <9562#section-5.4>`.
.. function:: uuid5(namespace, name)
Generate a UUID based on the SHA-1 hash of a namespace identifier (which is a
UUID) and a name (which is a :class:`bytes` object or a string
- that will be encoded using UTF-8).
+ that will be encoded using UTF-8)
+ according to :rfc:`RFC 9562, §5.5 <9562#section-5.5>`.
.. function:: uuid6(node=None, clock_seq=None)
Generate a UUID from a sequence number and the current time according to
- :rfc:`9562`.
+ :rfc:`RFC 9562, §5.6 <9562#section-5.6>`.
+
This is an alternative to :func:`uuid1` to improve database locality.
When *node* is not specified, :func:`getnode` is used to obtain the hardware
address as a 48-bit positive integer. When a sequence number *clock_seq* is
not specified, a pseudo-random 14-bit positive integer is generated.
- If *node* or *clock_seq* exceed their expected bit count, only their least
- significant bits are kept.
+ If *node* or *clock_seq* exceed their expected bit count,
+ only their least significant bits are kept.
.. versionadded:: 3.14
@@ -257,6 +266,10 @@ The :mod:`uuid` module defines the following functions:
non-specified arguments are substituted for a pseudo-random integer of
appropriate size.
+ By default, *a*, *b* and *c* are not generated by a cryptographically
+ secure pseudo-random number generator (CSPRNG). Use :func:`uuid4` when
+ a UUID needs to be used in a security-sensitive context.
+
.. versionadded:: 3.14
diff --git a/Doc/library/venv.rst b/Doc/library/venv.rst
index bed799aedfd..f16e24eac08 100644
--- a/Doc/library/venv.rst
+++ b/Doc/library/venv.rst
@@ -105,36 +105,52 @@ The command, if run with ``-h``, will show the available options::
Creates virtual Python environments in one or more target directories.
- positional arguments:
- ENV_DIR A directory to create the environment in.
-
- options:
- -h, --help show this help message and exit
- --system-site-packages
- Give the virtual environment access to the system
- site-packages dir.
- --symlinks Try to use symlinks rather than copies, when
- symlinks are not the default for the platform.
- --copies Try to use copies rather than symlinks, even when
- symlinks are the default for the platform.
- --clear Delete the contents of the environment directory
- if it already exists, before environment creation.
- --upgrade Upgrade the environment directory to use this
- version of Python, assuming Python has been
- upgraded in-place.
- --without-pip Skips installing or upgrading pip in the virtual
- environment (pip is bootstrapped by default)
- --prompt PROMPT Provides an alternative prompt prefix for this
- environment.
- --upgrade-deps Upgrade core dependencies (pip) to the latest
- version in PyPI
- --without-scm-ignore-files
- Skips adding SCM ignore files to the environment
- directory (Git is supported by default).
-
Once an environment has been created, you may wish to activate it, e.g. by
sourcing an activate script in its bin directory.
+.. _venv-cli:
+.. program:: venv
+
+.. option:: ENV_DIR
+
+ A required argument specifying the directory to create the environment in.
+
+.. option:: --system-site-packages
+
+ Give the virtual environment access to the system site-packages directory.
+
+.. option:: --symlinks
+
+ Try to use symlinks rather than copies, when symlinks are not the default for the platform.
+
+.. option:: --copies
+
+ Try to use copies rather than symlinks, even when symlinks are the default for the platform.
+
+.. option:: --clear
+
+ Delete the contents of the environment directory if it already exists, before environment creation.
+
+.. option:: --upgrade
+
+ Upgrade the environment directory to use this version of Python, assuming Python has been upgraded in-place.
+
+.. option:: --without-pip
+
+ Skips installing or upgrading pip in the virtual environment (pip is bootstrapped by default).
+
+.. option:: --prompt <PROMPT>
+
+ Provides an alternative prompt prefix for this environment.
+
+.. option:: --upgrade-deps
+
+ Upgrade core dependencies (pip) to the latest version in PyPI.
+
+.. option:: --without-scm-ignore-files
+
+ Skips adding SCM ignore files to the environment directory (Git is supported by default).
+
.. versionchanged:: 3.4
Installs pip by default, added the ``--without-pip`` and ``--copies``
diff --git a/Doc/library/wave.rst b/Doc/library/wave.rst
index 36c2bde87fb..a3f5bfd5e2f 100644
--- a/Doc/library/wave.rst
+++ b/Doc/library/wave.rst
@@ -123,26 +123,6 @@ Wave_read Objects
Rewind the file pointer to the beginning of the audio stream.
- The following two methods are defined for compatibility with the old :mod:`!aifc`
- module, and don't do anything interesting.
-
-
- .. method:: getmarkers()
-
- Returns ``None``.
-
- .. deprecated-removed:: 3.13 3.15
- The method only existed for compatibility with the :mod:`!aifc` module
- which has been removed in Python 3.13.
-
-
- .. method:: getmark(id)
-
- Raise an error.
-
- .. deprecated-removed:: 3.13 3.15
- The method only existed for compatibility with the :mod:`!aifc` module
- which has been removed in Python 3.13.
The following two methods define a term "position" which is compatible between
them, and is otherwise implementation dependent.
diff --git a/Doc/library/zlib.rst b/Doc/library/zlib.rst
index 75ead3c4cb1..7c5e9b086e1 100644
--- a/Doc/library/zlib.rst
+++ b/Doc/library/zlib.rst
@@ -44,6 +44,20 @@ The available exception and functions in this module are:
.. versionchanged:: 3.0
The result is always unsigned.
+.. function:: adler32_combine(adler1, adler2, len2, /)
+
+ Combine two Adler-32 checksums into one.
+
+ Given the Adler-32 checksum *adler1* of a sequence ``A`` and the
+ Adler-32 checksum *adler2* of a sequence ``B`` of length *len2*,
+ return the Adler-32 checksum of ``A`` and ``B`` concatenated.
+
+ This function is typically useful to combine Adler-32 checksums
+ that were concurrently computed. To compute checksums sequentially, use
+ :func:`adler32` with the running checksum as the ``value`` argument.
+
+ .. versionadded:: next
+
.. function:: compress(data, /, level=-1, wbits=MAX_WBITS)
Compresses the bytes in *data*, returning a bytes object containing compressed data.
@@ -136,6 +150,20 @@ The available exception and functions in this module are:
.. versionchanged:: 3.0
The result is always unsigned.
+.. function:: crc32_combine(crc1, crc2, len2, /)
+
+ Combine two CRC-32 checksums into one.
+
+ Given the CRC-32 checksum *crc1* of a sequence ``A`` and the
+ CRC-32 checksum *crc2* of a sequence ``B`` of length *len2*,
+ return the CRC-32 checksum of ``A`` and ``B`` concatenated.
+
+ This function is typically useful to combine CRC-32 checksums
+ that were concurrently computed. To compute checksums sequentially, use
+ :func:`crc32` with the running checksum as the ``value`` argument.
+
+ .. versionadded:: next
+
.. function:: decompress(data, /, wbits=MAX_WBITS, bufsize=DEF_BUF_SIZE)
Decompresses the bytes in *data*, returning a bytes object containing the
diff --git a/Doc/library/zoneinfo.rst b/Doc/library/zoneinfo.rst
index a57f3b8b3e8..53d8e2598ec 100644
--- a/Doc/library/zoneinfo.rst
+++ b/Doc/library/zoneinfo.rst
@@ -195,7 +195,7 @@ The ``ZoneInfo`` class
The ``ZoneInfo`` class has two alternate constructors:
-.. classmethod:: ZoneInfo.from_file(fobj, /, key=None)
+.. classmethod:: ZoneInfo.from_file(file_obj, /, key=None)
Constructs a ``ZoneInfo`` object from a file-like object returning bytes
(e.g. a file opened in binary mode or an :class:`io.BytesIO` object).
@@ -325,7 +325,7 @@ The behavior of a ``ZoneInfo`` file depends on how it was constructed:
>>> a is b
False
-3. ``ZoneInfo.from_file(fobj, /, key=None)``: When constructed from a file, the
+3. ``ZoneInfo.from_file(file_obj, /, key=None)``: When constructed from a file, the
``ZoneInfo`` object raises an exception on pickling. If an end user wants to
pickle a ``ZoneInfo`` constructed from a file, it is recommended that they
use a wrapper type or a custom serialization function: either serializing by