")
with self.assertRaises(ValueError):
@@ -901,6 +941,70 @@ def test_tostring_default_namespace_original_no_namespace(self):
with self.assertRaisesRegex(ValueError, EXPECTED_MSG):
ET.tostring(elem, encoding='unicode', default_namespace='foobar')
+ def test_tostring_default_namespace_attributes(self):
+ # gh-61290: the default namespace does not apply to attribute names
+ elem = ET.XML(''
+ '')
+ self.assertEqual(
+ ET.tostring(elem, encoding='unicode',
+ default_namespace='http://effbot.org/ns'),
+ ''
+ ''
+ )
+
+ def test_tostring_default_namespace_qualified_attributes(self):
+ # a qualified attribute name always needs a prefix, even if it is
+ # in the default namespace
+ elem = ET.Element('{http://effbot.org/ns}body',
+ {'{http://effbot.org/ns}attr': 'value'})
+ self.assertEqual(
+ ET.tostring(elem, encoding='unicode',
+ default_namespace='http://effbot.org/ns'),
+ ''
+ )
+ # an attribute in another namespace uses the prefix of that namespace
+ elem = ET.Element('{http://effbot.org/ns}body',
+ {'{foobar}attr': 'value', 'plain': 'value'})
+ self.assertEqual(
+ ET.tostring(elem, encoding='unicode',
+ default_namespace='http://effbot.org/ns'),
+ ''
+ )
+
+ def test_tostring_default_namespace_attributes_round_trip(self):
+ xml = ('')
+ elem = ET.XML(xml)
+ self.assertEqual(
+ ET.tostring(elem, encoding='unicode',
+ default_namespace='http://effbot.org/ns'),
+ xml
+ )
+ self.assertEqual(
+ [sorted(e.attrib.items()) for e in ET.XML(xml).iter()],
+ [sorted(e.attrib.items()) for e in elem.iter()]
+ )
+
+ def test_tostring_default_namespace_registered_empty_prefix(self):
+ # gh-118416: the empty prefix is registered for other namespace,
+ # so it cannot be used for the default namespace
+ nsmap = ET.register_namespace._namespace_map
+ self.addCleanup(nsmap.pop, 'default', None)
+ ET.register_namespace('', 'default')
+ elem = ET.Element('{default}elem')
+ self.assertEqual(
+ ET.tostring(elem, encoding='unicode',
+ default_namespace='otherdefault'),
+ ''
+ )
+ # without the option the registered prefix is used
+ self.assertEqual(
+ ET.tostring(elem, encoding='unicode'),
+ ''
+ )
+
def test_tostring_no_xml_declaration(self):
elem = ET.XML('')
self.assertEqual(
@@ -933,6 +1037,7 @@ def test_tostring_xml_declaration_cases(self):
(b"\n"
b"\xf8", 'ISO-8859-1', None),
('ø', 'unicode', None),
+ (b"\xef\xbb\xbf\xc3\xb8", 'utf-8-sig', None),
# ... xml_declaration = False
(b"ø", None, False),
@@ -940,6 +1045,7 @@ def test_tostring_xml_declaration_cases(self):
(b"ø", 'US-ASCII', False),
(b"\xf8", 'ISO-8859-1', False),
("ø", 'unicode', False),
+ (b"\xef\xbb\xbf\xc3\xb8", 'utf-8-sig', False),
# ... xml_declaration = True
(b"\n"
@@ -952,6 +1058,8 @@ def test_tostring_xml_declaration_cases(self):
b"\xf8", 'ISO-8859-1', True),
("\n"
"ø", 'unicode', True),
+ (b"\xef\xbb\xbf\n"
+ b"\xc3\xb8", 'utf-8-sig', True),
]
for expected_retval, encoding, xml_declaration in TESTCASES:
@@ -966,6 +1074,96 @@ def test_tostring_xml_declaration_cases(self):
expected_retval
)
+ def test_tostring_default_namespace_attributes_html(self):
+ elem = ET.XML('')
+ self.assertEqual(
+ ET.tostring(elem, encoding='unicode', method='html',
+ default_namespace='http://effbot.org/ns'),
+ ''
+ )
+
+ def test_tostring_standalone(self):
+ elem = ET.XML('')
+ self.assertEqual(
+ ET.tostring(elem, encoding='unicode', standalone=True),
+ "\n"
+ ""
+ )
+ self.assertEqual(
+ ET.tostring(elem, encoding='unicode', standalone=False),
+ "\n"
+ ""
+ )
+ # the XML declaration is written even if it would be omitted
+ self.assertEqual(
+ ET.tostring(elem, standalone=True),
+ b"\n"
+ b""
+ )
+ self.assertEqual(
+ ET.tostring(elem, encoding='UTF-8', standalone=False),
+ b"\n"
+ b""
+ )
+
+ def test_tostring_standalone_none(self):
+ elem = ET.XML('')
+ self.assertEqual(
+ ET.tostring(elem, encoding='unicode', standalone=None),
+ ''
+ )
+ self.assertEqual(
+ ET.tostring(elem, encoding='unicode', xml_declaration=True,
+ standalone=None),
+ "\n"
+ )
+
+ def test_tostring_standalone_without_xml_declaration(self):
+ elem = ET.XML('')
+ for standalone in True, False:
+ for xml_declaration in False, 0, '':
+ with self.subTest(standalone=standalone,
+ xml_declaration=xml_declaration):
+ with self.assertRaises(ValueError):
+ ET.tostring(elem, xml_declaration=xml_declaration,
+ standalone=standalone)
+
+ def test_tostring_standalone_text_method(self):
+ elem = ET.XML('text')
+ self.assertEqual(
+ ET.tostring(elem, encoding='unicode', method='text',
+ standalone=True),
+ 'text'
+ )
+
+ def test_tostringlist_standalone(self):
+ elem = ET.XML('')
+ self.assertEqual(
+ b''.join(ET.tostringlist(elem, standalone=True)),
+ b"\n"
+ b""
+ )
+ with self.assertRaises(ValueError):
+ ET.tostringlist(elem, xml_declaration=False, standalone=False)
+
+ def test_write_standalone(self):
+ elem = ET.XML('')
+ tree = ET.ElementTree(elem)
+ for standalone, expected in [
+ (True, "standalone='yes'"), (False, "standalone='no'")]:
+ with self.subTest(standalone=standalone):
+ file = io.StringIO()
+ tree.write(file, encoding='unicode', standalone=standalone)
+ self.assertEqual(
+ file.getvalue(),
+ "\n"
+ "" % expected
+ )
+ file = io.StringIO()
+ with self.assertRaises(ValueError):
+ tree.write(file, encoding='unicode', xml_declaration=False,
+ standalone=True)
+
def test_tostringlist_default_namespace(self):
elem = ET.XML('')
self.assertEqual(
@@ -1064,6 +1262,74 @@ def bxml(encoding, body=''):
self.assertRaises(ValueError, ET.XML, xml('undefined').encode('ascii'))
self.assertRaises(LookupError, ET.XML, xml('xxx').encode('ascii'))
+ def test_parse_text_source(self):
+ # gh-99064: The encoding declared in the document does not apply
+ # to a source which is already decoded.
+ def check(encoding, body):
+ xml = (f""
+ f"{body}")
+ with self.subTest(encoding=encoding):
+ self.assertEqual(ET.parse(io.StringIO(xml)).getroot().text,
+ body)
+ # the same with an explicitly created parser
+ self.assertEqual(
+ ET.parse(io.StringIO(xml), ET.XMLParser()).getroot().text,
+ body)
+ check("ascii", 'a')
+ check("iso-8859-1", '\xbd')
+ check("iso-8859-15", '\u20ac')
+ check("cp437", '\u221a')
+ check("utf-8", '\u4e2d')
+ # not ASCII compatible, unsupported for a bytes source
+ check("utf-16", '\u4e2d')
+ check("utf-32", '\u4e2d')
+
+ def test_parse_text_source_multiple_chunks(self):
+ # the encoding is overridden before the first chunk is parsed
+ body = '\xe4' * 100_000
+ xml = "%s" % body
+ self.assertEqual(ET.parse(io.StringIO(xml)).getroot().text, body)
+
+ def test_parse_input_larger_than_chunk(self):
+ # gh-83895: the C implementation feeds Expat in chunks of 1 MiB
+ size = 3 * (1 << 20)
+ xml = '%s' % ('x' * size)
+ for source in xml, xml.encode():
+ with self.subTest(type=type(source).__name__):
+ root = ET.fromstring(source)
+ self.assertEqual(len(root[0].text), size)
+ self.assertEqual(root[1].tag, 'b')
+
+ # gh-83895: input larger than INT_MAX is fed to Expat in chunks.
+ # memuse is 3 for the Python implementation, which joins the collected
+ # data, 2 would be enough for the C implementation.
+ @support.bigmemtest(size=support._2G + 100, memuse=3, dry_run=False)
+ def test_large_input(self, size):
+ data = b'' + b'x' * size + b''
+ root = None
+ try:
+ parser = ET.XMLParser()
+ parser.feed(data)
+ data = None
+ root = parser.close()
+ self.assertEqual(len(root.text), size)
+ finally:
+ data = None
+ root = None
+
+ def test_parse_error_after_chunk_boundary(self):
+ # the reported position accounts for the preceding chunks
+ size = 2 * (1 << 20)
+ with self.assertRaises(ET.ParseError) as cm:
+ ET.fromstring('%s<' % ('x' * size))
+ self.assertEqual(cm.exception.position, (1, size + 4))
+
+ def test_parse_error_msg_is_string(self):
+ with self.assertRaises(ET.ParseError) as cm:
+ ET.XML("<")
+ self.assertIsInstance(cm.exception.msg, str)
+ self.assertEqual(cm.exception.msg, "unclosed token: line 1, column 0")
+
@support.subTests('sample,exception', [
(b' \xa1', UnicodeDecodeError), # crashed
(b' \xa1\n"
@@ -1909,6 +2212,76 @@ def __next__(self):
self._feed(parser, "bar")
self.assert_event_tags(parser, [('start', 'foo'), ('end', 'foo')])
+ # gh-63102: the pull parser reports events from any target
+ class SimpleTarget:
+ def start(self, tag, attrib):
+ return ('start', tag)
+ def end(self, tag):
+ return ('end', tag)
+ def data(self, data):
+ pass
+ def comment(self, text):
+ return ('comment', text)
+ def pi(self, target, data=None):
+ return ('pi', target)
+ def close(self):
+ return 'closed'
+
+ def test_custom_target(self):
+ parser = ET.XMLPullParser(events=('start', 'end'),
+ target=self.SimpleTarget())
+ self._feed(parser, "")
+ self.assert_event_tuples(parser, [
+ ('start', ('start', 'root')),
+ ('start', ('start', 'element')),
+ ('end', ('end', 'element')),
+ ('end', ('end', 'root')),
+ ])
+
+ def test_custom_target_comment_pi(self):
+ parser = ET.XMLPullParser(events=('comment', 'pi'),
+ target=self.SimpleTarget())
+ self._feed(parser, "")
+ self.assert_event_tuples(parser, [
+ ('comment', ('comment', ' text ')),
+ ('pi', ('pi', 'pitarget')),
+ ])
+
+ def test_custom_target_without_method(self):
+ class Target:
+ def close(self):
+ pass
+ for event in ('start', 'end', 'comment', 'pi'):
+ with self.subTest(event=event):
+ with self.assertRaisesRegex(TypeError,
+ "the target does not support %r events" % event):
+ ET.XMLPullParser(events=(event,), target=Target())
+ # the namespace events do not need methods of the target
+ parser = ET.XMLPullParser(events=('start-ns', 'end-ns'),
+ target=Target())
+ self._feed(parser, "")
+ self.assert_event_tuples(parser, [
+ ('start-ns', ('', 'namespace')),
+ ('end-ns', None),
+ ])
+
+ def test_custom_target_ns_events(self):
+ # the target does not implement start_ns()/end_ns(),
+ # so the prefix and the uri are reported
+ parser = ET.XMLPullParser(events=('start-ns', 'end-ns'),
+ target=self.SimpleTarget())
+ self._feed(parser, "")
+ self.assert_event_tuples(parser, [
+ ('start-ns', ('', 'namespace')),
+ ('end-ns', None),
+ ])
+
+ def test_custom_target_close(self):
+ parser = ET.XMLPullParser(events=('end',), target=self.SimpleTarget())
+ self._feed(parser, "")
+ parser.close()
+ self.assert_event_tuples(parser, [('end', ('end', 'root'))])
+
def test_unknown_event(self):
with self.assertRaises(ValueError):
ET.XMLPullParser(events=('start', 'end', 'bogus'))
@@ -3246,7 +3619,7 @@ def __deepcopy__(self, memo):
self.assertEqual([c.tag for c in children[3:]],
[a.tag, b.tag, a.tag, b.tag])
- @support.skip_if_unlimited_stack_size
+ @support.run_with_limited_c_stack(500_000)
@support.skip_emscripten_stack_overflow()
@support.skip_wasi_stack_overflow()
def test_deeply_nested_deepcopy(self):
@@ -3477,6 +3850,37 @@ def test_find_xpath(self):
self.assertRaisesRegex(SyntaxError, 'XPath', e.find, './tag[last()-0]')
self.assertRaisesRegex(SyntaxError, 'XPath', e.find, './tag[last()+1]')
+ def test_find_xpath_index_no_quadratic_complexity(self):
+ class CountingElement(ET.Element):
+ findall_calls = 0
+ def findall(self, *args, **kwargs):
+ type(self).findall_calls += 1
+ return super().findall(*args, **kwargs)
+
+ def work(n, pattern):
+ root = CountingElement("root")
+ for _ in range(n):
+ ET.SubElement(root, "a")
+ CountingElement.findall_calls = 0
+ root.findall(pattern)
+ return CountingElement.findall_calls
+
+ for pattern in [".//a[1]", ".//a[last()]"]:
+ w1 = work(1024, pattern)
+ w2 = work(2048, pattern)
+ w3 = work(4096, pattern)
+
+ self.assertGreater(w1, 0)
+ r1 = w2 / w1
+ r2 = w3 / w2
+ # Doubling N must not ~double the parent.findall calls.
+ # Linear-in-N call counts indicate the cache is missing.
+ self.assertLess(
+ max(r1, r2), 1.5,
+ msg=f"Possible quadratic behavior on {pattern!r}: "
+ f"calls={w1, w2, w3} ratios={r1, r2}",
+ )
+
def test_findall(self):
e = ET.XML(SAMPLE_XML)
e[2] = ET.XML(SAMPLE_SECTION)
@@ -3665,6 +4069,19 @@ def test_bad_find(self):
with self.assertRaisesRegex(SyntaxError, 'cannot use absolute path'):
e.findall('/tag')
+ def test_find_invalid_path(self):
+ e = ET.XML(SAMPLE_XML)
+ paths = ('@', './x=y', './(', './)', './]', './!=', './::',
+ './()', "./'tag'", './"tag"', 'tag/@')
+ for obj in (e, ET.ElementTree(e)):
+ for method in ('find', 'findall', 'findtext', 'iterfind'):
+ for path in paths:
+ with self.subTest(type=type(obj).__name__,
+ method=method, path=path):
+ self.assertRaisesRegex(
+ SyntaxError, '^invalid path$',
+ getattr(obj, method), path)
+
def test_find_through_ElementTree(self):
e = ET.XML(SAMPLE_XML)
self.assertEqual(ET.ElementTree(e).find('tag').tag, 'tag')
@@ -4022,6 +4439,21 @@ def close(self):
('html', '-//W3C//DTD XHTML 1.0 Transitional//EN',
'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'))
+ for doctype, expected in [
+ ('', ('html', None, None)),
+ (']>', ('html', None, None)),
+ ('', ('html', None, 'a.dtd')),
+ (']>',
+ ('html', None, 'a.dtd')),
+ ('', ('html', '-//P', 'a.dtd')),
+ ("",
+ ('html', '-//P', 'a.dtd')),
+ ]:
+ with self.subTest(doctype=doctype):
+ parser = ET.XMLParser(target=DoctypeParser())
+ parser.feed(doctype + '')
+ self.assertEqual(parser.close(), expected)
+
def test_builder_lookup_errors(self):
class RaisingBuilder:
def __init__(self, raise_in=None, what=ValueError):
@@ -4720,6 +5152,11 @@ def test_simple_roundtrip(self):
xml = ''
self.assertEqual(c14n_roundtrip(xml), xml)
+ def test_c14n_strip_non_xml_whitespace(self):
+ # only " \t\r\n" are whitespace in XML (see XML 1.0, 2.3)
+ self.assertEqual(c14n_roundtrip(" \xa0x\xa0 ", strip_text=True),
+ "\xa0x\xa0")
+
def test_c14n_exclusion(self):
xml = textwrap.dedent("""\
@@ -4904,13 +5341,10 @@ def get_option(config, option_name, default=None):
class TestModule(unittest.TestCase):
- def test_deprecated_version(self):
- with self.assertWarnsRegex(
- DeprecationWarning,
- "'VERSION' is deprecated and slated for removal in Python 3.20",
- ) as cm:
- getattr(ET, "VERSION")
- self.assertEqual(cm.filename, __file__)
+ def test_deprecated_module_attributes(self):
+ support.check_deprecated_module_attributes(
+ self, ET, "VERSION", remove=(3, 20),
+ )
# --------------------------------------------------------------------
diff --git a/Lib/test/test_xml_etree_c.py b/Lib/test/test_xml_etree_c.py
index 270b9d6da8e7b9e..cf616f300670a3c 100644
--- a/Lib/test/test_xml_etree_c.py
+++ b/Lib/test/test_xml_etree_c.py
@@ -15,16 +15,6 @@
@unittest.skipUnless(cET, 'requires _elementtree')
class MiscTests(unittest.TestCase):
- # Issue #8651.
- @support.bigmemtest(size=support._2G + 100, memuse=1, dry_run=False)
- def test_length_overflow(self, size):
- data = b'x' * size
- parser = cET.XMLParser()
- try:
- self.assertRaises(OverflowError, parser.feed, data)
- finally:
- data = None
-
def test_del_attribute(self):
element = cET.Element('tag')
@@ -171,6 +161,35 @@ def test_xmlpullparser_leaks(self):
del parser
support.gc_collect()
+ def test_iter_tag_reentrant_compare(self):
+ destroyed = []
+ compared = []
+
+ class Tag:
+ def __del__(self):
+ destroyed.append(True)
+
+ def __eq__(self, other):
+ child.tag = "replaced"
+ return NotImplemented
+
+ __hash__ = object.__hash__
+
+ class Sought:
+ def __eq__(self, other):
+ if isinstance(other, Tag):
+ compared.append(not destroyed)
+ return NotImplemented
+
+ __hash__ = object.__hash__
+
+ root = cET.Element("root")
+ child = cET.SubElement(root, "x")
+ child.tag = Tag()
+ self.assertEqual(list(root.iter(Sought())), [])
+ self.assertEqual(compared, [True])
+ self.assertEqual(child.tag, "replaced")
+
def test_dict_disappearing_during_get_item(self):
# test fix for seg fault reported in issue 27946
class X:
@@ -194,8 +213,7 @@ def test_immutable_types(self):
)
for tp in dataset:
with self.subTest(tp=tp):
- with self.assertRaisesRegex(TypeError, "immutable"):
- tp.foo = 1
+ support.check_immutable_type(self, tp)
@support.cpython_only
def test_disallow_instantiation(self):
diff --git a/Lib/test/test_xmlrpc.py b/Lib/test/test_xmlrpc.py
index ee0e24f6e86ae33..78dbb5459cf6ae0 100644
--- a/Lib/test/test_xmlrpc.py
+++ b/Lib/test/test_xmlrpc.py
@@ -252,6 +252,18 @@ def test_loads_unsupported(self):
'')
self.assertRaises(ResponseError, xmlrpclib.loads, data)
+ def test_loads_nested_scalars(self):
+ template = '%s'
+ # CDATA splits 'ab' into two fragments so that joining them again
+ # would allocate another string. str.join() can reuse a single fragment.
+ data = template % 'a'
+ values, _ = xmlrpclib.loads(data)
+ self.assertEqual(values, ('ab', ''))
+
+ data = template % '12'
+ values, _ = xmlrpclib.loads(data)
+ self.assertEqual(values, (1, 2))
+
def check_loads(self, s, value, **kwargs):
dump = '%s' % s
result, m = xmlrpclib.loads(dump, **kwargs)
diff --git a/Lib/test/test_zipapp.py b/Lib/test/test_zipapp.py
index 8fb0a68deba535c..88cc55716f59a80 100644
--- a/Lib/test/test_zipapp.py
+++ b/Lib/test/test_zipapp.py
@@ -366,6 +366,24 @@ def test_shebang_is_executable(self):
zipapp.create_archive(str(source), str(target), interpreter='python')
self.assertTrue(target.stat().st_mode & stat.S_IEXEC)
+ @unittest.skipIf(sys.platform == 'win32',
+ 'Windows does not support an executable bit')
+ @os_helper.skip_unless_working_chmod
+ def test_copied_archive_with_pathlike_target_is_executable(self):
+ # Test that copying an archive to a PathLike target makes it executable.
+ source = self.tmpdir / 'source'
+ source.mkdir()
+ (source / '__main__.py').touch()
+ target = self.tmpdir / 'source.pyz'
+ zipapp.create_archive(source, target, interpreter='python')
+ # Copying an archive uses a different code path than creating
+ # one from scratch. Ensure that the executable bit is set
+ # even if the target is a path-like object.
+ # See https://github.com/python/cpython/issues/156568
+ new_target = self.tmpdir / 'changed.pyz'
+ zipapp.create_archive(target, new_target, interpreter='python')
+ self.assertTrue(new_target.stat().st_mode & stat.S_IEXEC)
+
@unittest.skipIf(sys.platform == 'win32',
'Windows does not support an executable bit')
def test_no_shebang_is_not_executable(self):
diff --git a/Lib/test/test_zipfile/_path/_test_params.py b/Lib/test/test_zipfile/_path/_test_params.py
index 00a9eaf2f99c1ae..8aaf7aa67a4dfb9 100644
--- a/Lib/test/test_zipfile/_path/_test_params.py
+++ b/Lib/test/test_zipfile/_path/_test_params.py
@@ -1,5 +1,6 @@
import functools
import types
+from contextlib import AbstractContextManager
from ._itertools import always_iterable
@@ -9,6 +10,8 @@ def parameterize(names, value_groups):
Decorate a test method to run it as a set of subtests.
Modeled after pytest.parametrize.
+
+ Context Manager types are entered and exited.
"""
def decorator(func):
@@ -17,6 +20,9 @@ def wrapped(self):
for values in value_groups:
resolved = map(Invoked.eval, always_iterable(values))
params = dict(zip(always_iterable(names), resolved))
+ for value in params.values():
+ if isinstance(value, AbstractContextManager):
+ self.enterContext(value)
with self.subTest(**params):
func(self, **params)
diff --git a/Lib/test/test_zipfile/_path/test_complexity.py b/Lib/test/test_zipfile/_path/test_complexity.py
index 7c108fc6ab8191d..f72b5b90c4510dd 100644
--- a/Lib/test/test_zipfile/_path/test_complexity.py
+++ b/Lib/test/test_zipfile/_path/test_complexity.py
@@ -17,7 +17,7 @@
class TestComplexity(unittest.TestCase):
@pytest.mark.flaky
def test_implied_dirs_performance(self):
- best, others = big_o.big_o(
+ best, _others = big_o.big_o(
compose(consume, zipfile._path.CompleteDirs._implied_dirs),
lambda size: [
'/'.join(string.ascii_lowercase + str(n)) for n in range(size)
@@ -66,7 +66,7 @@ def make_deep_path(cls, depth):
return ''.join(('d/',) * depth)
def test_baseline_regex_complexity(self):
- best, others = big_o.big_o(
+ best, _others = big_o.big_o(
lambda path: re.fullmatch(r'[^/]*\\.txt', path),
self.make_deep_path,
max_n=100,
@@ -76,7 +76,7 @@ def test_baseline_regex_complexity(self):
@pytest.mark.flaky
def test_glob_depth(self):
- best, others = big_o.big_o(
+ best, _others = big_o.big_o(
lambda path: consume(path.glob('*.txt')),
self.make_zip_path,
max_n=100,
@@ -86,7 +86,7 @@ def test_glob_depth(self):
@pytest.mark.flaky
def test_glob_width(self):
- best, others = big_o.big_o(
+ best, _others = big_o.big_o(
lambda path: consume(path.glob('*.txt')),
lambda size: self.make_zip_path(width=size),
max_n=100,
@@ -96,7 +96,7 @@ def test_glob_width(self):
@pytest.mark.flaky
def test_glob_width_and_depth(self):
- best, others = big_o.big_o(
+ best, _others = big_o.big_o(
lambda path: consume(path.glob('*.txt')),
lambda size: self.make_zip_path(depth=size, width=size),
max_n=10,
diff --git a/Lib/test/test_zipfile/_path/test_path.py b/Lib/test/test_zipfile/_path/test_path.py
index e7931b6f394075d..eec79311947f6cd 100644
--- a/Lib/test/test_zipfile/_path/test_path.py
+++ b/Lib/test/test_zipfile/_path/test_path.py
@@ -1,4 +1,3 @@
-import contextlib
import io
import itertools
import pathlib
@@ -83,12 +82,8 @@ def build_alpharep_fixture():
class TestPath(unittest.TestCase):
- def setUp(self):
- self.fixtures = contextlib.ExitStack()
- self.addCleanup(self.fixtures.close)
-
def zipfile_ondisk(self, alpharep):
- tmpdir = pathlib.Path(self.fixtures.enter_context(temp_dir()))
+ tmpdir = pathlib.Path(self.enterContext(temp_dir()))
buffer = alpharep.fp
alpharep.close()
path = tmpdir / alpharep.filename
@@ -100,7 +95,7 @@ def zipfile_ondisk(self, alpharep):
def test_iterdir_and_types(self, alpharep):
root = zipfile.Path(alpharep)
assert root.is_dir()
- a, n, b, g, j = root.iterdir()
+ a, n, b, g, j = root.iterdir() # noqa: RUF059
assert a.is_file()
assert b.is_dir()
assert g.is_dir()
@@ -120,8 +115,8 @@ def test_is_file_missing(self, alpharep):
@pass_alpharep
def test_iterdir_on_file(self, alpharep):
root = zipfile.Path(alpharep)
- a, n, b, g, j = root.iterdir()
- with self.assertRaises(ValueError):
+ a, n, b, g, j = root.iterdir() # noqa: RUF059
+ with self.assertRaises(NotADirectoryError):
a.iterdir()
@pass_alpharep
@@ -135,7 +130,7 @@ def test_subdir_is_dir(self, alpharep):
@pass_alpharep
def test_open(self, alpharep):
root = zipfile.Path(alpharep)
- a, n, b, g, j = root.iterdir()
+ a, n, b, g, j = root.iterdir() # noqa: RUF059
with a.open(encoding="utf-8") as strm:
data = strm.read()
self.assertEqual(data, "content of a")
@@ -145,7 +140,7 @@ def test_open(self, alpharep):
def test_open_encoding_utf16(self):
in_memory_file = io.BytesIO()
- zf = zipfile.ZipFile(in_memory_file, "w")
+ zf = self.enterContext(zipfile.ZipFile(in_memory_file, "w"))
zf.writestr("path/16.txt", "This was utf-16".encode("utf-16"))
zf.filename = "test_open_utf16.zip"
root = zipfile.Path(zf)
@@ -160,7 +155,7 @@ def test_open_encoding_utf16(self):
def test_open_encoding_errors(self):
in_memory_file = io.BytesIO()
- zf = zipfile.ZipFile(in_memory_file, "w")
+ zf = self.enterContext(zipfile.ZipFile(in_memory_file, "w"))
zf.writestr("path/bad-utf8.bin", b"invalid utf-8: \xff\xff.")
zf.filename = "test_read_text_encoding_errors.zip"
root = zipfile.Path(zf)
@@ -178,24 +173,30 @@ def test_open_encoding_errors(self):
data = u16.read_text("utf-8", encoding="utf-8")
# both keyword arguments work.
- with u16.open("r", encoding="utf-8", errors="strict") as f:
- # error during decoding with wrong codec.
- with self.assertRaises(UnicodeDecodeError):
- f.read()
+ # error during decoding with wrong codec.
+ with (
+ u16.open("r", encoding="utf-8", errors="strict") as f,
+ self.assertRaises(UnicodeDecodeError),
+ ):
+ f.read()
@unittest.skipIf(
not getattr(sys.flags, 'warn_default_encoding', 0),
"Requires warn_default_encoding",
)
+ @unittest.skipIf(
+ sys.implementation.name == 'pypy' and sys.pypy_version_info < (7, 3, 18),
+ "Older PyPy versions set the wrong stacklevel in text_encoding()",
+ )
@pass_alpharep
def test_encoding_warnings(self, alpharep):
"""EncodingWarning must blame the read_text and open calls."""
assert sys.flags.warn_default_encoding
root = zipfile.Path(alpharep)
- with self.assertWarns(EncodingWarning) as wc: # noqa: F821 (astral-sh/ruff#13296)
+ with self.assertWarns(EncodingWarning) as wc:
root.joinpath("a.txt").read_text()
assert __file__ == wc.filename
- with self.assertWarns(EncodingWarning) as wc: # noqa: F821 (astral-sh/ruff#13296)
+ with self.assertWarns(EncodingWarning) as wc:
root.joinpath("a.txt").open("r").close()
assert __file__ == wc.filename
@@ -204,7 +205,8 @@ def test_open_write(self):
If the zipfile is open for write, it should be possible to
write bytes or text to it.
"""
- zf = zipfile.Path(zipfile.ZipFile(io.BytesIO(), mode='w'))
+ zip_file = self.enterContext(zipfile.ZipFile(io.BytesIO(), mode='w'))
+ zf = zipfile.Path(zip_file)
with zf.joinpath('file.bin').open('wb') as strm:
strm.write(b'binary contents')
with zf.joinpath('file.txt').open('w', encoding="utf-8") as strm:
@@ -239,7 +241,7 @@ def test_open_missing_directory(self, alpharep):
@pass_alpharep
def test_read(self, alpharep):
root = zipfile.Path(alpharep)
- a, n, b, g, j = root.iterdir()
+ a, n, b, g, j = root.iterdir() # noqa: RUF059
assert a.read_text(encoding="utf-8") == "content of a"
# Also check positional encoding arg (gh-101144).
assert a.read_text("utf-8") == "content of a"
@@ -306,7 +308,7 @@ def test_mutability(self, alpharep):
reflect that change.
"""
root = zipfile.Path(alpharep)
- a, n, b, g, j = root.iterdir()
+ a, n, b, g, j = root.iterdir() # noqa: RUF059
alpharep.writestr('foo.txt', 'foo')
alpharep.writestr('bar/baz.txt', 'baz')
assert any(child.name == 'foo.txt' for child in root.iterdir())
@@ -319,7 +321,7 @@ def test_mutability(self, alpharep):
def huge_zipfile(self):
"""Create a read-only zipfile with a huge number of entries."""
strm = io.BytesIO()
- zf = zipfile.ZipFile(strm, "w")
+ zf = self.enterContext(zipfile.ZipFile(strm, "w"))
for entry in map(str, range(self.HUGE_ZIPFILE_NUM_ENTRIES)):
zf.writestr(entry, entry)
zf.mode = 'r'
@@ -351,6 +353,21 @@ class Subclass(zipfile.Path):
root = Subclass(alpharep)
assert isinstance(root / 'b', Subclass)
+ def test_at(self):
+ zip_file = self.enterContext(zipfile.ZipFile(io.BytesIO(), 'w'))
+ root = zipfile.Path(zip_file)
+ assert root.at == ''
+ assert (root / 'foo' / 'bar').at == 'foo/bar'
+
+ def test_str(self):
+ """
+ An unnamed zip file is indicated by ":zipfile:"
+ """
+ zip_file = self.enterContext(zipfile.ZipFile(io.BytesIO(), 'w'))
+ root = zipfile.Path(zip_file)
+ assert str(root) == ':zipfile:'
+ assert str(root / 'foo' / 'bar') == ':zipfile:/foo/bar'
+
@pass_alpharep
def test_filename(self, alpharep):
root = zipfile.Path(alpharep)
@@ -529,8 +546,30 @@ def test_glob_chars(self, alpharep):
zipfile.Path(alpharep, "j/l.baz"),
]
+ @parameterize(
+ ['alpharep', 'pattern', 'expected'],
+ [
+ (alpharep, pattern, expected)
+ for alpharep in alpharep_generators
+ for pattern, expected in [
+ ('[!a].txt', {'n.txt'}),
+ ('[!an].txt', set()),
+ ('[!b]', {'g/', 'j/'}),
+ ('j/[!k].b*', {'j/l.baz', 'j/m.bar'}),
+ ('j/[^k].b*', {'j/k.bin'}),
+ ('j/[!k-l].b*', {'j/m.bar'}),
+ ('j/[k-l].b*', {'j/k.bin', 'j/l.baz'}),
+ ('b[!x]c.txt', set()),
+ ]
+ ],
+ )
+ def test_glob_character_class_syntax(self, alpharep, pattern, expected):
+ root = zipfile.Path(alpharep)
+ assert {path.at for path in root.glob(pattern)} == expected
+
def test_glob_empty(self):
- root = zipfile.Path(zipfile.ZipFile(io.BytesIO(), 'w'))
+ zip_file = self.enterContext(zipfile.ZipFile(io.BytesIO(), 'w'))
+ root = zipfile.Path(zip_file)
with self.assertRaises(ValueError):
root.glob('')
@@ -580,7 +619,7 @@ def test_pickle(self, alpharep, path_type, subpath):
saved_1 = pickle.dumps(root)
root.root.close()
restored_1 = pickle.loads(saved_1)
- first, *rest = restored_1.iterdir()
+ first, *_rest = restored_1.iterdir()
assert first.read_text(encoding='utf-8').startswith('content of ')
restored_1.root.close()
@@ -614,7 +653,7 @@ def test_malformed_paths(self):
Paths with dots are treated like regular files.
"""
data = io.BytesIO()
- zf = zipfile.ZipFile(data, "w")
+ zf = self.enterContext(zipfile.ZipFile(data, "w"))
zf.writestr("/one-slash.txt", b"content")
zf.writestr("//two-slash.txt", b"content")
zf.writestr("../parent.txt", b"content")
@@ -632,7 +671,7 @@ def test_unsupported_names(self):
in the zip file.
"""
data = io.BytesIO()
- zf = zipfile.ZipFile(data, "w")
+ zf = self.enterContext(zipfile.ZipFile(data, "w"))
zf.writestr("path?", b"content")
zf.writestr("V: NMS.flac", b"fLaC...")
zf.filename = ''
@@ -647,7 +686,7 @@ def test_backslash_not_separator(self):
In a zip file, backslashes are not separators.
"""
data = io.BytesIO()
- zf = zipfile.ZipFile(data, "w")
+ zf = self.enterContext(zipfile.ZipFile(data, "w"))
zf.writestr(DirtyZipInfo("foo\\bar")._for_archive(zf), b"content")
zf.filename = ''
root = zipfile.Path(zf)
diff --git a/Lib/test/test_zipfile/test_core.py b/Lib/test/test_zipfile/test_core.py
index 4f20209927e7b3d..ccb8b87023eb5e6 100644
--- a/Lib/test/test_zipfile/test_core.py
+++ b/Lib/test/test_zipfile/test_core.py
@@ -1,6 +1,7 @@
import _pyio
import array
import contextlib
+import errno
import importlib.util
import io
import itertools
@@ -21,16 +22,20 @@
from random import randint, random, randbytes
from test import archiver_tests
-from test.support import script_helper, os_helper
+from test.support import script_helper
from test.support import (
findfile, requires_zlib, requires_bz2, requires_lzma,
requires_zstd, captured_stdout, captured_stderr, requires_subprocess,
- cpython_only
+ cpython_only, gc_collect, catch_unraisable_exception
)
from test.support.os_helper import (
- TESTFN, unlink, rmtree, temp_dir, temp_cwd, fd_count, FakePath
+ TESTFN, unlink, rmtree, temp_dir, temp_cwd, fd_count, FakePath,
+ with_source_date_epoch, without_source_date_epoch,
)
from test.support.import_helper import ensure_lazy_imports
+from test.support.warnings_helper import (
+ check_no_resource_warning, ignore_warnings,
+)
TESTFN2 = TESTFN + "2"
@@ -53,6 +58,15 @@ def get_files(test):
test.assertFalse(f.closed)
+@contextlib.contextmanager
+def save_restore_sys_path():
+ old_path = sys.path.copy()
+ try:
+ yield
+ finally:
+ sys.path[:] = old_path
+
+
class LazyImportTest(unittest.TestCase):
@cpython_only
def test_lazy_import(self):
@@ -497,7 +511,7 @@ def zip_test_writestr_permissions(self, f, compression):
self.make_test_archive(f, compression)
with zipfile.ZipFile(f, "r") as zipfp:
zinfo = zipfp.getinfo('strfile')
- self.assertEqual(zinfo.external_attr, 0o600 << 16)
+ self.assertEqual(zinfo.external_attr, 0o100600 << 16)
zinfo2 = zipfp.getinfo('written-open-w')
self.assertEqual(zinfo2.external_attr, 0o600 << 16)
@@ -655,6 +669,12 @@ def test_add_file_after_2107(self):
os.utime(TESTFN, (ts, ts))
except OverflowError:
self.skipTest('Host fs cannot set timestamp to required value.')
+ except OSError as exc:
+ # Some file systems (e.g. UFS and ZFS on illumos) do not
+ # support timestamps that do not fit in 32 bits.
+ if exc.errno != errno.EOVERFLOW:
+ raise
+ self.skipTest('Host fs cannot set timestamp to required value.')
mtime_ns = os.stat(TESTFN).st_mtime_ns
if mtime_ns != (4386268800 * 10**9):
@@ -1953,6 +1973,7 @@ def test_repack_file_entry_before_first_file(self):
with zipfile.ZipFile(TESTFN) as zh:
self.assertIsNone(zh.testzip())
+ @without_source_date_epoch # SOURCE_DATE_EPOCH would bypass the time mock below
@mock.patch.object(time, 'time', new=lambda: 315590400) # fix time for ZipFile.writestr()
def test_repack_bytes_before_removed_files(self):
"""Should preserve if there are bytes before stale local file entries."""
@@ -1997,6 +2018,7 @@ def test_repack_bytes_before_removed_files(self):
with zipfile.ZipFile(TESTFN) as zh:
self.assertIsNone(zh.testzip())
+ @without_source_date_epoch # SOURCE_DATE_EPOCH would bypass the time mock below
@mock.patch.object(time, 'time', new=lambda: 315590400) # fix time for ZipFile.writestr()
def test_repack_bytes_after_removed_files(self):
"""Should keep extra bytes if there are bytes after stale local file entries."""
@@ -2040,6 +2062,7 @@ def test_repack_bytes_after_removed_files(self):
with zipfile.ZipFile(TESTFN) as zh:
self.assertIsNone(zh.testzip())
+ @without_source_date_epoch # SOURCE_DATE_EPOCH would bypass the time mock below
@mock.patch.object(time, 'time', new=lambda: 315590400) # fix time for ZipFile.writestr()
def test_repack_bytes_between_removed_files(self):
"""Should strip only local file entries before random bytes."""
@@ -2244,6 +2267,7 @@ def test_repack_removed_partial(self):
with zipfile.ZipFile(TESTFN) as zh:
self.assertIsNone(zh.testzip())
+ @without_source_date_epoch # SOURCE_DATE_EPOCH would bypass the time mock below
@mock.patch.object(time, 'time', new=lambda: 315590400) # fix time for ZipFile.writestr()
def test_repack_removed_bytes_between_files(self):
"""Should not remove bytes between local file entries."""
@@ -2375,6 +2399,18 @@ def test_repack_writing(self, m_repack):
zh.repack()
m_repack.assert_not_called()
+ @mock.patch.object(zipfile, '_ZipRepacker')
+ def test_repack_reading(self, m_repack):
+ self._prepare_zip_from_test_files(TESTFN, self.test_files)
+ with zipfile.ZipFile(TESTFN, 'a') as zh:
+ with zh.open(self.test_files[0][0]):
+ with self.assertRaises(ValueError):
+ zh.repack()
+ m_repack.assert_not_called()
+ # Allowed once the reading handle is closed.
+ zh.repack()
+ m_repack.assert_called_once()
+
@mock.patch.object(zipfile, '_ZipRepacker')
def test_repack_mode_r(self, m_repack):
self._prepare_zip_from_test_files(TESTFN, self.test_files)
@@ -3996,29 +4032,24 @@ def test_writestr_extended_local_header_issue1202(self):
zinfo.flag_bits |= zipfile._MASK_USE_DATA_DESCRIPTOR # Include an extended local header.
orig_zip.writestr(zinfo, data)
+ @with_source_date_epoch(epoch=1735715999)
def test_write_with_source_date_epoch(self):
- with os_helper.EnvironmentVarGuard() as env:
- # Set the SOURCE_DATE_EPOCH environment variable to a specific timestamp
- env['SOURCE_DATE_EPOCH'] = "1735715999"
-
- with zipfile.ZipFile(TESTFN, "w") as zf:
- zf.writestr("test_source_date_epoch.txt", "Testing SOURCE_DATE_EPOCH")
+ with zipfile.ZipFile(TESTFN, "w") as zf:
+ zf.writestr("test_source_date_epoch.txt", "Testing SOURCE_DATE_EPOCH")
- with zipfile.ZipFile(TESTFN, "r") as zf:
- zip_info = zf.getinfo("test_source_date_epoch.txt")
- expected_utc = (2025, 1, 1, 7, 19, 58)
- self.assertEqual(zip_info.date_time, expected_utc)
+ with zipfile.ZipFile(TESTFN, "r") as zf:
+ zip_info = zf.getinfo("test_source_date_epoch.txt")
+ expected_utc = (2025, 1, 1, 7, 19, 58)
+ self.assertEqual(zip_info.date_time, expected_utc)
+ @without_source_date_epoch
def test_write_without_source_date_epoch(self):
- with os_helper.EnvironmentVarGuard() as env:
- del env['SOURCE_DATE_EPOCH']
-
- with zipfile.ZipFile(TESTFN, "w") as zf:
- zf.writestr("test_no_source_date_epoch.txt", "Testing without SOURCE_DATE_EPOCH")
+ with zipfile.ZipFile(TESTFN, "w") as zf:
+ zf.writestr("test_no_source_date_epoch.txt", "Testing without SOURCE_DATE_EPOCH")
- with zipfile.ZipFile(TESTFN, "r") as zf:
- zip_info = zf.getinfo("test_no_source_date_epoch.txt")
- self.assertTimestampAlmostEqual(time.localtime(), zip_info.date_time, tolerance=2)
+ with zipfile.ZipFile(TESTFN, "r") as zf:
+ zip_info = zf.getinfo("test_no_source_date_epoch.txt")
+ self.assertTimestampAlmostEqual(time.localtime(), zip_info.date_time, tolerance=2)
def assertTimestampAlmostEqual(self, time1, time2, tolerance):
import datetime
@@ -4051,6 +4082,43 @@ def test_close_on_exception(self):
except zipfile.BadZipFile:
self.assertIsNone(zipfp2.fp, 'zipfp is not closed')
+ def test_garbage_collection(self):
+ # gh-81954: Warn if a writable zipfile is closed by GC.
+ with self.assertWarns(ResourceWarning):
+ zipfile.ZipFile(io.BytesIO(), "w")
+ gc_collect()
+
+ # Only warn if there is possible data loss.
+ # Properly closed via context manager.
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("f.txt", b"data")
+
+ with check_no_resource_warning(self):
+ # Read mode: No possible data loss.
+ zipfile.ZipFile(buf, "r")
+
+ # Write with manual explicit close: No pending data.
+ zf = zipfile.ZipFile(io.BytesIO(), "w")
+ zf.writestr("f.txt", b"data")
+ zf.close()
+ del zf
+
+ # ResourceWarning escalated to an error is reported as unraisable,
+ # and the archive is still closed.
+ buf = io.BytesIO()
+ zf = zipfile.ZipFile(buf, "w")
+ zf.writestr("f.txt", b"data")
+ with (warnings.catch_warnings(action="error", category=ResourceWarning),
+ catch_unraisable_exception() as cm):
+ del zf
+ gc_collect()
+ self.assertIs(cm.unraisable.exc_type, ResourceWarning)
+
+ with zipfile.ZipFile(buf, "r") as zf:
+ self.assertEqual(zf.namelist(), ["f.txt"])
+ self.assertEqual(zf.read("f.txt"), b"data")
+
def test_unsupported_version(self):
# File has an extract_version of 120
data = (b'PK\x03\x04x\x00\x00\x00\x00\x00!p\xa1@\x00\x00\x00\x00\x00\x00'
@@ -4241,6 +4309,20 @@ def test_is_zip_valid_file(self):
self.assertTrue(zipfile.is_zipfile(fp))
self.assertEqual(fp.tell(), mid)
+ def test_is_zip_bad_central_directory_offset(self):
+ """Check that is_zipfile() rejects a central directory before the file."""
+ fp = io.BytesIO()
+ with zipfile.ZipFile(fp, mode="w") as zipf:
+ zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
+ data = bytearray(fp.getvalue())
+ endrec = len(data) - zipfile.sizeEndCentDir
+ struct.pack_into("> 16, filemode)
self.assertEqual(zi.external_attr & 0xFF, 0) # no MS-DOS flag
@@ -4556,6 +4709,8 @@ def test_open_conflicting_handles(self):
zipf.writestr('str', 'abcde')
with self.assertRaises(ValueError):
zipf.write(__file__, 'file')
+ with self.assertRaises(ValueError):
+ zipf.mkdir('directory')
with self.assertRaises(ValueError):
zipf.close()
w1.write(msg2)
@@ -4832,6 +4987,117 @@ def tearDown(self):
unlink(TESTFN2)
+class AbstractBoundedDecompressTests:
+ # ZipExtFile._read1() bounds the output of each decompress() call so that a
+ # small member declaring a large uncompressed size cannot expand into one
+ # unbounded read.
+ def test_read1_output_is_bounded(self):
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w", compression=self.compression) as zf:
+ zf.writestr("big", b"\0" * (4 * 1024 * 1024))
+ with zipfile.ZipFile(io.BytesIO(buf.getvalue())) as zf:
+ with zf.open("big") as f:
+ self.assertLessEqual(len(f._read1(100)), f.MIN_READ_SIZE)
+
+
+class StoredBoundedDecompressTests(AbstractBoundedDecompressTests,
+ unittest.TestCase):
+ compression = zipfile.ZIP_STORED
+
+
+@requires_zlib()
+class DeflateBoundedDecompressTests(AbstractBoundedDecompressTests,
+ unittest.TestCase):
+ compression = zipfile.ZIP_DEFLATED
+
+
+@requires_bz2()
+class Bzip2BoundedDecompressTests(AbstractBoundedDecompressTests,
+ unittest.TestCase):
+ compression = zipfile.ZIP_BZIP2
+
+
+@requires_lzma()
+class LzmaBoundedDecompressTests(AbstractBoundedDecompressTests,
+ unittest.TestCase):
+ compression = zipfile.ZIP_LZMA
+
+
+@requires_zstd()
+class ZstdBoundedDecompressTests(AbstractBoundedDecompressTests,
+ unittest.TestCase):
+ compression = zipfile.ZIP_ZSTANDARD
+
+
+class MonkeypatchedDecompressorTests(unittest.TestCase):
+ # Some third-party projects monkey-patch _get_decompressor() to add
+ # additional compression schemes. This can break at any time as the
+ # internal compressor objects change.
+ # To protect users, we try to keep this case working.
+ # See also: GH-156002 and GH-113767.
+ COMPRESSION = 99
+
+ class Compressor:
+ """Compressor with only the original BZ2Compressor API"""
+ def compress(self, data):
+ return data.swapcase()
+
+ def flush(self):
+ return b''
+
+ class Decompressor:
+ """Decompressor with only the 3.3+ BZ2Decompressor API"""
+ eof = False
+
+ def decompress(self, data):
+ return data.swapcase()
+
+ def setUp(self):
+ orig_check_compression = zipfile._check_compression
+ orig_get_compressor = zipfile._get_compressor
+ orig_get_decompressor = zipfile._get_decompressor
+
+ def check_compression(compression):
+ if compression != self.COMPRESSION:
+ orig_check_compression(compression)
+
+ def get_compressor(compress_type, compresslevel=None):
+ if compress_type == self.COMPRESSION:
+ return self.Compressor()
+ return orig_get_compressor(compress_type, compresslevel)
+
+ def get_decompressor(compress_type):
+ if compress_type == self.COMPRESSION:
+ return self.Decompressor()
+ return orig_get_decompressor(compress_type)
+
+ self.enterContext(mock.patch.object(
+ zipfile, '_check_compression', check_compression))
+ self.enterContext(mock.patch.object(
+ zipfile, '_get_compressor', get_compressor))
+ self.enterContext(mock.patch.object(
+ zipfile, '_get_decompressor', get_decompressor))
+
+ def test_roundtrip_monkeypatched_decompressor(self):
+ data = bytes(range(256)) * 8
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w", compression=self.COMPRESSION) as zf:
+ zf.writestr("member", data)
+ self.assertIn(data.swapcase(), buf.getvalue())
+ with (ignore_warnings(category=DeprecationWarning,
+ message='.*two arguments.*'),
+ zipfile.ZipFile(io.BytesIO(buf.getvalue())) as zf):
+ self.assertEqual(zf.read("member"), data)
+ with zf.open("member") as f:
+ self.assertEqual(f.read(100), data[:100])
+ self.assertEqual(f.read1(100), data[100:200])
+ f.seek(-100, os.SEEK_END)
+ self.assertEqual(f.read(), data[-100:])
+ # Rewinding past the read buffer re-creates the decompressor.
+ f.seek(0)
+ self.assertEqual(f.read(), data)
+
+
class AbstractBadCrcTests:
def test_testzip_with_bad_crc(self):
"""Tests that files with bad CRCs return their name from testzip."""
@@ -5412,14 +5678,14 @@ def test_write_dir(self):
self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
zipf.write(dirpath, "y")
zinfo = zipf.filelist[1]
- self.assertTrue(zinfo.filename, "y/")
+ self.assertEqual(zinfo.filename, "y/")
self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
with zipfile.ZipFile(TESTFN, "r") as zipf:
zinfo = zipf.filelist[0]
self.assertEndsWith(zinfo.filename, "/x/")
self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
zinfo = zipf.filelist[1]
- self.assertTrue(zinfo.filename, "y/")
+ self.assertEqual(zinfo.filename, "y/")
self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
target = os.path.join(TESTFN2, "target")
os.mkdir(target)
@@ -5476,6 +5742,9 @@ def test_mkdir(self):
zf.extractall(target)
self.assertEqual(set(os.listdir(target)), {"directory", "directory2", "directory3", "directory4"})
+ with self.assertRaises(ValueError):
+ zf.mkdir("closed")
+
def test_create_directory_with_write(self):
with zipfile.ZipFile(TESTFN, "w") as zf:
zf.writestr(zipfile.ZipInfo('directory/'), '')
@@ -5503,10 +5772,10 @@ def test_root_folder_in_zipfile(self):
the zip file, this is a strange behavior, but we should support it.
"""
in_memory_file = io.BytesIO()
- zf = zipfile.ZipFile(in_memory_file, "w")
- zf.mkdir('/')
- zf.writestr('./a.txt', 'aaa')
- zf.extractall(TESTFN2)
+ with zipfile.ZipFile(in_memory_file, "w") as zf:
+ zf.mkdir('/')
+ zf.writestr('./a.txt', 'aaa')
+ zf.extractall(TESTFN2)
def tearDown(self):
rmtree(TESTFN2)
@@ -5798,17 +6067,18 @@ def test_add_comment(self):
def test_cli_with_metadata_encoding(self):
errmsg = "Non-conforming encodings not supported with -c."
args = ["--metadata-encoding=shift_jis", "-c", "nonesuch", "nonesuch"]
- with captured_stdout() as stdout:
- with captured_stderr() as stderr:
+ with (captured_stdout() as stdout,
+ captured_stderr() as stderr,
+ save_restore_sys_path()):
self.assertRaises(SystemExit, zipfile.main, args)
self.assertEqual(stdout.getvalue(), "")
self.assertIn(errmsg, stderr.getvalue())
- with captured_stdout() as stdout:
+ with captured_stdout() as stdout, save_restore_sys_path():
zipfile.main(["--metadata-encoding=shift_jis", "-t", TESTFN])
listing = stdout.getvalue()
- with captured_stdout() as stdout:
+ with captured_stdout() as stdout, save_restore_sys_path():
zipfile.main(["--metadata-encoding=shift_jis", "-l", TESTFN])
listing = stdout.getvalue()
for name in self.file_names:
@@ -5827,7 +6097,9 @@ def test_cli_with_metadata_encoding_extract(self):
except UnicodeEncodeError:
self.skipTest(f'cannot encode file name {fn!a}')
- zipfile.main(["--metadata-encoding=shift_jis", "-e", TESTFN, TESTFN2])
+ with save_restore_sys_path():
+ zipfile.main(["--metadata-encoding=shift_jis", "-e",
+ TESTFN, TESTFN2])
listing = os.listdir(TESTFN2)
for name in self.file_names:
self.assertIn(name, listing)
diff --git a/Lib/test/test_zipfile64.py b/Lib/test/test_zipfile64.py
index 7d802d59849ce1f..e13f064f2ac4fd4 100644
--- a/Lib/test/test_zipfile64.py
+++ b/Lib/test/test_zipfile64.py
@@ -17,6 +17,7 @@
import sys
import unittest.mock as mock
+from contextlib import contextmanager
from tempfile import TemporaryFile
from test.support import os_helper
@@ -91,176 +92,133 @@ def tearDown(self):
os_helper.unlink(TESTFN2)
-class TestRepack(unittest.TestCase):
- def setUp(self):
- # Create test data.
- line_gen = ("Test of zipfile line %d." % i for i in range(1000000))
- self.data = '\n'.join(line_gen).encode('ascii')
-
- # It will contain enough copies of self.data to reach about 8 GiB.
- self.datacount = 8*1024**3 // len(self.data)
+class TestRepacker(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.largefilename = 'largefile.txt'
- # memory usage should not exceed 10 MiB
- self.allowed_memory = 10*1024**2
+ line_gen = ("Test of zipfile line %d." % i for i in range(1000000))
+ cls.chunk = '\n'.join(line_gen).encode('ascii')
+
+ # It will contain enough copies of cls.chunk to reach about 4.1 GiB.
+ cls.chunkcount = int(4.1*1024**3 / len(cls.chunk))
+
+ cls.filename = 'file.txt'
+ cls.lorem = b'Sed ut perspiciatis unde omnis iste natus error sit voluptatem'
+
+ # Memory usage should not exceed 10 MiB during repacking.
+ # This empirical threshold ensures that the internal processing
+ # like signature scanning, compressed block end tracing, and
+ # data copying are properly buffered without loading the entire
+ # large file into memory.
+ cls.allowed_memory = 10*1024**2
+
+ @contextmanager
+ def assert_memory_usage(self, threshold):
+ tracemalloc.start()
+ try:
+ yield
+ finally:
+ current, peak = tracemalloc.get_traced_memory()
+ tracemalloc.stop()
+ self.assertLess(peak, threshold)
def _write_large_file(self, fh):
next_time = time.monotonic() + _PRINT_WORKING_MSG_INTERVAL
- for num in range(self.datacount):
- fh.write(self.data)
+ for num in range(self.chunkcount):
+ fh.write(self.chunk)
# Print still working message since this test can be really slow
if next_time <= time.monotonic():
next_time = time.monotonic() + _PRINT_WORKING_MSG_INTERVAL
print((
' writing %d of %d, be patient...' %
- (num, self.datacount)), file=sys.__stdout__)
+ (num, self.chunkcount)), file=sys.__stdout__)
sys.__stdout__.flush()
def test_strip_removed_large_file(self):
"""Should move the physical data of a file positioned after a large
removed file without causing a memory issue."""
- # Try the temp file. If we do TESTFN2, then it hogs
- # gigabytes of disk space for the duration of the test.
with TemporaryFile() as f:
- tracemalloc.start()
- self._test_strip_removed_large_file(f)
- self.assertFalse(f.closed)
- current, peak = tracemalloc.get_traced_memory()
- tracemalloc.stop()
- self.assertLess(peak, self.allowed_memory)
-
- def _test_strip_removed_large_file(self, f):
- file = 'file.txt'
- file1 = 'largefile.txt'
- data = b'Sed ut perspiciatis unde omnis iste natus error sit voluptatem'
- with zipfile.ZipFile(f, 'w') as zh:
- with zh.open(file1, 'w', force_zip64=True) as fh:
- self._write_large_file(fh)
- zh.writestr(file, data)
-
- with zipfile.ZipFile(f, 'a') as zh:
- zh.remove(file1)
- zh.repack()
- self.assertIsNone(zh.testzip())
+ with zipfile.ZipFile(f, 'w') as zh:
+ with zh.open(self.largefilename, 'w', force_zip64=True) as fh:
+ self._write_large_file(fh)
+ zh.writestr(self.filename, self.lorem)
+
+ with self.assert_memory_usage(self.allowed_memory), \
+ zipfile.ZipFile(f, 'a') as zh:
+ zh.remove(self.largefilename)
+ zh.repack()
+ self.assertIsNone(zh.testzip())
def test_strip_removed_file_before_large_file(self):
"""Should move the physical data of a large file positioned after a
removed file without causing a memory issue."""
- # Try the temp file. If we do TESTFN2, then it hogs
- # gigabytes of disk space for the duration of the test.
with TemporaryFile() as f:
- tracemalloc.start()
- self._test_strip_removed_file_before_large_file(f)
- self.assertFalse(f.closed)
- current, peak = tracemalloc.get_traced_memory()
- tracemalloc.stop()
- self.assertLess(peak, self.allowed_memory)
-
- def _test_strip_removed_file_before_large_file(self, f):
- file = 'file.txt'
- file1 = 'largefile.txt'
- data = b'Sed ut perspiciatis unde omnis iste natus error sit voluptatem'
- with zipfile.ZipFile(f, 'w') as zh:
- zh.writestr(file, data)
- with zh.open(file1, 'w', force_zip64=True) as fh:
- self._write_large_file(fh)
-
- with zipfile.ZipFile(f, 'a') as zh:
- zh.remove(file)
- zh.repack()
- self.assertIsNone(zh.testzip())
+ with zipfile.ZipFile(f, 'w') as zh:
+ zh.writestr(self.filename, self.lorem)
+ with zh.open(self.largefilename, 'w', force_zip64=True) as fh:
+ self._write_large_file(fh)
+
+ with self.assert_memory_usage(self.allowed_memory), \
+ zipfile.ZipFile(f, 'a') as zh:
+ zh.remove(self.filename)
+ zh.repack()
+ self.assertIsNone(zh.testzip())
def test_strip_removed_large_file_with_dd(self):
"""Should scan for the data descriptor of a removed large file without
causing a memory issue."""
- # Try the temp file. If we do TESTFN2, then it hogs
- # gigabytes of disk space for the duration of the test.
with TemporaryFile() as f:
- tracemalloc.start()
- self._test_strip_removed_large_file_with_dd(f)
- self.assertFalse(f.closed)
- current, peak = tracemalloc.get_traced_memory()
- tracemalloc.stop()
- self.assertLess(peak, self.allowed_memory)
-
- def _test_strip_removed_large_file_with_dd(self, f):
- file = 'file.txt'
- file1 = 'largefile.txt'
- data = b'Sed ut perspiciatis unde omnis iste natus error sit voluptatem'
- with zipfile.ZipFile(Unseekable(f), 'w') as zh:
- with zh.open(file1, 'w', force_zip64=True) as fh:
- self._write_large_file(fh)
- zh.writestr(file, data)
-
- with zipfile.ZipFile(f, 'a') as zh:
- zh.remove(file1)
- zh.repack()
- self.assertIsNone(zh.testzip())
+ with zipfile.ZipFile(Unseekable(f), 'w') as zh:
+ with zh.open(self.largefilename, 'w', force_zip64=True) as fh:
+ self._write_large_file(fh)
+ zh.writestr(self.filename, self.lorem)
+
+ with self.assert_memory_usage(self.allowed_memory), \
+ zipfile.ZipFile(f, 'a') as zh:
+ zh.remove(self.largefilename)
+ zh.repack()
+ self.assertIsNone(zh.testzip())
def test_strip_removed_large_file_with_dd_no_sig(self):
- """Should scan for the data descriptor (without signature) of a removed
- large file without causing a memory issue."""
+ """Should scan for the unsigned data descriptor of a removed large file
+ without causing a memory issue."""
# Reduce data scale for this test, as it's especially slow...
- self.datacount = 30*1024**2 // len(self.data)
- self.allowed_memory = 200*1024
+ self.chunkcount = int(30*1024**2 / len(self.chunk))
- # Try the temp file. If we do TESTFN2, then it hogs
- # gigabytes of disk space for the duration of the test.
with TemporaryFile() as f:
- tracemalloc.start()
- self._test_strip_removed_large_file_with_dd_no_sig(f)
- self.assertFalse(f.closed)
- current, peak = tracemalloc.get_traced_memory()
- tracemalloc.stop()
- self.assertLess(peak, self.allowed_memory)
-
- def _test_strip_removed_large_file_with_dd_no_sig(self, f):
- file = 'file.txt'
- file1 = 'largefile.txt'
- data = b'Sed ut perspiciatis unde omnis iste natus error sit voluptatem'
- with mock.patch('zipfile.struct.pack', side_effect=struct_pack_no_dd_sig):
- with zipfile.ZipFile(Unseekable(f), 'w') as zh:
- with zh.open(file1, 'w', force_zip64=True) as fh:
+ with mock.patch('zipfile.struct.pack', side_effect=struct_pack_no_dd_sig), \
+ zipfile.ZipFile(Unseekable(f), 'w') as zh:
+ with zh.open(self.largefilename, 'w', force_zip64=True) as fh:
self._write_large_file(fh)
- zh.writestr(file, data)
+ zh.writestr(self.filename, self.lorem)
- with zipfile.ZipFile(f, 'a') as zh:
- zh.remove(file1)
- # strict_descriptor=False to scan the unsigned data descriptor
- # (scanning is disabled under the strict_descriptor=True default)
- zh.repack(strict_descriptor=False)
- self.assertIsNone(zh.testzip())
+ with self.assert_memory_usage(self.allowed_memory), \
+ zipfile.ZipFile(f, 'a') as zh:
+ zh.remove(self.largefilename)
+ # strict_descriptor=False to scan the unsigned data descriptor
+ # (scanning is disabled under the strict_descriptor=True default)
+ zh.repack(strict_descriptor=False)
+ self.assertIsNone(zh.testzip())
@requires_zlib()
def test_strip_removed_large_file_with_dd_no_sig_by_decompression(self):
- """Should scan for the data descriptor (without signature) of a removed
- large file without causing a memory issue."""
- # Try the temp file. If we do TESTFN2, then it hogs
- # gigabytes of disk space for the duration of the test.
+ """Should scan for the unsigned data descriptor (via tracing compressed
+ block end) of a removed large file without causing a memory issue."""
with TemporaryFile() as f:
- tracemalloc.start()
- self._test_strip_removed_large_file_with_dd_no_sig_by_decompression(
- f, zipfile.ZIP_DEFLATED)
- self.assertFalse(f.closed)
- current, peak = tracemalloc.get_traced_memory()
- tracemalloc.stop()
- self.assertLess(peak, self.allowed_memory)
-
- def _test_strip_removed_large_file_with_dd_no_sig_by_decompression(self, f, method):
- file = 'file.txt'
- file1 = 'largefile.txt'
- data = b'Sed ut perspiciatis unde omnis iste natus error sit voluptatem'
- with mock.patch('zipfile.struct.pack', side_effect=struct_pack_no_dd_sig):
- with zipfile.ZipFile(Unseekable(f), 'w', compression=method) as zh:
- with zh.open(file1, 'w', force_zip64=True) as fh:
+ with mock.patch('zipfile.struct.pack', side_effect=struct_pack_no_dd_sig), \
+ zipfile.ZipFile(Unseekable(f), 'w', compression=zipfile.ZIP_DEFLATED) as zh:
+ with zh.open(self.largefilename, 'w', force_zip64=True) as fh:
self._write_large_file(fh)
- zh.writestr(file, data)
-
- with zipfile.ZipFile(f, 'a') as zh:
- zh.remove(file1)
- # strict_descriptor=False to detect the unsigned data descriptor
- # (scanning is disabled under the strict_descriptor=True default)
- zh.repack(strict_descriptor=False)
- self.assertIsNone(zh.testzip())
+ zh.writestr(self.filename, self.lorem)
+
+ with self.assert_memory_usage(self.allowed_memory), \
+ zipfile.ZipFile(f, 'a') as zh:
+ zh.remove(self.largefilename)
+ # strict_descriptor=False to detect the unsigned data descriptor
+ # (scanning is disabled under the strict_descriptor=True default)
+ zh.repack(strict_descriptor=False)
+ self.assertIsNone(zh.testzip())
class OtherTests(unittest.TestCase):
diff --git a/Lib/test/test_zipimport.py b/Lib/test/test_zipimport.py
index 76cd85709a63af8..94875d7153f9c5b 100644
--- a/Lib/test/test_zipimport.py
+++ b/Lib/test/test_zipimport.py
@@ -9,6 +9,7 @@
import time
import unittest
import unittest.mock
+import warnings
from test import support
from test.support import import_helper
@@ -229,6 +230,81 @@ def testPy(self):
files = {TESTMOD + ".py": test_src}
self.doTest(".py", files, TESTMOD)
+ def test_syntax_warning(self):
+ files = {TESTMOD + ".py": "x = 1 is 1\n"}
+ self.makeZip(files)
+ zi = zipimport.zipimporter(TEMP_ZIP)
+
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always", SyntaxWarning)
+ spec = zi.find_spec(TESTMOD)
+ self.assertIsNotNone(spec)
+ self.assertEqual(caught, [])
+
+ mod = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(mod)
+
+ self.assertEqual(len(caught), 1)
+ self.assertIsInstance(caught[0].message, SyntaxWarning)
+
+ def test_syntax_error_defers_to_exec(self):
+ files = {TESTMOD + ".py": "x =\n"}
+ self.makeZip(files)
+ zi = zipimport.zipimporter(TEMP_ZIP)
+ expected_path = os.path.join(TEMP_ZIP, TESTMOD + ".py")
+
+ spec = zi.find_spec(TESTMOD)
+ self.assertIsNotNone(spec)
+ self.assertEqual(spec.origin, expected_path)
+ self.assertEqual(zi.get_filename(TESTMOD), expected_path)
+
+ mod = importlib.util.module_from_spec(spec)
+ with self.assertRaises(SyntaxError):
+ spec.loader.exec_module(mod)
+
+ def test_get_filename_no_warnings(self):
+ files = {TESTMOD + ".py": "x = 1 is 1\n"}
+ self.makeZip(files)
+ zi = zipimport.zipimporter(TEMP_ZIP)
+
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always", SyntaxWarning)
+ zi.get_filename(TESTMOD)
+
+ self.assertEqual(caught, [])
+
+ def test_syntax_error_in_source_with_valid_pyc(self):
+ bad_src = "x =\n"
+ files = {TESTMOD + ".py": bad_src,
+ TESTMOD + pyc_ext: make_pyc(test_co, NOW, len(bad_src))}
+ self.makeZip(files)
+ zi = zipimport.zipimporter(TEMP_ZIP)
+ expected_path = os.path.join(TEMP_ZIP, TESTMOD + pyc_ext)
+
+ spec = zi.find_spec(TESTMOD)
+ self.assertIsNotNone(spec)
+ self.assertEqual(spec.origin, expected_path)
+
+ mod = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(mod)
+ self.assertEqual(mod.get_file(), expected_path)
+
+ def test_syntax_error_in_package_init_no_fallthrough(self):
+ packdir = TESTPACK + os.sep
+ files = {packdir + "__init__.py": "x =\n",
+ TESTPACK + ".py": test_src}
+ self.makeZip(files)
+ zi = zipimport.zipimporter(TEMP_ZIP)
+ expected_path = os.path.join(TEMP_ZIP, TESTPACK, "__init__.py")
+
+ spec = zi.find_spec(TESTPACK)
+ self.assertIsNotNone(spec)
+ self.assertEqual(spec.origin, expected_path)
+
+ mod = importlib.util.module_from_spec(spec)
+ with self.assertRaises(SyntaxError):
+ spec.loader.exec_module(mod)
+
def testPyc(self):
files = {TESTMOD + pyc_ext: test_pyc}
self.doTest(pyc_ext, files, TESTMOD)
@@ -1026,6 +1102,62 @@ class DeflateCompressedZipImportTestCase(UncompressedZipImportTestCase):
class ZStdCompressedZipImportTestCase(UncompressedZipImportTestCase):
compression = ZIP_ZSTANDARD
+ def test_concatenated_frames(self):
+ from compression import zstd
+ import zipfile
+
+ class ConcatenatedFrameCompressor:
+ def compress(self, data):
+ return b"".join(zstd.compress(bytes([byte])) for byte in data)
+
+ def flush(self):
+ return b""
+
+ with unittest.mock.patch.object(
+ zipfile,
+ "_get_compressor",
+ return_value=ConcatenatedFrameCompressor(),
+ ):
+ self.doTest(".py", {TESTMOD + ".py": test_src}, TESTMOD)
+
+ def test_concatenated_frames_linear_input(self):
+ from compression import zstd
+
+ frame_count = 100
+ frame = zstd.compress(b"x")
+ compressed = frame * frame_count
+ input_sizes = []
+ decompressor_class = zipimport._get_zstd_decompressor_class()
+
+ class RecordingDecompressor:
+ def __init__(self):
+ self._decompressor = decompressor_class()
+
+ def __getattr__(self, name):
+ return getattr(self._decompressor, name)
+
+ def decompress(self, data, max_length=-1):
+ input_sizes.append(memoryview(data).nbytes)
+ return self._decompressor.decompress(data, max_length)
+
+ with unittest.mock.patch.object(
+ zipimport, "_zstd_decompressor_class", RecordingDecompressor
+ ):
+ self.assertEqual(
+ zipimport._zstd_decompress(compressed), b"x" * frame_count
+ )
+
+ self.assertEqual(sum(input_sizes), len(compressed))
+
+ def test_truncated_frame(self):
+ from compression import zstd
+
+ compressed = zstd.compress(b"x")
+ for data in (b"", compressed[:-1]):
+ with self.subTest(data=data):
+ with self.assertRaises(zipimport.ZipImportError):
+ zipimport._zstd_decompress(data)
+
class BadFileZipImportTestCase(unittest.TestCase):
def assertZipFailure(self, filename):
@@ -1074,6 +1206,24 @@ def testNotZipFile(self):
fp.close()
self.assertZipFailure(TESTMOD)
+ def testInvalidUTF8FileName(self):
+ # A UTF-8-flagged file name that is not valid UTF-8 raises ZipImportError.
+ UTF8_FLAG = 0x800
+ name = b'\xff\xfe\xff'
+ cdh = b'PK\x01\x02' + struct.pack(
+ '= (1, 2, 5, 3):
+ if zlib.zlib_version_info >= (1, 2, 5, 3):
sync_opt.append('Z_BLOCK')
sync_opt = [getattr(zlib, opt) for opt in sync_opt
@@ -719,6 +782,20 @@ def test_decompress_eof_incomplete_stream(self):
dco.flush()
self.assertFalse(dco.eof)
+ def test_decompress_flush_corrupt_stream(self):
+ x = b'x\x9cK\xcb\xcf\x07\x00\x02\x82\x01E' # 'foo'
+ corrupt = x[:-1] + b'\x00'
+ dco = zlib.decompressobj()
+ self.assertEqual(dco.decompress(corrupt, 1), b'f')
+ self.assertRaises(zlib.error, dco.flush)
+
+ def test_decompress_flush_twice(self):
+ x = b'x\x9cK\xcb\xcf\x07\x00\x02\x82\x01E' # 'foo'
+ dco = zlib.decompressobj()
+ self.assertEqual(dco.decompress(x), b'foo')
+ self.assertEqual(dco.flush(), b'')
+ self.assertEqual(dco.flush(), b'')
+
def test_decompress_unused_data(self):
# Repeated calls to decompress() after EOF should accumulate data in
# dco.unused_data, instead of just storing the arg to the last call.
@@ -745,6 +822,18 @@ def test_decompress_unused_data(self):
self.assertEqual(dco.unconsumed_tail, b'')
self.assertEqual(dco.unused_data, remainder)
+ def test_decompress_unconsumed_tail_after_eof(self):
+ source = b'abcdefghijklmnopqrstuvwxyz'
+ remainder = b'0123456789'
+ dco = zlib.decompressobj()
+ data = dco.decompress(zlib.compress(source) + remainder, 1)
+ data += dco.decompress(dco.unconsumed_tail)
+
+ self.assertTrue(dco.eof)
+ self.assertEqual(data, source)
+ self.assertEqual(dco.unconsumed_tail, b'')
+ self.assertEqual(dco.unused_data, remainder)
+
# issue27164
def test_decompress_raw_with_dictionary(self):
zdict = b'abcdefghijklmnopqrstuvwxyz'
@@ -918,7 +1007,7 @@ def test_large_unconsumed_tail(self, size):
def test_wbits(self):
# wbits=0 only supported since zlib v1.2.3.5
- supports_wbits_0 = ZLIB_RUNTIME_VERSION_TUPLE >= (1, 2, 3, 5)
+ supports_wbits_0 = zlib.zlib_version_info >= (1, 2, 3, 5)
co = zlib.compressobj(level=1, wbits=15)
zlib15 = co.compress(HAMLET_SCENE) + co.flush()
@@ -1090,7 +1179,7 @@ def testEOFError(self):
self.assertRaises(EOFError, zlibd.decompress, b"")
@support.skip_if_pgo_task
- @bigmemtest(size=_4G + 100, memuse=3.3)
+ @bigmemtest(size=_4G + 100, memuse=4.5)
def testDecompress4G(self, size):
# "Test zlib._ZlibDecompressor.decompress() with >4GiB input"
blocksize = min(10 * 1024 * 1024, size)
@@ -1223,13 +1312,10 @@ def __index__(self):
class TestModule(unittest.TestCase):
- def test_deprecated__version__(self):
- with self.assertWarnsRegex(
- DeprecationWarning,
- "'__version__' is deprecated and slated for removal in Python 3.20",
- ) as cm:
- getattr(zlib, "__version__")
- self.assertEqual(cm.filename, __file__)
+ def test_deprecated_module_attributes(self):
+ support.check_deprecated_module_attributes(
+ self, zlib, "__version__", remove=(3, 20),
+ )
if __name__ == "__main__":
diff --git a/Lib/test/test_zoneinfo/test_zoneinfo.py b/Lib/test/test_zoneinfo/test_zoneinfo.py
index a10f434eb27590d..6656d7c1dc2cd67 100644
--- a/Lib/test/test_zoneinfo/test_zoneinfo.py
+++ b/Lib/test/test_zoneinfo/test_zoneinfo.py
@@ -6,16 +6,20 @@
import importlib.metadata
import io
import json
+import ntpath
import os
import pathlib
import pickle
import re
import shutil
import struct
+import sys
import tempfile
+import types
import unittest
from datetime import date, datetime, time, timedelta, timezone
from functools import cached_property
+from unittest import mock
from test.support import MISSING_C_DOCSTRINGS
from test.support.os_helper import EnvironmentVarGuard, FakePath
@@ -316,6 +320,18 @@ def test_unambiguous(self):
self.assertEqual(dt.utcoffset(), offset.utcoffset, dt)
self.assertEqual(dt.dst(), offset.dst, dt)
+ def test_datetime_subclass_negative_components(self):
+ class MinusOneDateTime(datetime):
+ hour = minute = second = -1
+
+ zi = self.zone_from_key("UTC")
+ dt = MinusOneDateTime(2024, 1, 1, tzinfo=zi)
+
+ self.assertEqual(dt.utcoffset(), ZERO)
+ self.assertEqual(dt.dst(), ZERO)
+ self.assertEqual(dt.tzname(), "UTC")
+ self.assertEqual(zi.fromutc(dt), datetime(2024, 1, 1, tzinfo=zi))
+
def test_folds_and_gaps(self):
test_cases = []
for key in self.zones():
@@ -630,6 +646,26 @@ def test_one_transition(self):
dt_utc_actual = dt_local.astimezone(timezone.utc)
self.assertEqual(dt_utc_actual, dt_utc)
+ def test_one_transition_fold(self):
+ GMT = ZoneOffset("-00", ZERO)
+ N03 = ZoneOffset("-03", -timedelta(hours=3))
+
+ transitions = [
+ ZoneTransition(datetime(1976, 12, 1), GMT, N03),
+ ]
+
+ after = "<-03>3"
+
+ zf = self.construct_zone(transitions, after)
+ zi = self.klass.from_file(zf)
+
+ dt_utc = datetime(1976, 12, 1, 1, tzinfo=timezone.utc)
+ dt_local = dt_utc.astimezone(zi)
+
+ self.assertEqual(dt_local.fold, 1)
+ self.assertEqual(dt_local.utcoffset(), N03.utcoffset)
+ self.assertEqual(dt_local.astimezone(timezone.utc), dt_utc)
+
def test_one_zone_dst(self):
DST = ZoneOffset("DST", ONE_H, ONE_H)
transitions = [
@@ -759,6 +795,34 @@ def test_invalid_transition_index(self):
with self.assertRaises(ValueError):
self.klass.from_file(f)
+ def test_invalid_charcnt(self):
+ # 128 local time types whose abbreviations are the suffixes of a
+ # single long abbreviation spanning the entire block: every index
+ # would get its own copy of most of the block.
+ types = b"".join(struct.pack(">lbb", 3600, 0, i) for i in range(128))
+ chars = b"A" * 65535 + b"\x00"
+
+ # With a negative charcnt the block would be the rest of the file
+ for charcnt in (len(chars), -1):
+ with self.subTest(charcnt=charcnt):
+ header = b"TZif" + b"\x00" * 16
+ header += struct.pack(">6l", 0, 0, 0, 0, 128, charcnt)
+ f = io.BytesIO(header + types + chars)
+
+ with self.assertRaises(ValueError):
+ self.klass.from_file(f)
+
+ def test_abbreviation_index_above_127(self):
+ chars = b"X" * 129 + b"\x00" + b"ABC\x00"
+ header = b"TZif" + b"\x00" * 16
+ header += struct.pack(">6l", 0, 0, 0, 0, 1, len(chars))
+ types = struct.pack(">lbB", 3600, 0, 130)
+ zi = self.klass.from_file(io.BytesIO(header + types + chars))
+
+ dt = datetime(2026, 1, 1, tzinfo=zi)
+ self.assertEqual(dt.tzname(), "ABC")
+ self.assertEqual(dt.utcoffset(), ONE_H)
+
def test_transition_lookahead_out_of_bounds(self):
STD = ZoneOffset("STD", ZERO)
DST = ZoneOffset("DST", ONE_H, ONE_H)
@@ -1480,6 +1544,33 @@ def _add():
(datetime(2020, 12, 31, 23, 59, 59, 999999), AAA, NORMAL),
)
+ @call
+ def _add():
+ # Julian days 58, 59 and 60 always mean February 27, February 28
+ # and March 1, including in leap years.
+ AAA = ZoneOffset("AAA", ZERO)
+ BBB = ZoneOffset("BBB", ONE_H, ONE_H)
+
+ for start, end, start_date, end_date in (
+ (58, 59, (2, 27), (2, 28)),
+ (59, 60, (2, 28), (3, 1)),
+ ):
+ tzstr = f"AAA0BBB,J{start}/12,J{end}/12"
+ cases[tzstr] = []
+ for year in (2019, 2020, 2000, 2100):
+ start_dt = datetime(year, *start_date, 12)
+ end_dt = datetime(year, *end_date, 12)
+ cases[tzstr].extend((
+ (start_dt - timedelta(seconds=1), AAA, NORMAL),
+ (start_dt, AAA, GAP),
+ (start_dt.replace(fold=1), BBB, GAP),
+ (start_dt + ONE_H, BBB, NORMAL),
+ (end_dt - ONE_H - timedelta(seconds=1), BBB, NORMAL),
+ (end_dt - ONE_H, BBB, FOLD),
+ ((end_dt - ONE_H).replace(fold=1), AAA, FOLD),
+ (end_dt, AAA, NORMAL),
+ ))
+
@call
def _add():
# Taken from America/Godthab, this rule has a transition on the
@@ -1632,6 +1723,13 @@ def __eq__(self, other):
except CustomError:
pass
+ def test_clear_cache_non_string_keys(self):
+ la0 = self.klass("America/Los_Angeles")
+ self.klass.clear_cache(only_keys=[None, 1])
+ la1 = self.klass("America/Los_Angeles")
+
+ self.assertIs(la0, la1)
+
def test_weak_cache_descriptor_use_after_free(self):
class BombDescriptor:
def __get__(self, obj, owner):
@@ -1656,6 +1754,70 @@ class EvilZoneInfo(self.klass):
class CZoneInfoCacheTest(ZoneInfoCacheTest):
module = c_zoneinfo
+ def test_strong_cache_path_like_key(self):
+ # A non-str key is matched by identity, and comparing it against a
+ # str key must not raise TypeError.
+ class Key:
+ def __fspath__(self):
+ return "UTC"
+
+ def __len__(self):
+ return 3
+
+ def split(self, sep):
+ return ["UTC"]
+
+ key = Key()
+ original = self.klass(key)
+ self.assertIs(self.klass(key), original)
+ self.assertIsNot(self.klass("UTC"), original)
+ self.klass.clear_cache(only_keys=(key,))
+ self.assertIsNot(self.klass(key), original)
+
+ def test_strong_cache_str_subclass(self):
+ class Stringy(str):
+ def __eq__(self, other):
+ raise CustomError
+
+ __hash__ = str.__hash__
+
+ for cached_type, lookup_type in ((str, Stringy), (Stringy, str),
+ (Stringy, Stringy)):
+ with self.subTest(cached_type=cached_type, lookup_type=lookup_type):
+ self.klass.clear_cache()
+ original = self.klass(cached_type("America/Los_Angeles"))
+ self.assertIs(
+ self.klass(lookup_type("America/Los_Angeles")), original
+ )
+
+ def test_strong_cache_reentrant_clear(self):
+ self._test_strong_cache_reentrant_clear("lookup")
+
+ def test_strong_cache_reentrant_clear_only_keys(self):
+ self._test_strong_cache_reentrant_clear("clear")
+
+ def _test_strong_cache_reentrant_clear(self, operation):
+ klass = self.klass
+
+ class Stringy(str):
+ cleared = False
+
+ def __eq__(self, other):
+ if not self.cleared:
+ self.cleared = True
+ klass.clear_cache(only_keys=(self,))
+ return super().__eq__(other)
+
+ __hash__ = str.__hash__
+
+ original = klass(Stringy("America/Los_Angeles"))
+ key = Stringy("America/Los_Angeles")
+ if operation == "lookup":
+ self.assertIs(klass(key), original)
+ else:
+ klass.clear_cache(only_keys=(key,))
+ self.assertIsNot(klass("America/Los_Angeles"), original)
+
def test_inconsistent_weak_cache_get(self):
class Cache:
def get(self, key, default=None):
@@ -1957,6 +2119,38 @@ def test_tzpath_type_error(self):
with self.assertRaises(TypeError):
self.module.reset_tzpath(bad_value)
+ def test_validate_key_windows_paths(self):
+ # Check the key validation with Windows path rules on every platform.
+ tzpath = self.module._tzpath
+ base = ntpath.normpath(ntpath.join("_", "_"))[:-1]
+ fake_os = types.SimpleNamespace(path=ntpath)
+
+ good_keys = [
+ "UTC",
+ "America/New_York",
+ "America/Argentina/Buenos_Aires",
+ "Etc/GMT+1",
+ ]
+ bad_keys = [
+ "C:\\Windows\\win.ini",
+ "America/C:\\Windows\\win.ini", # Drive in a component
+ "America/C:/Windows/win.ini",
+ "America/D:secret", # Drive-relative component
+ "America/Argentina/D:secret",
+ "America/\\Windows\\win.ini", # Rooted component
+ "America/\\\\server\\share\\file", # UNC component
+ ]
+
+ with mock.patch.object(tzpath, "os", fake_os):
+ for key in good_keys:
+ with self.subTest(key=key):
+ tzpath._validate_tzfile_path(key, _base=base)
+
+ for key in bad_keys:
+ with self.subTest(key=key):
+ with self.assertRaises(ValueError):
+ tzpath._validate_tzfile_path(key, _base=base)
+
def test_tzpath_attribute(self):
tzpath_0 = [f"{DRIVE}/one", f"{DRIVE}/two"]
tzpath_1 = [f"{DRIVE}/three"]
@@ -2142,6 +2336,8 @@ def test_pydatetime(self):
PYTHONTZPATH=str(ZONEINFO_DATA.tzpath))
+@unittest.skipIf(sys.modules.get("_zoneinfo") is None,
+ "_zoneinfo C module not available")
class ExtensionBuiltTest(unittest.TestCase):
"""Smoke test to ensure that the C and Python extensions are both tested.
diff --git a/Lib/test/test_zstd.py b/Lib/test/test_zstd.py
index 9225c42e0e711aa..0763ba31737a4ca 100644
--- a/Lib/test/test_zstd.py
+++ b/Lib/test/test_zstd.py
@@ -7,9 +7,12 @@
import os
import unittest
import tempfile
+import textwrap
import threading
+from test import support
from test.support.import_helper import import_module
+from test.support.script_helper import assert_python_ok
from test.support import threading_helper
from test.support import _1M
@@ -24,8 +27,6 @@
ZstdDecompressor,
ZstdDict,
ZstdError,
- zstd_version,
- zstd_version_info,
COMPRESSION_LEVEL_DEFAULT,
get_frame_info,
get_frame_size,
@@ -133,9 +134,33 @@ def setUpModule():
class FunctionsTestCase(unittest.TestCase):
- def test_version(self):
- s = ".".join((str(i) for i in zstd_version_info))
- self.assertEqual(s, zstd_version)
+ def _test_zstd_version(self, v, string):
+ self.assertIsInstance(v[:], tuple)
+ self.assertEqual(len(v), 3)
+ self.assertIsInstance(v[0], int)
+ self.assertIsInstance(v[1], int)
+ self.assertIsInstance(v[2], int)
+ self.assertIsInstance(v.major, int)
+ self.assertIsInstance(v.minor, int)
+ self.assertIsInstance(v.patch, int)
+ self.assertEqual(v[0], v.major)
+ self.assertEqual(v[1], v.minor)
+ self.assertEqual(v[2], v.patch)
+ self.assertGreaterEqual(v.major, 0)
+ self.assertGreaterEqual(v.minor, 0)
+ self.assertGreaterEqual(v.patch, 0)
+
+ self.assertEqual(string, '%d.%d.%d' % v)
+
+ def test_zstd_version(self):
+ if support.verbose:
+ print(f'ZSTD_VERSION = {zstd.ZSTD_VERSION}', flush=True)
+ print(f'zstd_version = {zstd.zstd_version}', flush=True)
+ print(f'ZSTD_VERSION_INFO = {zstd.ZSTD_VERSION_INFO}', flush=True)
+ print(f'zstd_version_info = {zstd.zstd_version_info}', flush=True)
+ self._test_zstd_version(zstd.ZSTD_VERSION_INFO, zstd.ZSTD_VERSION)
+ self._test_zstd_version(zstd.zstd_version_info, zstd.zstd_version)
+ self.assertEqual(zstd.ZSTD_VERSION_INFO[0], zstd.zstd_version_info[0])
def test_compressionLevel_values(self):
min, max = CompressionParameter.compression_level.bounds()
@@ -188,6 +213,52 @@ def test_decompress_2x130_1K(self):
dat = decompress(DAT_130K_C + DAT_130K_C)
self.assertEqual(len(dat), 2 * _130_1K)
+ def test_decompress_multi_frames(self):
+ big = random.randbytes(100_000)
+ frames = [b"a" * 100, b"", big, b"b" * 100, big]
+ expected = b"".join(frames)
+ dat = b"".join(map(compress, frames))
+ self.assertEqual(decompress(dat), expected)
+ self.assertEqual(decompress(bytearray(dat)), expected)
+ self.assertEqual(decompress(memoryview(dat)), expected)
+ with self.assertRaisesRegex(ZstdError, "Compressed data ended before"):
+ decompress(dat[:-50_000])
+ with self.assertRaisesRegex(ZstdError, "Unknown frame descriptor"):
+ decompress(dat + b"junk")
+
+ def test_decompress_error_releases_buffer(self):
+ # The argument can be resized while the exception is handled.
+ for dat in COMPRESSED_100_PLUS_32KB[:-10], b"junk" * 10:
+ with self.subTest(dat=dat[:10]):
+ dat = bytearray(dat)
+ try:
+ decompress(dat)
+ except ZstdError:
+ dat += b"more"
+ else:
+ self.fail("no exception")
+
+ def test_decompress_many_frames(self):
+ # The amount of data passed to the decompressors should grow
+ # linearly with the number of frames.
+ class Decompressor:
+ def __init__(self, *args, **kwargs):
+ self.decomp = ZstdDecompressor(*args, **kwargs)
+ def __getattr__(self, name):
+ return getattr(self.decomp, name)
+ def decompress(self, data):
+ nonlocal fed
+ fed += len(data)
+ return self.decomp.decompress(data)
+ dat = compress(b"")
+ with support.swap_attr(zstd, "ZstdDecompressor", Decompressor):
+ fed = 0
+ self.assertEqual(decompress(dat * 1000), b"")
+ fed1 = fed
+ fed = 0
+ self.assertEqual(decompress(dat * 2000), b"")
+ self.assertLess(fed, fed1 * 3)
+
class CompressorTestCase(unittest.TestCase):
@@ -346,6 +417,58 @@ def test_zstd_multithread_compress(self):
with ZstdFile(io.BytesIO(), 'w', options=options) as f:
f.write(b)
+ @unittest.skipIf(not SUPPORT_MULTITHREADING,
+ "zstd build doesn't support multi-threaded compression")
+ def test_free_busy_multithread_compressor_with_dict(self):
+ # A compressor can be freed while a worker thread is still
+ # compressing with a dictionary that the compression context owns.
+ # Whether a failure is detected depends on the memory allocator,
+ # so use a fresh process for each case.
+ code = textwrap.dedent("""
+ import gc, random, sys
+ from compression.zstd import (CompressionParameter,
+ ZstdCompressor, ZstdDict)
+
+ job_size = 1 << 20
+ zd = ZstdDict(random.randbytes(1 << 10) * (1 << 10), is_raw=True)
+ options = {CompressionParameter.compression_level: 10,
+ CompressionParameter.nb_workers: 1,
+ CompressionParameter.job_size: job_size}
+ c = ZstdCompressor(options=options, zstd_dict=zd)
+ # Returns while the worker thread is compressing the first job.
+ c.compress(random.randbytes(1 << 10) * ((job_size >> 10) + 64))
+ if sys.argv[1] == 'error':
+ # A failed call does not wait for the worker thread either.
+ import _testcapi
+ _testcapi.set_nomemory(0)
+ try:
+ c.compress(b'x')
+ except MemoryError:
+ pass
+ finally:
+ _testcapi.remove_mem_hooks()
+ if sys.argv[1] == 'gc':
+ # The garbage collector clears the compressor before
+ # deallocating it.
+ cycle = [c]
+ cycle.append(cycle)
+ del c, cycle
+ gc.collect()
+ elif sys.argv[1] != 'exit':
+ del c
+ # Otherwise the compressor is freed at interpreter exit.
+ """)
+ cases = ['del', 'gc', 'exit']
+ try:
+ import _testcapi # noqa: F401
+ except ImportError:
+ pass
+ else:
+ cases.append('error')
+ for case in cases:
+ with self.subTest(case=case):
+ assert_python_ok('-c', code, case)
+
def test_compress_flushblock(self):
point = len(THIS_FILE_BYTES) // 2
@@ -1548,6 +1671,42 @@ def test_len(self):
self.assertEqual(len(TRAINED_DICT), len(TRAINED_DICT.dict_content))
self.assertIn(str(len(TRAINED_DICT)), str(TRAINED_DICT))
+ @unittest.skipUnless(SUPPORT_MULTITHREADING,
+ "zstd build doesn't support multi-threaded compression")
+ @support.requires_subprocess()
+ def test_collect_cycle_with_busy_compressor(self):
+ # The dictionary must outlive the compression context when both are
+ # collected by the garbage collector while a worker thread is still
+ # using the dictionary. Whether the failure is detected depends on
+ # the memory allocator, so use a fresh process for each case.
+ code = textwrap.dedent("""
+ import gc, random, sys
+ from compression.zstd import (CompressionParameter,
+ ZstdCompressor, ZstdDict)
+
+ class Cycle:
+ pass
+
+ job_size = 1 << 20
+ content = random.randbytes(1 << 10) * (1 << 8)
+ zd = ZstdDict(content, is_raw=True)
+ options = {CompressionParameter.compression_level: 10,
+ CompressionParameter.nb_workers: 1,
+ CompressionParameter.job_size: job_size}
+ c = ZstdCompressor(options=options,
+ zstd_dict=getattr(zd, sys.argv[1]))
+ cycle = Cycle()
+ cycle.cycle = cycle
+ cycle.compressor = c
+ # Returns while the worker thread is compressing the first job.
+ c.compress(random.randbytes(1 << 10) * ((job_size >> 10) + 64))
+ del zd, c, cycle
+ gc.collect()
+ """)
+ for attr in 'as_digested_dict', 'as_prefix':
+ with self.subTest(attr=attr):
+ assert_python_ok('-c', code, attr)
+
class FileTestCase(unittest.TestCase):
def setUp(self):
self.DECOMPRESSED_42 = b'a'*42
diff --git a/Lib/test/translationdata/argparse/msgids.txt b/Lib/test/translationdata/argparse/msgids.txt
index ae89ac74726ecfc..8a2305b89a56672 100644
--- a/Lib/test/translationdata/argparse/msgids.txt
+++ b/Lib/test/translationdata/argparse/msgids.txt
@@ -18,7 +18,7 @@ invalid %(type)s value: %(value)r
invalid choice: %(value)r (choose from %(choices)s)
invalid choice: %(value)r, maybe you meant %(closest)r? (choose from %(choices)s)
not allowed with argument %s
-one of the arguments %s is required
+one of the following arguments is required: %s
option '%(option)s' is deprecated
options
positional arguments
diff --git a/Lib/test/wheeldata/setuptools-79.0.1-py3-none-any.whl b/Lib/test/wheeldata/setuptools-79.0.1-py3-none-any.whl
deleted file mode 100644
index 3eb896915897fb7..000000000000000
Binary files a/Lib/test/wheeldata/setuptools-79.0.1-py3-none-any.whl and /dev/null differ
diff --git a/Lib/test/wheeldata/setuptools-84.2.1-py3-none-any.whl b/Lib/test/wheeldata/setuptools-84.2.1-py3-none-any.whl
new file mode 100644
index 000000000000000..f708be8904f2d5e
Binary files /dev/null and b/Lib/test/wheeldata/setuptools-84.2.1-py3-none-any.whl differ
diff --git a/Lib/test/win_console_handler.py b/Lib/test/win_console_handler.py
index e7779b9363503b4..a1c7c42c109330b 100644
--- a/Lib/test/win_console_handler.py
+++ b/Lib/test/win_console_handler.py
@@ -15,7 +15,7 @@
import sys
# Function prototype for the handler function. Returns BOOL, takes a DWORD.
-HandlerRoutine = WINFUNCTYPE(wintypes.BOOL, wintypes.DWORD)
+HANDLER_ROUTINE = WINFUNCTYPE(wintypes.BOOL, wintypes.DWORD)
def _ctrl_handler(sig):
"""Handle a sig event and return 0 to terminate the process"""
@@ -27,12 +27,13 @@ def _ctrl_handler(sig):
print("UNKNOWN EVENT")
return 0
-ctrl_handler = HandlerRoutine(_ctrl_handler)
+ctrl_handler = HANDLER_ROUTINE(_ctrl_handler)
-SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler
-SetConsoleCtrlHandler.argtypes = (HandlerRoutine, wintypes.BOOL)
-SetConsoleCtrlHandler.restype = wintypes.BOOL
+@ctypes.util.wrap_dll_function(ctypes.windll.kernel32)
+def SetConsoleCtrlHandler(HandlerRoutine: HANDLER_ROUTINE,
+ Add: wintypes.BOOL) -> wintypes.BOOL:
+ pass
if __name__ == "__main__":
# Add our console control handling function with value 1
diff --git a/Lib/threading.py b/Lib/threading.py
index abac31e25886fae..507d40a1baa275f 100644
--- a/Lib/threading.py
+++ b/Lib/threading.py
@@ -363,10 +363,11 @@ def wait(self, timeout=None):
waiter.acquire()
gotit = True
else:
- if timeout > 0:
- gotit = waiter.acquire(True, timeout)
- else:
+ if timeout <= 0:
gotit = waiter.acquire(False)
+ else:
+ # A NaN timeout is rejected by acquire().
+ gotit = waiter.acquire(True, timeout)
return gotit
finally:
self._acquire_restore(saved_state)
diff --git a/Lib/tkinter/__init__.py b/Lib/tkinter/__init__.py
index dde4accecf61ba4..8147b2898139710 100644
--- a/Lib/tkinter/__init__.py
+++ b/Lib/tkinter/__init__.py
@@ -170,6 +170,9 @@ def _parse_version(version):
releaselevel = {'a': 'alpha', 'b': 'beta'}[releaselevel]
return _VersionInfoType(major, minor, micro, releaselevel, serial)
+TCL_VERSION_INFO = _parse_version(_tkinter.TCL_PATCH_LEVEL)
+TK_VERSION_INFO = _parse_version(_tkinter.TK_PATCH_LEVEL)
+
@enum._simple_enum(enum.StrEnum)
class EventType:
@@ -818,6 +821,25 @@ def tk_inactive(self, reset=False, *, displayof=0):
else:
return self.tk.getint(self.tk.call(args))
+ def tk_check_screenreader(self):
+ """Return whether a screen reader is currently running.
+
+ Requires Tk 9.1 or newer."""
+ return self.tk.getboolean(self.tk.call(
+ 'tk', 'accessible', 'check_screenreader'))
+
+ @property
+ def accessible(self):
+ """The accessible attributes of the widget, as an Accessible
+ object.
+
+ Requires Tk 9.1 or newer."""
+ try:
+ return self._accessible_object
+ except AttributeError:
+ self._accessible_object = Accessible(self)
+ return self._accessible_object
+
def wait_variable(self, name):
"""Wait until the variable is modified.
@@ -2307,6 +2329,68 @@ def yview_scroll(self, number, what):
self.tk.call(self._w, 'yview', 'scroll', number, what)
+def _accessible_attribute(name):
+ """Internal function. Create an Accessible attribute property."""
+ def getter(self):
+ widget = self._widget
+ return widget.tk.call('tk', 'accessible', 'get_acc_' + name,
+ widget._w)
+ def setter(self, value):
+ widget = self._widget
+ widget.tk.call('tk', 'accessible', 'set_acc_' + name,
+ widget._w, value)
+ return property(getter, setter,
+ doc=f'The accessible {name} of the widget.')
+
+
+class Accessible:
+ """The accessible attributes of a widget.
+
+ Returned by the accessible property of a widget. The attributes
+ are exposed to assistive technologies such as screen readers.
+ Requires Tk 9.1 or newer.
+
+ If no assistive technology is active when the application starts,
+ setting an attribute has no effect and reading it returns 0.
+ Reading an attribute that has not been set raises TclError.
+ A widget must have a role before other attributes can be used.
+ """
+
+ def __init__(self, widget):
+ self._widget = widget
+
+ def __repr__(self):
+ return f''
+
+ role = _accessible_attribute('role')
+ name = _accessible_attribute('name')
+ description = _accessible_attribute('description')
+ value = _accessible_attribute('value')
+ state = _accessible_attribute('state')
+ action = _accessible_attribute('action')
+ help = _accessible_attribute('help')
+
+ def add_object(self):
+ """Register the widget with the platform accessibility API."""
+ widget = self._widget
+ widget.tk.call('tk', 'accessible', 'add_acc_object', widget._w)
+
+ def emit_selection_change(self):
+ """Notify the platform accessibility API that the selection
+ in the widget has changed."""
+ widget = self._widget
+ widget.tk.call('tk', 'accessible', 'emit_selection_change',
+ widget._w)
+
+ def emit_focus_change(self):
+ """Notify the platform accessibility API that the widget has
+ received focus.
+
+ Not available on macOS."""
+ widget = self._widget
+ widget.tk.call('tk', 'accessible', 'emit_focus_change', widget._w)
+
+
class Wm:
"""Provides functions for the communication with the window manager."""
@@ -2352,7 +2436,7 @@ def wm_attributes(self, *args, return_python_dict=False, **kwargs):
# TODO: deprecate
return self.tk.call('wm', 'attributes', self._w, *args)
elif args:
- raise TypeError('wm_attribute() options have been specified as '
+ raise TypeError('wm_attributes() options have been specified as '
'positional and keyword arguments')
else:
self.tk.call('wm', 'attributes', self._w, *self._options(kwargs))
diff --git a/Lib/tkinter/constants.py b/Lib/tkinter/constants.py
index 63eee33d24d6c7e..dcc326673b51744 100644
--- a/Lib/tkinter/constants.py
+++ b/Lib/tkinter/constants.py
@@ -18,6 +18,16 @@
NSEW='nsew'
CENTER='center'
+# -labelanchor, in addition to the values above
+EN='en'
+ES='es'
+WN='wn'
+WS='ws'
+
+# -compound
+TEXT='text'
+IMAGE='image'
+
# -fill
NONE='none'
X='x'
@@ -54,8 +64,38 @@
# -bordermode
INSIDE='inside'
+IGNORE='ignore'
OUTSIDE='outside'
+# -direction
+ABOVE='above'
+BELOW='below'
+FLUSH='flush'
+
+# -stretch
+ALWAYS='always'
+MIDDLE='middle'
+NEVER='never'
+
+# -tabstyle
+TABULAR='tabular'
+WORDPROCESSOR='wordprocessor'
+
+# -insertunfocussed (Tk 8.6+)
+HOLLOW='hollow'
+
+# -mode
+DETERMINATE='determinate'
+INDETERMINATE='indeterminate'
+
+# -selecttype (Tk 9.0+)
+ITEM='item'
+CELL='cell'
+
+# -show
+TREE='tree'
+HEADINGS='headings'
+
# Special tags, marks and insert positions
SEL='sel'
SEL_FIRST='sel.first'
@@ -72,6 +112,29 @@
ACTIVE='active'
# Canvas state
HIDDEN='hidden'
+# Entry and ttk widget states
+READONLY='readonly'
+# Other ttk widget states
+ALTERNATE='alternate'
+BACKGROUND='background'
+FOCUS='focus'
+HOVER='hover'
+INVALID='invalid'
+PRESSED='pressed'
+SELECTED='selected'
+# ttk widget states for Treeview items and Notebook tabs (Tk 9.1+)
+# FIRST='first' and LAST='last' are also used
+LEAF='leaf'
+OPEN='open'
+
+# -validate
+# ALL='all', FOCUS='focus' and NONE='none' are also valid
+KEY='key'
+FOCUSIN='focusin'
+FOCUSOUT='focusout'
+
+# Validation reasons, in addition to the values above
+FORCED='forced'
# Menu item types
CASCADE='cascade'
@@ -80,6 +143,10 @@
RADIOBUTTON='radiobutton'
SEPARATOR='separator'
+# -type for menus
+MENUBAR='menubar'
+TEAROFF='tearoff'
+
# Selection modes for list boxes
SINGLE='single'
BROWSE='browse'
@@ -108,3 +175,4 @@
SCROLL='scroll'
UNITS='units'
PAGES='pages'
+PIXELS='pixels'
diff --git a/Lib/tkinter/font.py b/Lib/tkinter/font.py
index 5b663a4e456456b..1349e49fbd68a5b 100644
--- a/Lib/tkinter/font.py
+++ b/Lib/tkinter/font.py
@@ -104,7 +104,8 @@ def __init__(self, root=None, font=None, name=None, exists=False,
if exists:
self.name = name
# confirm font exists
- if self.name not in tk.splitlist(tk.call("font", "names")):
+ name = getattr(name, 'string', name) # can be a Tcl object
+ if name not in tk.splitlist(tk.call("font", "names")):
raise tkinter._tkinter.TclError(
"named font %s does not already exist" % (self.name,))
# if font config info supplied, apply it
@@ -123,11 +124,11 @@ def __init__(self, root=None, font=None, name=None, exists=False,
self._call = tk.call
def __str__(self):
- # A wrapped description is a list or tuple, not a string; format it as
- # a Tcl word so it can be used as an option value (as ttk does).
- if isinstance(self.name, str):
- return self.name
- return tkinter._join(self.name)
+ # A wrapped description can be a list or tuple; format it as a Tcl
+ # word so it can be used as an option value (as ttk does).
+ if isinstance(self.name, (list, tuple)):
+ return tkinter._join(self.name)
+ return str(self.name)
def __repr__(self):
return f"<{self.__class__.__module__}.{self.__class__.__qualname__}" \
@@ -136,7 +137,13 @@ def __repr__(self):
def __eq__(self, other):
if not isinstance(other, Font):
return NotImplemented
- return self.name == other.name and self._tk == other._tk
+ name = self.name
+ other_name = other.name
+ if type(name) is not type(other_name):
+ # A Tcl object does not compare equal to a string.
+ name = getattr(name, 'string', name)
+ other_name = getattr(other_name, 'string', other_name)
+ return name == other_name and self._tk == other._tk
def __getitem__(self, key):
return self.cget(key)
diff --git a/Lib/tkinter/simpledialog.py b/Lib/tkinter/simpledialog.py
index 1b0cf51317ee082..caef785f936db36 100644
--- a/Lib/tkinter/simpledialog.py
+++ b/Lib/tkinter/simpledialog.py
@@ -722,12 +722,13 @@ def askstring(title, prompt, **kw):
@contextlib.contextmanager
def _temp_grab_focus(grab, focus=None, destroy=True):
- old_focus = grab.focus_get()
- old_grab = grab.grab_current()
- if old_grab is not None and old_grab.winfo_exists():
- old_status = old_grab.grab_status()
- else:
- old_status = None
+ # Use Tcl window names rather than widgets, because the focus and the
+ # grab can be in a window which was not created by tkinter, such as
+ # a native message box.
+ tk = grab.tk
+ old_focus = tk.call('focus')
+ old_grab = tk.call('grab', 'current', grab._w)
+ old_status = tk.call('grab', 'status', old_grab) if old_grab else None
# The "grab" command will fail if another application
# already holds the grab. So catch it.
try:
@@ -741,9 +742,11 @@ def _temp_grab_focus(grab, focus=None, destroy=True):
yield
finally:
- if old_focus is not None:
+ # The old windows and even the whole application can be destroyed
+ # by now, so catch errors.
+ if old_focus:
try:
- old_focus.focus_set()
+ tk.call('focus', old_focus)
except TclError:
pass
try:
@@ -755,15 +758,17 @@ def _temp_grab_focus(grab, focus=None, destroy=True):
grab.destroy()
except TclError:
pass
- if (old_grab is not None and old_grab.winfo_exists()
- and old_grab.winfo_ismapped()):
- # The "grab" command will fail if another application
- # already holds the grab. So catch it.
+ if old_grab:
+ # Do not restore the grab if the window is no longer mapped:
+ # a local grab on an unmapped window would block the application.
+ # The "grab" command will fail if another application already
+ # holds the grab on a window with the same name. So catch it.
try:
- if old_status == 'global':
- old_grab.grab_set_global()
- else:
- old_grab.grab_set()
+ if grab.getboolean(tk.call('winfo', 'ismapped', old_grab)):
+ if old_status == 'global':
+ tk.call('grab', 'set', '-global', old_grab)
+ else:
+ tk.call('grab', 'set', old_grab)
except TclError:
pass
diff --git a/Lib/tkinter/ttk.py b/Lib/tkinter/ttk.py
index 57953d90b672a2c..73d2b63ad445f87 100644
--- a/Lib/tkinter/ttk.py
+++ b/Lib/tkinter/ttk.py
@@ -12,7 +12,7 @@
of the widgets appearance lies at Themes.
"""
-__author__ = "Guilherme Polo "
+# Original author: Guilherme Polo
__all__ = ["Button", "Checkbutton", "Combobox", "Entry", "Frame", "Label",
"Labelframe", "LabelFrame", "Menubutton", "Notebook", "Panedwindow",
@@ -24,6 +24,7 @@
"tclobjs_to_py", "setup_master"]
import tkinter
+lazy import warnings
from tkinter import _flatten, _join, _stringify, _splitdict
@@ -2210,9 +2211,10 @@ def destroy(self):
def __getattr__(name):
- if name == "__version__":
- from warnings import _deprecated
-
- _deprecated("__version__", remove=(3, 20))
- return "0.3.1" # Do not change
+ if name in ("__version__", "__author__"):
+ warnings._deprecated(name, remove=(3, 20))
+ return { # Do not change
+ "__version__": "0.3.1",
+ "__author__": "Guilherme Polo ",
+ }[name]
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
diff --git a/Lib/tokenize.py b/Lib/tokenize.py
index 3545d92c4f5d7ff..3cde65d0a707ae9 100644
--- a/Lib/tokenize.py
+++ b/Lib/tokenize.py
@@ -20,10 +20,10 @@
which tells you which encoding was used to decode the bytes stream.
"""
-__author__ = 'Ka-Ping Yee '
-__credits__ = ('GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, '
- 'Skip Montanaro, Raymond Hettinger, Trent Nelson, '
- 'Michael Foord')
+# Original author: Ka-Ping Yee
+# Credits: ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro,
+# Raymond Hettinger, Trent Nelson, Michael Foord
+
from builtins import open as _builtin_open
from codecs import lookup, BOM_UTF8
import collections
@@ -36,6 +36,7 @@
from token import EXACT_TOKEN_TYPES
import _tokenize
lazy import _colorize
+lazy import warnings
cookie_re = re.compile(br'^[ \t\f]*#.*?coding[:=][ \t]*([-\w.]+)', re.ASCII)
blank_re = re.compile(br'^[ \t\f]*(?:[#\r\n]|$)', re.ASCII)
@@ -640,5 +641,17 @@ def _generate_tokens_from_c_tokenizer(source, encoding=None, extra_tokens=False)
raise TokenError(msg, (e.lineno, e.offset)) from None
+def __getattr__(name):
+ if name in ("__author__", "__credits__"):
+ warnings._deprecated(name, remove=(3, 20))
+ return { # Do not change
+ "__author__": 'Ka-Ping Yee',
+ "__credits__": ('GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, '
+ 'Skip Montanaro, Raymond Hettinger, Trent Nelson, '
+ 'Michael Foord'),
+ }[name]
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+
+
if __name__ == "__main__":
_main()
diff --git a/Lib/trace.py b/Lib/trace.py
index 43ec201c4696d1d..66471f45e1c0040 100644
--- a/Lib/trace.py
+++ b/Lib/trace.py
@@ -287,8 +287,11 @@ def write_results(self, show_missing=True, summary=False, coverdir=None, *,
n_lines, n_hits, modulename, filename = sums[m]
print(f"{n_lines:5d} {n_hits/n_lines:.1%} {modulename} ({filename})")
+ self._save_counts()
+
+ def _save_counts(self):
+ """Save the accumulated counts to ``self.outfile`` if one was given."""
if self.outfile:
- # try and store counts and module info into self.outfile
try:
with open(self.outfile, 'wb') as f:
pickle.dump((self.counts, self.calledfuncs, self.callers),
@@ -744,6 +747,8 @@ def parse_ignore_dir(s):
if not opts.no_report:
results.write_results(opts.missing, opts.summary, opts.coverdir)
+ else:
+ results._save_counts()
if __name__=='__main__':
main()
diff --git a/Lib/traceback.py b/Lib/traceback.py
index dcdab1f12e9a168..3ecb1dd318fbcb7 100644
--- a/Lib/traceback.py
+++ b/Lib/traceback.py
@@ -1611,7 +1611,11 @@ def _format_syntax_error(self, stype, **kwargs):
)
else:
yield ' {}\n'.format(ltext)
- msg = self.msg or ""
+ try:
+ if not (msg := self.msg):
+ msg = ""
+ except TypeError:
+ pass
yield "{}{}{}: {}{}{}{}\n".format(
theme.type,
stype,
@@ -1954,31 +1958,34 @@ def _compute_suggestion_error(exc_value, tb, wrong_name):
return None
else:
assert isinstance(exc_value, NameError)
- # find most recent frame
- if tb is None:
+ try:
+ # find most recent frame
+ if tb is None:
+ return None
+ while tb.tb_next is not None:
+ tb = tb.tb_next
+ frame = tb.tb_frame
+ d = (
+ list(frame.f_locals)
+ + list(frame.f_globals)
+ + list(frame.f_builtins)
+ )
+ d = [x for x in d if isinstance(x, str)]
+ if not_normalized and wrong_name in d:
+ return wrong_name
+
+ # Check first if we are in a method and the instance
+ # has the wrong name as attribute
+ if 'self' in frame.f_locals:
+ self = frame.f_locals['self']
+ try:
+ has_wrong_name = hasattr(self, wrong_name)
+ except Exception:
+ has_wrong_name = False
+ if has_wrong_name:
+ return f"self.{wrong_name}"
+ except Exception:
return None
- while tb.tb_next is not None:
- tb = tb.tb_next
- frame = tb.tb_frame
- d = (
- list(frame.f_locals)
- + list(frame.f_globals)
- + list(frame.f_builtins)
- )
- d = [x for x in d if isinstance(x, str)]
- if not_normalized and wrong_name in d:
- return wrong_name
-
- # Check first if we are in a method and the instance
- # has the wrong name as attribute
- if 'self' in frame.f_locals:
- self = frame.f_locals['self']
- try:
- has_wrong_name = hasattr(self, wrong_name)
- except Exception:
- has_wrong_name = False
- if has_wrong_name:
- return f"self.{wrong_name}"
if not_normalized and wrong_name in d:
return wrong_name
diff --git a/Lib/tracemalloc.py b/Lib/tracemalloc.py
index cec99c59700fe05..426981ebe97b4de 100644
--- a/Lib/tracemalloc.py
+++ b/Lib/tracemalloc.py
@@ -119,6 +119,7 @@ def _sort_key(self):
def _compare_grouped_stats(old_group, new_group):
statistics = []
+ old_group = dict(old_group)
for traceback, stat in new_group.items():
previous = old_group.pop(traceback, None)
if previous is not None:
@@ -478,7 +479,7 @@ def _group_by(self, key_type, cumulative):
if key_type not in ('traceback', 'filename', 'lineno'):
raise ValueError("unknown key_type: %r" % (key_type,))
if cumulative and key_type not in ('lineno', 'filename'):
- raise ValueError("cumulative mode cannot by used "
+ raise ValueError("cumulative mode cannot be used "
"with key type %r" % key_type)
stats = {}
diff --git a/Lib/turtle.py b/Lib/turtle.py
index af2c7448a0af17f..a060d3aa651013b 100644
--- a/Lib/turtle.py
+++ b/Lib/turtle.py
@@ -1,4 +1,3 @@
-#
# turtle.py: a Tkinter based turtle graphics module for Python
# Version 1.1b - 4. 5. 2009
#
@@ -22,80 +21,17 @@
# 3. This notice may not be removed or altered from any source distribution.
"""
-Turtle graphics is a popular way for introducing programming to
-kids. It was part of the original Logo programming language developed
-by Wally Feurzig and Seymour Papert in 1966.
-
-Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an ``import turtle``, give it
-the command turtle.forward(15), and it moves (on-screen!) 15 pixels in
-the direction it is facing, drawing a line as it moves. Give it the
-command turtle.right(25), and it rotates in-place 25 degrees clockwise.
-
-By combining together these and similar commands, intricate shapes and
-pictures can easily be drawn.
-
------ turtle.py
-
-This module is an extended reimplementation of turtle.py from the
-Python standard distribution up to Python 2.5. (See: https://www.python.org)
-
-It tries to keep the merits of turtle.py and to be (nearly) 100%
-compatible with it. This means in the first place to enable the
-learning programmer to use all the commands, classes and methods
-interactively when using the module from within IDLE run with
-the -n switch.
-
-Roughly it has the following features added:
-
-- Better animation of the turtle movements, especially of turning the
- turtle. So the turtles can more easily be used as a visual feedback
- instrument by the (beginning) programmer.
-
-- Different turtle shapes, image files as turtle shapes, user defined
- and user controllable turtle shapes, among them compound
- (multicolored) shapes. Turtle shapes can be stretched and tilted, which
- makes turtles very versatile geometrical objects.
-
-- Fine control over turtle movement and screen updates via delay(),
- and enhanced tracer() and speed() methods.
-
-- Aliases for the most commonly used commands, like fd for forward etc.,
- following the early Logo traditions. This reduces the boring work of
- typing long sequences of commands, which often occur in a natural way
- when kids try to program fancy pictures on their first encounter with
- turtle graphics.
-
-- Turtles now have an undo()-method with configurable undo-buffer.
-
-- Some simple commands/methods for creating event driven programs
- (mouse-, key-, timer-events). Especially useful for programming games.
-
-- A scrollable Canvas class. The default scrollable Canvas can be
- extended interactively as needed while playing around with the turtle(s).
-
-- A TurtleScreen class with methods controlling background color or
- background image, window and canvas size and other properties of the
- TurtleScreen.
-
-- There is a method, setworldcoordinates(), to install a user defined
- coordinate-system for the TurtleScreen.
-
-- The implementation uses a 2-vector class named Vec2D, derived from tuple.
- This class is public, so it can be imported by the application programmer,
- which makes certain types of computations very natural and compact.
-
-- Appearance of the TurtleScreen and the Turtles at startup/import can be
- configured by means of a turtle.cfg configuration file.
- The default configuration mimics the appearance of the old turtle module.
-
-- If configured appropriately the module reads in docstrings from a docstring
- dictionary in some different language, supplied separately and replaces
- the English ones by those read in. There is a utility function
- write_docstringdict() to write a dictionary with the original (English)
- docstrings to disc, so it can serve as a template for translations.
-
-Behind the scenes there are some features included with possible
-extensions in mind. These will be commented and documented elsewhere.
+Imagine a robotic turtle starting at (0, 0) in the x-y plane.
+After an `import turtle`, give it the command `turtle.forward(15)`, and it
+moves (on-screen!) 15 pixels in the direction it is facing, drawing a line as
+it moves. Give it the command `turtle.right(25)`, and it rotates in-place 25
+degrees clockwise.
+
+Turtle graphics is an implementation of the drawing tools introduced in Logo
+in 1967. It was created as an educational tool, and its instant, visible
+feedback makes it an effective way for learners to encounter programming
+concepts. It is also a convenient way to produce simple graphical output
+without bringing in external libraries.
"""
import tkinter as TK
@@ -105,6 +41,7 @@
import inspect
import sys
+from os import environ
from os.path import isfile, split, join
from pathlib import Path
from contextlib import contextmanager
@@ -166,7 +103,7 @@
}
def config_dict(filename):
- """Convert content of config-file into dictionary."""
+ """Convert the content of a config file into a dict."""
with open(filename, "r") as f:
cfglines = f.readlines()
cfgdict = {}
@@ -177,7 +114,7 @@ def config_dict(filename):
try:
key, value = line.split("=")
except ValueError:
- print("Bad line in config-file %s:\n%s" % (filename,line))
+ print(f"Bad line in config-file {filename}:\n{line}")
continue
key = key.strip()
value = value.strip()
@@ -195,17 +132,17 @@ def config_dict(filename):
return cfgdict
def readconfig(cfgdict):
- """Read config-files, change configuration-dict accordingly.
+ """Read config files and update the configuration dict accordingly.
If there is a turtle.cfg file in the current working directory,
- read it from there. If this contains an importconfig-value,
- say 'myway', construct filename turtle_mayway.cfg else use
- turtle.cfg and read it from the import-directory, where
- turtle.py is located.
- Update configuration dictionary first according to config-file,
- in the import directory, then according to config-file in the
- current working directory.
- If no config-file is found, the default configuration is used.
+ read it. If it contains an importconfig value, say 'myway',
+ use the filename turtle_myway.cfg, otherwise turtle.cfg, and
+ read that file from the directory where turtle.py is located.
+
+ The configuration dict is updated first from the config file in
+ the turtle.py directory, then from the one in the current working
+ directory. If no config file is found, the default configuration
+ is used.
"""
default_cfg = "turtle.cfg"
cfgdict1 = {}
@@ -231,46 +168,54 @@ def readconfig(cfgdict):
class Vec2D(tuple):
- """A 2 dimensional vector class, used as a helper class
- for implementing turtle graphics.
- May be useful for turtle graphics programs also.
- Derived from tuple, so a vector is a tuple!
+ """A two-dimensional vector class, used as a helper class for
+ implementing turtle graphics. May be useful for turtle graphics
+ programs too. Derived from tuple, so a vector is a tuple!
Provides (for a, b vectors, k number):
- a+b vector addition
- a-b vector subtraction
- a*b inner product
- k*a and a*k multiplication with scalar
- |a| absolute value of a
- a.rotate(angle) rotation
+ a + b: vector addition
+ a - b: vector subtraction
+ a * b: inner product
+ k * a and a * k: multiplication with scalar
+ abs(a): absolute value of a
+ a.rotate(angle): rotation
"""
+
def __new__(cls, x, y):
return tuple.__new__(cls, (x, y))
+
def __add__(self, other):
return Vec2D(self[0]+other[0], self[1]+other[1])
+
def __mul__(self, other):
if isinstance(other, Vec2D):
return self[0]*other[0]+self[1]*other[1]
return Vec2D(self[0]*other, self[1]*other)
+
def __rmul__(self, other):
if isinstance(other, int) or isinstance(other, float):
return Vec2D(self[0]*other, self[1]*other)
return NotImplemented
+
def __sub__(self, other):
return Vec2D(self[0]-other[0], self[1]-other[1])
+
def __neg__(self):
return Vec2D(-self[0], -self[1])
+
def __abs__(self):
return math.hypot(*self)
+
def rotate(self, angle):
- """rotate self counterclockwise by angle
- """
+ """Rotate self counterclockwise by angle."""
perp = Vec2D(-self[1], self[0])
angle = math.radians(angle)
c, s = math.cos(angle), math.sin(angle)
return Vec2D(self[0]*c+perp[0]*s, self[1]*c+perp[1]*s)
+
def __getnewargs__(self):
return (self[0], self[1])
+
def __repr__(self):
return "(%.2f,%.2f)" % self
@@ -280,11 +225,11 @@ def __repr__(self):
### May be replaced by an interface to some different graphics toolkit ###
##############################################################################
-## helper functions for Scrolled Canvas, to forward Canvas-methods
+## Helper functions for Scrolled Canvas, to forward Canvas-methods
## to ScrolledCanvas class
def __methodDict(cls, _dict):
- """helper function for Scrolled Canvas"""
+ """Helper function for Scrolled Canvas."""
baseList = list(cls.__bases__)
baseList.reverse()
for _super in baseList:
@@ -294,7 +239,7 @@ def __methodDict(cls, _dict):
_dict[key] = value
def __methods(cls):
- """helper function for Scrolled Canvas"""
+ """Helper function for Scrolled Canvas."""
_dict = {}
__methodDict(cls, _dict)
return _dict.keys()
@@ -325,11 +270,12 @@ def __forwardmethods(fromClass, toClass, toPart, exclude = ()):
class ScrolledCanvas(TK.Frame):
- """Modeled after the scrolled canvas class from Grayons's Tkinter book.
+ """Modeled after the scrolled canvas class from Grayson's Tkinter book.
Used as the default canvas, which pops up automatically when
using turtle graphics functions or the Turtle class.
"""
+
def __init__(self, master, width=500, height=350,
canvwidth=600, canvheight=500):
TK.Frame.__init__(self, master, width=width, height=height)
@@ -356,7 +302,7 @@ def __init__(self, master, width=500, height=350,
self._rootwindow.bind('', self.onResize)
def reset(self, canvwidth=None, canvheight=None, bg = None):
- """Adjust canvas and scrollbars according to given canvas size."""
+ """Adjust canvas size, background color and scrollbars."""
if canvwidth:
self.canvwidth = canvwidth
if canvheight:
@@ -374,8 +320,7 @@ def reset(self, canvwidth=None, canvheight=None, bg = None):
def adjustScrolls(self):
- """ Adjust scrollbars according to window- and canvas-size.
- """
+ """Adjust scrollbars according to window and canvas size."""
cwidth = self._canvas.winfo_width()
cheight = self._canvas.winfo_height()
self._canvas.xview_moveto(0.5*(self.canvwidth-cwidth)/self.canvwidth)
@@ -394,33 +339,27 @@ def onResize(self, event):
self.adjustScrolls()
def bbox(self, *args):
- """ 'forward' method, which canvas itself has inherited...
- """
+ """Forward to the canvas method of the same name."""
return self._canvas.bbox(*args)
def cget(self, *args, **kwargs):
- """ 'forward' method, which canvas itself has inherited...
- """
+ """Forward to the canvas method of the same name."""
return self._canvas.cget(*args, **kwargs)
def config(self, *args, **kwargs):
- """ 'forward' method, which canvas itself has inherited...
- """
+ """Forward to the canvas method of the same name."""
self._canvas.config(*args, **kwargs)
def bind(self, *args, **kwargs):
- """ 'forward' method, which canvas itself has inherited...
- """
+ """Forward to the canvas method of the same name."""
self._canvas.bind(*args, **kwargs)
def unbind(self, *args, **kwargs):
- """ 'forward' method, which canvas itself has inherited...
- """
+ """Forward to the canvas method of the same name."""
self._canvas.unbind(*args, **kwargs)
def focus_force(self):
- """ 'forward' method, which canvas itself has inherited...
- """
+ """Forward to the canvas method of the same name."""
self._canvas.focus_force()
__forwardmethods(ScrolledCanvas, TK.Canvas, '_canvas')
@@ -428,6 +367,7 @@ def focus_force(self):
class _Root(TK.Tk):
"""Root class for Screen based on Tkinter."""
+
def __init__(self):
TK.Tk.__init__(self)
@@ -439,7 +379,7 @@ def _getcanvas(self):
return self._canvas
def set_geometry(self, width, height, startx, starty):
- self.geometry("%dx%d%+d%+d"%(width, height, startx, starty))
+ self.geometry("%dx%d%+d%+d" % (width, height, startx, starty))
def ondestroy(self, destroy):
self.wm_protocol("WM_DELETE_WINDOW", destroy)
@@ -453,23 +393,22 @@ def win_height(self):
Canvas = TK.Canvas
-class TurtleScreenBase(object):
+class TurtleScreenBase:
"""Provide the basic graphics functionality.
- Interface between Tkinter and turtle.py.
+ Interface between Tkinter and turtle.py.
- To port turtle.py to some different graphics toolkit
- a corresponding TurtleScreenBase class has to be implemented.
+ To port turtle.py to a different graphics toolkit,
+ a corresponding TurtleScreenBase class must be implemented.
"""
def _blankimage(self):
- """return a blank image object
- """
+ """Return a blank image object."""
img = TK.PhotoImage(width=1, height=1, master=self.cv)
img.blank()
return img
def _image(self, filename):
- """return an image object containing the
+ """Return an image object containing the
imagedata from an image file named filename.
"""
return TK.PhotoImage(file=filename, master=self.cv)
@@ -489,20 +428,21 @@ def __init__(self, cv):
self._updating = False
def _createpoly(self):
- """Create an invisible polygon item on canvas self.cv)
- """
+ """Create an invisible polygon item on canvas self.cv."""
return self.cv.create_polygon((0, 0, 0, 0, 0, 0), fill="", outline="")
def _drawpoly(self, polyitem, coordlist, fill=None,
outline=None, width=None, top=False):
- """Configure polygonitem polyitem according to provided
- arguments:
- coordlist is sequence of coordinates
- fill is filling color
- outline is outline color
- top is a boolean value, which specifies if polyitem
- will be put on top of the canvas' displaylist so it
- will not be covered by other items.
+ """Configure polygon item polyitem according to the given arguments.
+
+ Arguments:
+ coordlist -- a sequence of coordinates
+ fill -- the fill color
+ outline -- the outline color
+ width -- the outline width
+ top -- a boolean value, which specifies if polyitem will be
+ put on top of the canvas' display list so it will not
+ be covered by other items
"""
cl = []
for x, y in coordlist:
@@ -519,20 +459,21 @@ def _drawpoly(self, polyitem, coordlist, fill=None,
self.cv.tag_raise(polyitem)
def _createline(self):
- """Create an invisible line item on canvas self.cv)
- """
+ """Create an invisible line item on canvas self.cv."""
return self.cv.create_line(0, 0, 0, 0, fill="", width=2,
capstyle = TK.ROUND)
def _drawline(self, lineitem, coordlist=None,
fill=None, width=None, top=False):
- """Configure lineitem according to provided arguments:
- coordlist is sequence of coordinates
- fill is drawing color
- width is width of drawn line.
- top is a boolean value, which specifies if polyitem
- will be put on top of the canvas' displaylist so it
- will not be covered by other items.
+ """Configure line item lineitem according to the given arguments.
+
+ Arguments:
+ coordlist -- a sequence of coordinates
+ fill -- the drawing color
+ width -- the width of the drawn line
+ top -- a boolean value, which specifies if lineitem will be
+ put on top of the canvas' display list so it will not
+ be covered by other items
"""
if coordlist is not None:
cl = []
@@ -549,13 +490,13 @@ def _drawline(self, lineitem, coordlist=None,
def _delete(self, item):
"""Delete graphics item from canvas.
- If item is"all" delete all graphics items.
+
+ If item is "all", delete all graphics items.
"""
self.cv.delete(item)
def _update(self):
- """Redraw graphics items on canvas
- """
+ """Redraw graphics items on canvas."""
if self._updating:
# Reentrant call (e.g. a drag handler moving the turtle,
# gh-50966): flush drawing without reprocessing input.
@@ -572,8 +513,7 @@ def _delay(self, delay):
self.cv.after(delay)
def _iscolorstring(self, color):
- """Check if the string color is a legal Tkinter color string.
- """
+ """Check if the string color is a legal Tkinter color string."""
try:
self.cv.winfo_rgb(color)
ok = True
@@ -591,10 +531,11 @@ def _bgcolor(self, color=None):
return self.cv.cget("bg")
def _write(self, pos, txt, align, font, pencolor):
- """Write txt at pos in canvas with specified font
- and color.
- Return text item and x-coord of right bottom corner
- of text's bounding box."""
+ """Write txt at pos on the canvas with specified font and color.
+
+ Return text item and x-coord of right bottom corner of text's
+ bounding box.
+ """
x, y = pos
x = x * self.xscale
y = y * self.yscale
@@ -611,31 +552,28 @@ def _onclick(self, item, fun, num=1, add=None):
num, the number of the mouse-button defaults to 1
"""
if fun is None:
- self.cv.tag_unbind(item, "" % num)
+ self.cv.tag_unbind(item, f"")
else:
def eventfun(event):
x, y = (self.cv.canvasx(event.x)/self.xscale,
-self.cv.canvasy(event.y)/self.yscale)
fun(x, y)
- self.cv.tag_bind(item, "" % num, eventfun, add)
+ self.cv.tag_bind(item, f"", eventfun, add)
def _onrelease(self, item, fun, num=1, add=None):
"""Bind fun to mouse-button-release event on turtle.
fun must be a function with two arguments, the coordinates
of the point on the canvas where mouse button is released.
num, the number of the mouse-button defaults to 1
-
- If a turtle is clicked, first _onclick-event will be performed,
- then _onscreensclick-event.
"""
if fun is None:
- self.cv.tag_unbind(item, "" % num)
+ self.cv.tag_unbind(item, f"")
else:
def eventfun(event):
x, y = (self.cv.canvasx(event.x)/self.xscale,
-self.cv.canvasy(event.y)/self.yscale)
fun(x, y)
- self.cv.tag_bind(item, "" % num,
+ self.cv.tag_bind(item, f"",
eventfun, add)
def _ondrag(self, item, fun, num=1, add=None):
@@ -648,7 +586,7 @@ def _ondrag(self, item, fun, num=1, add=None):
mouse-click event on that turtle.
"""
if fun is None:
- self.cv.tag_unbind(item, "" % num)
+ self.cv.tag_unbind(item, f"")
else:
def eventfun(event):
try:
@@ -657,7 +595,7 @@ def eventfun(event):
fun(x, y)
except Exception:
pass
- self.cv.tag_bind(item, "" % num, eventfun, add)
+ self.cv.tag_bind(item, f"", eventfun, add)
def _onscreenclick(self, fun, num=1, add=None):
"""Bind fun to mouse-click event on canvas.
@@ -666,27 +604,28 @@ def _onscreenclick(self, fun, num=1, add=None):
num, the number of the mouse-button defaults to 1
If a turtle is clicked, first _onclick-event will be performed,
- then _onscreensclick-event.
+ then _onscreenclick-event.
"""
if fun is None:
- self.cv.unbind("" % num)
+ self.cv.unbind(f"")
else:
def eventfun(event):
x, y = (self.cv.canvasx(event.x)/self.xscale,
-self.cv.canvasy(event.y)/self.yscale)
fun(x, y)
- self.cv.bind("" % num, eventfun, add)
+ self.cv.bind(f"", eventfun, add)
def _onkeyrelease(self, fun, key):
"""Bind fun to key-release event of key.
- Canvas must have focus. See method listen
+
+ Canvas must have focus. See the listen() method.
"""
if fun is None:
- self.cv.unbind("" % key, None)
+ self.cv.unbind(f"", None)
else:
def eventfun(event):
fun()
- self.cv.bind("" % key, eventfun)
+ self.cv.bind(f"", eventfun)
def _onkeypress(self, fun, key=None):
"""If key is given, bind fun to key-press event of key.
@@ -697,37 +636,32 @@ def _onkeypress(self, fun, key=None):
if key is None:
self.cv.unbind("", None)
else:
- self.cv.unbind("" % key, None)
+ self.cv.unbind(f"", None)
else:
def eventfun(event):
fun()
if key is None:
self.cv.bind("", eventfun)
else:
- self.cv.bind("" % key, eventfun)
+ self.cv.bind(f"", eventfun)
def _listen(self):
- """Set focus on canvas (in order to collect key-events)
- """
+ """Set focus on canvas (in order to collect key-events)."""
self.cv.focus_force()
def _ontimer(self, fun, t):
- """Install a timer, which calls fun after t milliseconds.
- """
+ """Install a timer, which calls fun after t milliseconds."""
if t == 0:
self.cv.after_idle(fun)
else:
self.cv.after(t, fun)
def _createimage(self, image):
- """Create and return image item on canvas.
- """
+ """Create and return image item on canvas."""
return self.cv.create_image(0, 0, image=image)
def _drawimage(self, item, pos, image):
- """Configure image item as to draw image object
- at position (x,y) on canvas)
- """
+ """Configure the canvas item to show image at position pos."""
x, y = pos
self.cv.coords(item, (x * self.xscale, -y * self.yscale))
self.cv.itemconfig(item, image=image)
@@ -736,24 +670,22 @@ def _setbgpic(self, item, image):
"""Configure image item as to draw image object
at center of canvas. Set item to the first item
in the displaylist, so it will be drawn below
- any other item ."""
+ any other item."""
self.cv.itemconfig(item, image=image)
self.cv.tag_lower(item)
def _type(self, item):
- """Return 'line' or 'polygon' or 'image' depending on
- type of item.
- """
+ """Return 'line' or 'polygon' or 'image' depending on type of item."""
return self.cv.type(item)
def _pointlist(self, item):
- """returns list of coordinate-pairs of points of item
- Example (for insiders):
- >>> from turtle import *
- >>> getscreen()._pointlist(getturtle().turtle._item)
- [(0.0, 9.9999999999999982), (0.0, -9.9999999999999982),
- (9.9999999999999982, 0.0)]
- >>> """
+ """Return list of coordinate pairs of points of item.
+
+ For example:
+ >>> getscreen()._pointlist(getturtle().turtle._item)
+ [(0.0, 9.9999999999999982), (0.0, -9.9999999999999982),
+ (9.9999999999999982, 0.0)]
+ """
cl = self.cv.coords(item)
pl = [(cl[i], -cl[i+1]) for i in range(0, len(cl), 2)]
return pl
@@ -774,8 +706,9 @@ def _rescale(self, xscalefactor, yscalefactor):
self.cv.coords(item, *newcoordlist)
def _resize(self, canvwidth=None, canvheight=None, bg=None):
- """Resize the canvas the turtles are drawing on. Does
- not alter the drawing window.
+ """Resize the canvas the turtles are drawing on.
+
+ Does not alter the drawing window.
"""
# needs amendment
if not isinstance(self.cv, ScrolledCanvas):
@@ -789,8 +722,7 @@ def _resize(self, canvwidth=None, canvheight=None, bg=None):
self.cv.reset(canvwidth, canvheight, bg)
def _window_size(self):
- """ Return the width and height of the turtle window.
- """
+ """Return the width and height of the turtle window."""
width = self.cv.winfo_width()
if width <= 1: # the window isn't managed by a geometry manager
width = self.cv['width']
@@ -800,52 +732,51 @@ def _window_size(self):
return width, height
def mainloop(self):
- """Starts event loop - calling Tkinter's mainloop function.
-
- No argument.
-
- Must be last statement in a turtle graphics program.
- Must NOT be used if a script is run from within IDLE in -n mode
- (No subprocess) - for interactive use of turtle graphics.
-
- Example (for a TurtleScreen instance named screen):
- >>> screen.mainloop()
+ """Start the event loop by calling Tkinter's mainloop method.
+ Must be the last statement in a turtle graphics program. Must not
+ be used if a script is run from within IDLE in -n mode (no
+ subprocess).
"""
self.cv.tk.mainloop()
def textinput(self, title, prompt):
"""Pop up a dialog window for input of a string.
- Arguments: title is the title of the dialog window,
- prompt is a text mostly describing what information to input.
-
- Return the string input
+ title is the title of the dialog window and prompt is a text
+ describing what information to input. Return the string entered.
If the dialog is canceled, return None.
- Example (for a TurtleScreen instance named screen):
- >>> screen.textinput("NIM", "Name of first player:")
+ Arguments:
+ title -- a string
+ prompt -- a string
+ Example (for a TurtleScreen instance named screen):
+ >>> screen.textinput("NIM", "Name of first player:")
"""
return simpledialog.askstring(title, prompt, parent=self.cv)
def numinput(self, title, prompt, default=None, minval=None, maxval=None):
"""Pop up a dialog window for input of a number.
- Arguments: title is the title of the dialog window,
- prompt is a text mostly describing what numerical information to input.
- default: default value
- minval: minimum value for input
- maxval: maximum value for input
+ title is the title of the dialog window and prompt is a text
+ describing what numerical information to input. default is the
+ default value, minval and maxval are the minimum and maximum
+ values for input. If these are given and the number entered is not
+ between minval and maxval, a hint is issued and the dialog remains
+ open for correction. Return the number entered. If the dialog is
+ canceled, return None.
- The number input must be in the range minval .. maxval if these are
- given. If not, a hint is issued and the dialog remains open for
- correction. Return the number input.
- If the dialog is canceled, return None.
+ Arguments:
+ title -- a string
+ prompt -- a string
+ default -- a number or None
+ minval -- a number or None
+ maxval -- a number or None
Example (for a TurtleScreen instance named screen):
- >>> screen.numinput("Poker", "Your stakes:", 1000, minval=10, maxval=10000)
-
+ >>> screen.numinput("Poker", "Your stakes:", 1000,
+ ... minval=10, maxval=10000)
"""
return simpledialog.askfloat(title, prompt, initialvalue=default,
minvalue=minval, maxvalue=maxval,
@@ -857,27 +788,28 @@ def numinput(self, title, prompt, default=None, minval=None, maxval=None):
##############################################################################
-class Terminator (Exception):
- """Will be raised in TurtleScreen.update, if _RUNNING becomes False.
+class Terminator(Exception):
+ """Raised by turtle commands after the turtle screen has been closed.
- This stops execution of a turtle graphics script.
- Main purpose: use in the Demo-Viewer turtle.Demo.py.
+ This stops the execution of a turtle graphics script. It is mainly
+ used by the turtledemo viewer.
"""
- pass
class TurtleGraphicsError(Exception):
- """Some TurtleGraphics Error
- """
+ """Raised for invalid arguments or operations."""
-class Shape(object):
+class Shape:
"""Data structure modeling shapes.
- attribute _type is one of "polygon", "image", "compound"
- attribute _data is - depending on _type a poygon-tuple,
- an image or a list constructed using the addcomponent method.
+ type_ is one of the strings "polygon", "image" or "compound". What
+ data must be depends on type_: for "polygon" a tuple of pairs of
+ coordinates, for "image" an image (only used internally), and for
+ "compound" None, as a compound shape is built up using the
+ addcomponent method.
"""
+
def __init__(self, type_, data=None):
self._type = type_
if type_ == "polygon":
@@ -888,40 +820,44 @@ def __init__(self, type_, data=None):
elif type_ == "compound":
data = []
else:
- raise TurtleGraphicsError("There is no shape type %s" % type_)
+ raise TurtleGraphicsError(f"There is no shape type {type_!r}")
self._data = data
def addcomponent(self, poly, fill, outline=None):
- """Add component to a shape of type compound.
+ """Add a component to a shape of type "compound".
- Arguments: poly is a polygon, i. e. a tuple of number pairs.
- fill is the fillcolor of the component,
- outline is the outline color of the component.
+ poly is a polygon, a tuple of pairs of numbers. fill is the color
+ the polygon is filled with and outline is the color of its
+ outline. If outline is not given, fill is used for it as well.
- call (for a Shapeobject namend s):
- -- s.addcomponent(((0,0), (10,10), (-10,10)), "red", "blue")
+ Arguments:
+ poly -- a tuple of pairs of numbers
+ fill -- a color
+ outline -- a color or None
Example:
- >>> poly = ((0,0),(10,-5),(0,10),(-10,-5))
- >>> s = Shape("compound")
- >>> s.addcomponent(poly, "red", "blue")
- >>> # .. add more components and then use register_shape()
+ >>> poly = ((0,0), (10,-5), (0,10), (-10,-5))
+ >>> s = Shape("compound")
+ >>> s.addcomponent(poly, "red", "blue")
+ >>> # ... add more components and then use register_shape()
"""
if self._type != "compound":
- raise TurtleGraphicsError("Cannot add component to %s Shape"
- % self._type)
+ raise TurtleGraphicsError(f"Cannot add component to {self._type!r} Shape")
+
if outline is None:
outline = fill
self._data.append([poly, fill, outline])
-class Tbuffer(object):
- """Ring buffer used as undobuffer for RawTurtle objects."""
+class Tbuffer:
+ """Ring buffer used as undo buffer for RawTurtle objects."""
+
def __init__(self, bufsize=10):
self.bufsize = bufsize
self.buffer = [[None]] * bufsize
self.ptr = -1
self.cumulate = False
+
def reset(self, bufsize=None):
if bufsize is None:
for i in range(self.bufsize):
@@ -930,6 +866,7 @@ def reset(self, bufsize=None):
self.bufsize = bufsize
self.buffer = [[None]] * bufsize
self.ptr = -1
+
def push(self, item):
if self.bufsize > 0:
if not self.cumulate:
@@ -937,6 +874,7 @@ def push(self, item):
self.buffer[self.ptr] = item
else:
self.buffer[self.ptr].append(item)
+
def pop(self):
if self.bufsize > 0:
item = self.buffer[self.ptr]
@@ -946,20 +884,31 @@ def pop(self):
self.buffer[self.ptr] = [None]
self.ptr = (self.ptr - 1) % self.bufsize
return (item)
+
+ def remove(self, item):
+ if item not in self.buffer:
+ return
+ index = self.buffer.index(item)
+ self.buffer.remove(item)
+ if index <= self.ptr:
+ self.ptr = (self.ptr - 1) % self.bufsize
+ self.buffer.insert((self.ptr+1) % self.bufsize, [None])
+
def nr_of_items(self):
return self.bufsize - self.buffer.count([None])
+
def __repr__(self):
return str(self.buffer) + " " + str(self.ptr)
-
class TurtleScreen(TurtleScreenBase):
- """Provides screen oriented methods like bgcolor etc.
+ """Provides the screen-oriented methods, such as bgcolor().
- Only relies upon the methods of TurtleScreenBase and NOT
- upon components of the underlying graphics toolkit -
- which is Tkinter in this case.
+ Only relies upon the methods of TurtleScreenBase and not upon
+ components of the underlying graphics toolkit, which is Tkinter
+ in this case.
"""
+
_RUNNING = True
def __init__(self, cv, mode=_CFG["mode"],
@@ -1002,18 +951,19 @@ def __init__(self, cv, mode=_CFG["mode"],
rootwindow.wm_attributes(topmost=True)
rootwindow.wm_attributes(topmost=False)
+ # A new screen means that turtle graphics is running again.
+ TurtleScreen._RUNNING = True
+
def clear(self):
"""Delete all drawings and all turtles from the TurtleScreen.
- No argument.
-
- Reset empty TurtleScreen to its initial state: white background,
- no backgroundimage, no eventbindings and tracing on.
+ Aliases: clear | clearscreen
- Example (for a TurtleScreen instance named screen):
- >>> screen.clear()
-
- Note: this method is not available as function.
+ Reset the now empty TurtleScreen to its initial state: white
+ background, no background image, no event bindings and tracing on.
+ As a function, this method is only available under the name
+ clearscreen. The function clear is derived from the Turtle method
+ clear.
"""
self._delayvalue = _CFG["delay"]
self._colormode = _CFG["colormode"]
@@ -1033,26 +983,29 @@ def clear(self):
Turtle._pen = None
def mode(self, mode=None):
- """Set turtle-mode ('standard', 'logo' or 'world') and perform reset.
+ """Set the turtle mode and perform a reset.
- Optional argument:
- mode -- one of the strings 'standard', 'logo' or 'world'
+ mode is one of the strings "standard", "logo" or "world". If mode
+ is not given, return the current mode.
- Mode 'standard' is compatible with turtle.py.
- Mode 'logo' is compatible with most Logo-Turtle-Graphics.
- Mode 'world' uses userdefined 'worldcoordinates'. *Attention*: in
- this mode angles appear distorted if x/y unit-ratio doesn't equal 1.
- If mode is not given, return the current mode.
+ Mode "standard" is compatible with the old turtle module. Mode
+ "logo" is compatible with most Logo turtle graphics. Mode "world"
+ uses user-defined world coordinates, see setworldcoordinates(). In
+ this mode, angles appear distorted if the x and y units are not of
+ equal length.
Mode Initial turtle heading positive angles
------------|-------------------------|-------------------
- 'standard' to the right (east) counterclockwise
- 'logo' upward (north) clockwise
+ "standard" to the right (east) counterclockwise
+ "logo" upward (north) clockwise
+
+ Argument:
+ mode -- a string or None
- Examples:
- >>> mode('logo') # resets turtle heading to north
- >>> mode()
- 'logo'
+ Example (for a TurtleScreen instance named screen):
+ >>> screen.mode("logo") # resets turtle heading to north
+ >>> screen.mode()
+ 'logo'
"""
if mode is None:
return self._mode
@@ -1067,26 +1020,29 @@ def mode(self, mode=None):
self.reset()
def setworldcoordinates(self, llx, lly, urx, ury):
- """Set up a user defined coordinate-system.
-
- Arguments:
- llx -- a number, x-coordinate of lower left corner of canvas
- lly -- a number, y-coordinate of lower left corner of canvas
- urx -- a number, x-coordinate of upper right corner of canvas
- ury -- a number, y-coordinate of upper right corner of canvas
+ """Set up a user-defined coordinate system.
- Set up user coodinat-system and switch to mode 'world' if necessary.
- This performs a screen.reset. If mode 'world' is already active,
- all drawings are redrawn according to the new coordinates.
+ llx and lly are the x and y coordinates of the lower left corner of
+ the canvas. urx and ury are the x and y coordinates of the upper
+ right corner. Switch to mode "world" if necessary, which performs a
+ reset. If mode "world" is already active, all drawings are redrawn
+ according to the new coordinates. In user-defined coordinate
+ systems, angles may appear distorted, see mode().
- But ATTENTION: in user-defined coordinatesystems angles may appear
- distorted. (see Screen.mode())
+ Arguments:
+ llx -- a number
+ lly -- a number
+ urx -- a number
+ ury -- a number
Example (for a TurtleScreen instance named screen):
- >>> screen.setworldcoordinates(-10,-0.5,50,1.5)
- >>> for _ in range(36):
- ... left(10)
- ... forward(0.5)
+ >>> screen.reset()
+ >>> screen.setworldcoordinates(-50,-7.5,50,7.5)
+ >>> for _ in range(72):
+ ... left(10)
+ ...
+ >>> for _ in range(8):
+ ... left(45); fd(2) # a regular octagon
"""
if self.mode() != "world":
self.mode("world")
@@ -1106,31 +1062,35 @@ def setworldcoordinates(self, llx, lly, urx, ury):
self.update()
def register_shape(self, name, shape=None):
- """Adds a turtle shape to TurtleScreen's shapelist.
+ """Add a turtle shape to the TurtleScreen's shape list.
+
+ Aliases: register_shape | addshape
+
+ It can be called in four different ways:
+
+ (1) name is the name of an image file (PNG, GIF, PGM, and PPM) and
+ shape is None. Install the corresponding image shape.
+ (2) name is an arbitrary string and shape is the name of an image
+ file (PNG, GIF, PGM, and PPM). Install the corresponding image
+ shape.
+ (3) name is an arbitrary string and shape is a tuple of pairs of
+ coordinates. Install the corresponding polygon shape.
+ (4) name is an arbitrary string and shape is a (compound) Shape
+ object. Install the corresponding compound shape.
+
+ Image shapes do not rotate when turning the turtle, so they do not
+ display the heading of the turtle. To use a registered shape, call
+ shape() with its name.
Arguments:
- (1) name is the name of an image file (PNG, GIF, PGM, and PPM) and shape is None.
- Installs the corresponding image shape.
- !! Image-shapes DO NOT rotate when turning the turtle,
- !! so they do not display the heading of the turtle!
- (2) name is an arbitrary string and shape is the name of an image file (PNG, GIF, PGM, and PPM).
- Installs the corresponding image shape.
- !! Image-shapes DO NOT rotate when turning the turtle,
- !! so they do not display the heading of the turtle!
- (3) name is an arbitrary string and shape is a tuple
- of pairs of coordinates. Installs the corresponding
- polygon shape
- (4) name is an arbitrary string and shape is a
- (compound) Shape object. Installs the corresponding
- compound shape.
- To use a shape, you have to issue the command shape(shapename).
-
- call: register_shape("turtle.gif")
- --or: register_shape("tri", ((0,0), (10,10), (-10,10)))
+ name -- a string
+ shape -- a string, a tuple of pairs of numbers, a Shape object
+ or None
Example (for a TurtleScreen instance named screen):
- >>> screen.register_shape("triangle", ((5,-3),(0,5),(-5,-3)))
-
+ >>> screen.register_shape("turtle.gif")
+ >>> screen.register_shape("turtle", "turtle.gif")
+ >>> screen.register_shape("triangle", ((5,-3), (0,5), (-5,-3)))
"""
if shape is None:
shape = Shape("image", self._image(name))
@@ -1142,14 +1102,12 @@ def register_shape(self, name, shape=None):
self._shapes[name] = shape
def _colorstr(self, color):
- """Return color string corresponding to args.
+ """Return the color string corresponding to color.
- Argument may be a string or a tuple of three
- numbers corresponding to actual colormode,
- i.e. in the range 0<=n<=colormode.
+ color may be a string or a tuple of three numbers, each between 0 and
+ the current colormode.
- If the argument doesn't represent a color,
- an error is raised.
+ If color doesn't represent a color, an error is raised.
"""
if len(color) == 1:
color = color[0]
@@ -1182,16 +1140,24 @@ def _color(self, cstr):
def colormode(self, cmode=None):
"""Return the colormode or set it to 1.0 or 255.
- Optional argument:
- cmode -- one of the values 1.0 or 255
+ After setting it, the r, g and b values of color triples have to
+ be between 0 and cmode.
- r, g, b values of colortriples have to be in range 0..cmode.
+ Argument:
+ cmode -- a number or None
Example (for a TurtleScreen instance named screen):
- >>> screen.colormode()
- 1.0
- >>> screen.colormode(255)
- >>> pencolor(240,160,80)
+ >>> screen.colormode(1)
+ >>> turtle.pencolor(240, 160, 80)
+ Traceback (most recent call last):
+ ...
+ turtle.TurtleGraphicsError: bad color sequence: (240, 160, 80)
+ >>> screen.colormode()
+ 1.0
+ >>> screen.colormode(255)
+ >>> screen.colormode()
+ 255
+ >>> turtle.pencolor(240,160,80)
"""
if cmode is None:
return self._colormode
@@ -1201,12 +1167,13 @@ def colormode(self, cmode=None):
self._colormode = int(cmode)
def reset(self):
- """Reset all Turtles on the Screen to their initial state.
+ """Reset all turtles on the screen to their initial state.
- No argument.
+ Aliases: reset | resetscreen
- Example (for a TurtleScreen instance named screen):
- >>> screen.reset()
+ As a function, this method is only available under the name
+ resetscreen. The function reset is derived from the Turtle method
+ reset().
"""
for turtle in self._turtles:
turtle._setmode(self._mode)
@@ -1216,40 +1183,40 @@ def turtles(self):
"""Return the list of turtles on the screen.
Example (for a TurtleScreen instance named screen):
- >>> screen.turtles()
- []
+ >>> for turtle in screen.turtles():
+ ... turtle.color("red")
"""
return self._turtles
def bgcolor(self, *args):
- """Set or return backgroundcolor of the TurtleScreen.
+ """Return or set the background color of the TurtleScreen.
Four input formats are allowed:
- bgcolor()
- Return the current background color as color specification
+ Return the current background color as a color specification
string or as a tuple (see example). May be used as input
- to another color/pencolor/fillcolor/bgcolor call.
+ to another color(), pencolor(), fillcolor() or bgcolor() call.
- bgcolor(colorstring)
Set the background color to colorstring, which is a Tk color
specification string, such as "red", "yellow", or "#33cc8c".
- bgcolor((r, g, b))
Set the background color to the RGB color represented by
- the tuple of r, g, and b. Each of r, g, and b must be in
- the range 0..colormode, where colormode is either 1.0 or 255
+ the tuple of r, g, and b. Each of r, g, and b must be
+ between 0 and colormode, where colormode is either 1.0 or 255
(see colormode()).
- bgcolor(r, g, b)
Set the background color to the RGB color represented by
- r, g, and b. Each of r, g, and b must be in the range
- 0..colormode.
+ r, g, and b. Each of r, g, and b must be between 0 and
+ colormode.
Example (for a TurtleScreen instance named screen):
- >>> screen.bgcolor("orange")
- >>> screen.bgcolor()
- 'orange'
- >>> colormode(255)
- >>> screen.bgcolor('#800080')
- >>> screen.bgcolor()
- (128.0, 0.0, 128.0)
+ >>> screen.bgcolor("orange")
+ >>> screen.bgcolor()
+ 'orange'
+ >>> screen.colormode(255)
+ >>> screen.bgcolor("#800080")
+ >>> screen.bgcolor()
+ (128.0, 0.0, 128.0)
"""
if args:
color = self._colorstr(args)
@@ -1261,23 +1228,26 @@ def bgcolor(self, *args):
return color
def tracer(self, n=None, delay=None):
- """Turns turtle animation on/off and set delay for update drawings.
+ """Turn turtle animation on or off and set the drawing delay.
- Optional arguments:
- n -- nonnegative integer
- delay -- nonnegative integer
+ If n is given, only every n-th regular screen update is performed,
+ which can be used to speed up the drawing of complex graphics. If
+ n is 0, animation is turned off and the screen is only updated by
+ calling update(). If delay is given, it sets the drawing delay, see
+ delay(). When called without arguments, return the current value
+ of n.
- If n is given, only each n-th regular screen update is really performed.
- (Can be used to accelerate the drawing of complex graphics.)
- Second arguments sets delay value (see RawTurtle.delay())
+ Arguments:
+ n -- a nonnegative integer or None
+ delay -- a nonnegative integer or None
Example (for a TurtleScreen instance named screen):
- >>> screen.tracer(8, 25)
- >>> dist = 2
- >>> for i in range(200):
- ... fd(dist)
- ... rt(90)
- ... dist += 2
+ >>> screen.tracer(8, 25)
+ >>> dist = 2
+ >>> for i in range(200):
+ ... fd(dist)
+ ... rt(90)
+ ... dist += 2
"""
if n is None:
return self._tracing
@@ -1289,15 +1259,21 @@ def tracer(self, n=None, delay=None):
self.update()
def delay(self, delay=None):
- """ Return or set the drawing delay in milliseconds.
+ """Return or set the drawing delay in milliseconds.
+
+ This is approximately the time interval between two consecutive
+ canvas updates. The longer the drawing delay, the slower the
+ animation.
- Optional argument:
- delay -- positive integer
+ Argument:
+ delay -- a nonnegative integer or None
Example (for a TurtleScreen instance named screen):
- >>> screen.delay(15)
- >>> screen.delay()
- 15
+ >>> screen.delay()
+ 10
+ >>> screen.delay(5)
+ >>> screen.delay()
+ 5
"""
if delay is None:
return self._delayvalue
@@ -1305,16 +1281,17 @@ def delay(self, delay=None):
@contextmanager
def no_animation(self):
- """Temporarily turn off auto-updating the screen.
+ """Temporarily turn off turtle animation.
- This is useful for drawing complex shapes where even the fastest setting
- is too slow. Once this context manager is exited, the drawing will
- be displayed.
+ The code inside the with block is not animated. Once the block is
+ exited, the drawing appears. This is useful for drawing complex
+ shapes where even the fastest speed setting is too slow.
- Example (for a TurtleScreen instance named screen
- and a Turtle instance named turtle):
- >>> with screen.no_animation():
- ... turtle.circle(50)
+ Example (for a TurtleScreen instance named screen):
+ >>> with screen.no_animation():
+ ... for dist in range(2, 400, 2):
+ ... fd(dist)
+ ... rt(90)
"""
tracer = self.tracer()
try:
@@ -1324,7 +1301,7 @@ def no_animation(self):
self.tracer(tracer)
def _incrementudc(self):
- """Increment update counter."""
+ """Increment the update counter."""
if not TurtleScreen._RUNNING:
TurtleScreen._RUNNING = True
raise Terminator
@@ -1334,6 +1311,8 @@ def _incrementudc(self):
def update(self):
"""Perform a TurtleScreen update.
+
+ To be used when tracer() is turned off.
"""
tracing = self._tracing
self._tracing = True
@@ -1344,85 +1323,91 @@ def update(self):
self._update()
def window_width(self):
- """ Return the width of the turtle window.
+ """Return the width of the turtle window.
Example (for a TurtleScreen instance named screen):
- >>> screen.window_width()
- 640
+ >>> screen.window_width()
+ 640
"""
return self._window_size()[0]
def window_height(self):
- """ Return the height of the turtle window.
+ """Return the height of the turtle window.
Example (for a TurtleScreen instance named screen):
- >>> screen.window_height()
- 480
+ >>> screen.window_height()
+ 480
"""
return self._window_size()[1]
def getcanvas(self):
"""Return the Canvas of this TurtleScreen.
- No argument.
-
Example (for a Screen instance named screen):
- >>> cv = screen.getcanvas()
- >>> cv
-
+ >>> cv = screen.getcanvas()
+ >>> cv
+
"""
return self.cv
def getshapes(self):
"""Return a list of names of all currently available turtle shapes.
- No argument.
-
Example (for a TurtleScreen instance named screen):
- >>> screen.getshapes()
- ['arrow', 'blank', 'circle', ... , 'turtle']
+ >>> screen.getshapes()
+ ['arrow', 'blank', 'circle', ..., 'turtle']
"""
return sorted(self._shapes.keys())
def onclick(self, fun, btn=1, add=None):
- """Bind fun to mouse-click event on canvas.
+ """Bind fun to mouse-click events on this screen.
- Arguments:
- fun -- a function with two arguments, the coordinates of the
- clicked point on the canvas.
- btn -- the number of the mouse-button, defaults to 1
+ Aliases: onclick | onscreenclick
+
+ fun is called with the coordinates of the clicked point on the
+ canvas. If fun is None, existing bindings are removed. btn is the
+ number of the mouse button and defaults to 1, the left mouse
+ button. If add is True, a new binding is added, otherwise it
+ replaces a previous binding. As a function, this method is only
+ available under the name onscreenclick. The function onclick is
+ derived from the Turtle method onclick.
- Example (for a TurtleScreen instance named screen)
+ Arguments:
+ fun -- a function with two arguments or None
+ btn -- an integer
+ add -- a boolean or None
- >>> screen.onclick(goto)
- >>> # Subsequently clicking into the TurtleScreen will
- >>> # make the turtle move to the clicked point.
- >>> screen.onclick(None)
+ Example (for a TurtleScreen instance named screen):
+ >>> screen.onscreenclick(turtle.goto)
+ >>> # Subsequently clicking into the TurtleScreen will
+ >>> # make the turtle move to the clicked point.
+ >>> screen.onscreenclick(None) # remove event binding again
"""
self._onscreenclick(fun, btn, add)
def onkey(self, fun, key):
- """Bind fun to key-release event of key.
+ """Bind fun to the key-release event of key.
- Arguments:
- fun -- a function with no arguments
- key -- a string: key (e.g. "a") or key-symbol (e.g. "space")
-
- In order to be able to register key-events, TurtleScreen
- must have focus. (See method listen.)
+ Aliases: onkey | onkeyrelease
- Example (for a TurtleScreen instance named screen):
+ key is a key, such as "a", or a key symbol, such as "space". If
+ fun is None, the event binding is removed. To be able to receive
+ key events, the TurtleScreen must have focus, see listen().
- >>> def f():
- ... fd(50)
- ... lt(60)
- ...
- >>> screen.onkey(f, "Up")
- >>> screen.listen()
+ Arguments:
+ fun -- a function with no arguments or None
+ key -- a string
- Subsequently the turtle can be moved by repeatedly pressing
- the up-arrow key, consequently drawing a hexagon
+ Example (for a TurtleScreen instance named screen):
+ >>> def f():
+ ... fd(50)
+ ... lt(60)
+ ...
+ >>> screen.onkey(f, "Up")
+ >>> screen.listen()
+ The turtle can then be moved by repeatedly pressing the up-arrow
+ key, drawing a hexagon.
"""
if fun is None:
if key in self._keys:
@@ -1432,29 +1417,28 @@ def onkey(self, fun, key):
self._onkeyrelease(fun, key)
def onkeypress(self, fun, key=None):
- """Bind fun to key-press event of key if key is given,
- or to any key-press-event if no key is given.
+ """Bind fun to the key-press event of key.
- Arguments:
- fun -- a function with no arguments
- key -- a string: key (e.g. "a") or key-symbol (e.g. "space")
+ key is a key, such as "a", or a key symbol, such as "space". If
+ key is not given, fun is bound to the key-press event of any key.
+ If fun is None, the event binding is removed. To be able to
+ receive key events, the TurtleScreen must have focus, see
+ listen().
- In order to be able to register key-events, TurtleScreen
- must have focus. (See method listen.)
-
- Example (for a TurtleScreen instance named screen
- and a Turtle instance named turtle):
+ Arguments:
+ fun -- a function with no arguments or None
+ key -- a string or None
- >>> def f():
- ... fd(50)
- ... lt(60)
- ...
- >>> screen.onkeypress(f, "Up")
- >>> screen.listen()
+ Example (for a TurtleScreen instance named screen):
+ >>> def f():
+ ... fd(50)
+ ... lt(60)
+ ...
+ >>> screen.onkeypress(f, "Up")
+ >>> screen.listen()
- Subsequently the turtle can be moved by repeatedly pressing
- the up-arrow key, or by keeping pressed the up-arrow key.
- consequently drawing a hexagon.
+ The turtle can then be moved by pressing or holding down the
+ up-arrow key, drawing a hexagon.
"""
if fun is None:
if key in self._keys:
@@ -1464,54 +1448,54 @@ def onkeypress(self, fun, key=None):
self._onkeypress(fun, key)
def listen(self, xdummy=None, ydummy=None):
- """Set focus on TurtleScreen (in order to collect key-events)
+ """Set focus on the TurtleScreen so that it receives key events.
- No arguments.
- Dummy arguments are provided in order
- to be able to pass listen to the onclick method.
+ The two dummy arguments are only there so that listen() can be
+ passed to onclick().
- Example (for a TurtleScreen instance named screen):
- >>> screen.listen()
+ Arguments:
+ xdummy -- ignored
+ ydummy -- ignored
"""
self._listen()
def ontimer(self, fun, t=0):
- """Install a timer, which calls fun after t milliseconds.
+ """Install a timer that calls fun after t milliseconds.
Arguments:
- fun -- a function with no arguments.
- t -- a number >= 0
+ fun -- a function with no arguments
+ t -- a nonnegative number
Example (for a TurtleScreen instance named screen):
-
- >>> running = True
- >>> def f():
- ... if running:
- ... fd(50)
- ... lt(60)
- ... screen.ontimer(f, 250)
- ...
- >>> f() # makes the turtle marching around
- >>> running = False
+ >>> running = True
+ >>> def f():
+ ... if running:
+ ... fd(50)
+ ... lt(60)
+ ... screen.ontimer(f, 250)
+ ...
+ >>> f() # makes the turtle march around
+ >>> running = False
"""
self._ontimer(fun, t)
def bgpic(self, picname=None):
- """Set background image or return name of current backgroundimage.
+ """Set the background image or return the name of the current one.
- Optional argument:
- picname -- a string, name of an image file (PNG, GIF, PGM, and PPM) or "nopic".
+ If picname is the name of an image file (PNG, GIF, PGM, and PPM),
+ set that image as the background. If picname is "nopic", delete
+ the background image, if present. If picname is None, return the
+ filename of the current background image.
- If picname is a filename, set the corresponding image as background.
- If picname is "nopic", delete backgroundimage, if present.
- If picname is None, return the filename of the current backgroundimage.
+ Argument:
+ picname -- a string or None
Example (for a TurtleScreen instance named screen):
- >>> screen.bgpic()
- 'nopic'
- >>> screen.bgpic("landscape.gif")
- >>> screen.bgpic()
- 'landscape.gif'
+ >>> screen.bgpic()
+ 'nopic'
+ >>> screen.bgpic("landscape.gif")
+ >>> screen.bgpic()
+ 'landscape.gif'
"""
if picname is None:
return self._bgpicname
@@ -1523,34 +1507,44 @@ def bgpic(self, picname=None):
def screensize(self, canvwidth=None, canvheight=None, bg=None):
"""Resize the canvas the turtles are drawing on.
- Optional arguments:
- canvwidth -- positive integer, new width of canvas in pixels
- canvheight -- positive integer, new height of canvas in pixels
- bg -- colorstring or color-tuple, new backgroundcolor
- If no arguments are given, return current (canvaswidth, canvasheight)
+ canvwidth and canvheight are the new width and height of the
+ canvas in pixels, and bg is the new background color. If no
+ arguments are given, return the current canvas width and height.
- Do not alter the drawing window. To observe hidden parts of
- the canvas use the scrollbars. (Can make visible those parts
- of a drawing, which were outside the canvas before!)
+ The drawing window is not altered. To see hidden parts of the
+ canvas, use the scrollbars. This can make visible those parts of a
+ drawing which were outside the canvas before, for example to find
+ a turtle that has wandered off the canvas.
- Example (for a Turtle instance named turtle):
- >>> turtle.screensize(2000,1500)
- >>> # e.g. to search for an erroneously escaped turtle ;-)
+ Arguments:
+ canvwidth -- a positive integer or None
+ canvheight -- a positive integer or None
+ bg -- a colorstring or None
+
+ Example (for a TurtleScreen instance named screen):
+ >>> screen.screensize()
+ (400, 300)
+ >>> screen.screensize(2000,1500)
+ >>> screen.screensize()
+ (2000, 1500)
"""
return self._resize(canvwidth, canvheight, bg)
def save(self, filename, *, overwrite=False):
- """Save the drawing as a PostScript file
+ """Save the current drawing and the turtles as a PostScript file.
- Arguments:
- filename -- a string, the path of the created file.
- Must end with '.ps' or '.eps'.
+ filename is the path of the file to create. It must end with
+ ".ps" or ".eps". If a file with that name already exists, a
+ FileExistsError is raised, unless overwrite is True. overwrite
+ must be given by name, as in overwrite=True.
- Optional arguments:
- overwrite -- boolean, if true, then existing files will be overwritten
+ Arguments:
+ filename -- a string
+ overwrite -- a boolean
Example (for a TurtleScreen instance named screen):
- >>> screen.save('my_drawing.eps')
+ >>> screen.save("my_drawing.ps")
+ >>> screen.save("my_drawing.ps", overwrite=True)
"""
filename = Path(filename)
if not filename.parent.exists():
@@ -1572,20 +1566,26 @@ def save(self, filename, *, overwrite=False):
postscript = self.cv.postscript()
filename.write_text(postscript)
+ # Aliases for the commonly used commands:
+
onscreenclick = onclick
resetscreen = reset
clearscreen = clear
addshape = register_shape
onkeyrelease = onkey
-class TNavigator(object):
- """Navigation part of the RawTurtle.
+
+class TNavigator:
+ """The navigation part of RawTurtle.
+
Implements methods for turtle movement.
"""
+
START_ORIENTATION = {
"standard": Vec2D(1.0, 0.0),
"world" : Vec2D(1.0, 0.0),
- "logo" : Vec2D(0.0, 1.0) }
+ "logo" : Vec2D(0.0, 1.0),
+ }
DEFAULT_MODE = "standard"
DEFAULT_ANGLEOFFSET = 0
DEFAULT_ANGLEORIENT = 1
@@ -1601,16 +1601,15 @@ def __init__(self, mode=DEFAULT_MODE):
TNavigator.reset(self)
def reset(self):
- """reset turtle to its initial values
+ """Reset the turtle to its initial values.
- Will be overwritten by parent class
+ Will be overwritten by the child class.
"""
self._position = Vec2D(0.0, 0.0)
self._orient = TNavigator.START_ORIENTATION[self._mode]
def _setmode(self, mode=None):
- """Set turtle-mode to 'standard', 'world' or 'logo'.
- """
+ """Set the turtle's mode to 'standard', 'world' or 'logo'."""
if mode is None:
return self._mode
if mode not in ["standard", "logo", "world"]:
@@ -1624,7 +1623,7 @@ def _setmode(self, mode=None):
self._angleOrient = -1
def _setDegreesPerAU(self, fullcircle):
- """Helper function for degrees() and radians()"""
+ """Helper function for degrees() and radians()."""
self._fullcircle = fullcircle
self._degreesPerAU = 360/fullcircle
if self._mode == "standard":
@@ -1633,60 +1632,80 @@ def _setDegreesPerAU(self, fullcircle):
self._angleOffset = fullcircle/4.
def degrees(self, fullcircle=360.0):
- """ Set angle measurement units to degrees.
+ """Set the angle measurement units to degrees.
- Optional argument:
- fullcircle - a number
+ The number of degrees in a full circle is set to fullcircle, which
+ defaults to 360.
- Set angle measurement units, i. e. set number
- of 'degrees' for a full circle. Default value is
- 360 degrees.
+ Argument:
+ fullcircle -- a number
Example (for a Turtle instance named turtle):
- >>> turtle.left(90)
- >>> turtle.heading()
- 90
-
- Change angle measurement unit to grad (also known as gon,
- grade, or gradian and equals 1/100-th of the right angle.)
- >>> turtle.degrees(400.0)
- >>> turtle.heading()
- 100
-
+ >>> turtle.home()
+ >>> turtle.left(90)
+ >>> turtle.heading()
+ 90.0
+
+ >>> # Change angle measurement unit to grad (also known as gon,
+ >>> # grade, or gradian and equals 1/100-th of the right angle.)
+ >>> turtle.degrees(400.0)
+ >>> turtle.heading()
+ 100.0
+ >>> turtle.degrees(360)
+ >>> turtle.heading()
+ 90.0
"""
self._setDegreesPerAU(fullcircle)
def radians(self):
- """ Set the angle measurement units to radians.
+ """Set the angle measurement units to radians.
- No arguments.
+ Equivalent to degrees(2 * math.pi).
Example (for a Turtle instance named turtle):
- >>> turtle.heading()
- 90
- >>> turtle.radians()
- >>> turtle.heading()
- 1.5707963267948966
+ >>> turtle.home()
+ >>> turtle.left(90)
+ >>> turtle.heading()
+ 90.0
+ >>> turtle.radians()
+ >>> turtle.heading()
+ 1.5707963267948966
"""
self._setDegreesPerAU(math.tau)
def _go(self, distance):
- """move turtle forward by specified distance"""
+ """Move the turtle forward by the specified distance."""
ende = self._position + self._orient * distance
self._goto(ende)
def _rotate(self, angle):
- """Turn turtle counterclockwise by specified angle if angle > 0."""
+ """Turn the turtle counterclockwise by specified angle, if the angle > 0."""
angle *= self._degreesPerAU
self._orient = self._orient.rotate(angle)
def _goto(self, end):
- """move turtle to position end."""
+ """Move the turtle to the end position."""
self._position = end
+ @contextmanager
+ def _undo_sequence(self):
+ """Record the enclosed actions as a single undo step."""
+ undobuffer = self.undobuffer
+ if not undobuffer or undobuffer.cumulate:
+ yield
+ return
+ undobuffer.push(["seq"])
+ undobuffer.cumulate = True
+ try:
+ yield
+ finally:
+ undobuffer.cumulate = False
+
def teleport(self, x=None, y=None, *, fill_gap: bool = False) -> None:
- """To be overwritten by child class RawTurtle.
- Includes no TPen references."""
+ """To be overwritten by the child class RawTurtle.
+
+ Includes no TPen references.
+ """
new_x = x if x is not None else self._position[0]
new_y = y if y is not None else self._position[1]
self._position = Vec2D(new_x, new_y)
@@ -1696,21 +1715,20 @@ def forward(self, distance):
Aliases: forward | fd
- Argument:
- distance -- a number (integer or float)
+ The turtle moves in the direction it is headed.
- Move the turtle forward by the specified distance, in the direction
- the turtle is headed.
+ Argument:
+ distance -- a number
Example (for a Turtle instance named turtle):
- >>> turtle.position()
- (0.00,0.00)
- >>> turtle.forward(25)
- >>> turtle.position()
- (25.00,0.00)
- >>> turtle.forward(-75)
- >>> turtle.position()
- (-50.00,0.00)
+ >>> turtle.position()
+ (0.00,0.00)
+ >>> turtle.forward(25)
+ >>> turtle.position()
+ (25.00,0.00)
+ >>> turtle.forward(-75)
+ >>> turtle.position()
+ (-50.00,0.00)
"""
self._go(distance)
@@ -1719,134 +1737,125 @@ def back(self, distance):
Aliases: back | backward | bk
- Argument:
- distance -- a number
+ The turtle moves opposite to the direction it is headed.
+ The turtle's heading does not change.
- Move the turtle backward by distance, opposite to the direction the
- turtle is headed. Do not change the turtle's heading.
+ Argument:
+ distance -- a number
Example (for a Turtle instance named turtle):
- >>> turtle.position()
- (0.00,0.00)
- >>> turtle.backward(30)
- >>> turtle.position()
- (-30.00,0.00)
+ >>> turtle.position()
+ (0.00,0.00)
+ >>> turtle.backward(30)
+ >>> turtle.position()
+ (-30.00,0.00)
"""
self._go(-distance)
def right(self, angle):
- """Turn turtle right by angle units.
+ """Turn the turtle right by the specified angle.
Aliases: right | rt
- Argument:
- angle -- a number (integer or float)
+ The angle is measured in degrees by default; the unit can be
+ changed with degrees() or radians(). How the heading is measured
+ depends on the turtle mode, see mode().
- Turn turtle right by angle units. (Units are by default degrees,
- but can be set via the degrees() and radians() functions.)
- Angle orientation depends on mode. (See this.)
+ Argument:
+ angle -- a number
Example (for a Turtle instance named turtle):
- >>> turtle.heading()
- 22.0
- >>> turtle.right(45)
- >>> turtle.heading()
- 337.0
+ >>> turtle.heading()
+ 22.0
+ >>> turtle.right(45)
+ >>> turtle.heading()
+ 337.0
"""
self._rotate(-angle)
def left(self, angle):
- """Turn turtle left by angle units.
+ """Turn the turtle left by the specified angle.
Aliases: left | lt
- Argument:
- angle -- a number (integer or float)
+ The angle is measured in degrees by default; the unit can be
+ changed with degrees() or radians(). How the heading is measured
+ depends on the turtle mode, see mode().
- Turn turtle left by angle units. (Units are by default degrees,
- but can be set via the degrees() and radians() functions.)
- Angle orientation depends on mode. (See this.)
+ Argument:
+ angle -- a number
Example (for a Turtle instance named turtle):
- >>> turtle.heading()
- 22.0
- >>> turtle.left(45)
- >>> turtle.heading()
- 67.0
+ >>> turtle.heading()
+ 22.0
+ >>> turtle.left(45)
+ >>> turtle.heading()
+ 67.0
"""
self._rotate(angle)
def pos(self):
- """Return the turtle's current location (x,y), as a Vec2D-vector.
+ """Return the turtle's current location (x,y) as a Vec2D vector.
Aliases: pos | position
- No arguments.
-
Example (for a Turtle instance named turtle):
- >>> turtle.pos()
- (0.00, 240.00)
+ >>> turtle.pos()
+ (0.00,240.00)
"""
return self._position
def xcor(self):
- """ Return the turtle's x coordinate.
-
- No arguments.
+ """Return the turtle's x coordinate.
Example (for a Turtle instance named turtle):
- >>> reset()
- >>> turtle.left(60)
- >>> turtle.forward(100)
- >>> print(turtle.xcor())
- 50.0
+ >>> turtle.home()
+ >>> turtle.left(50)
+ >>> turtle.forward(100)
+ >>> print(round(turtle.xcor(), 5))
+ 64.27876
"""
return self._position[0]
def ycor(self):
- """ Return the turtle's y coordinate
- ---
- No arguments.
+ """Return the turtle's y coordinate.
Example (for a Turtle instance named turtle):
- >>> reset()
- >>> turtle.left(60)
- >>> turtle.forward(100)
- >>> print(turtle.ycor())
- 86.6025403784
+ >>> turtle.home()
+ >>> turtle.left(60)
+ >>> turtle.forward(100)
+ >>> print(round(turtle.ycor(), 5))
+ 86.60254
"""
return self._position[1]
def goto(self, x, y=None):
- """Move turtle to an absolute position.
+ """Move the turtle to an absolute position.
- Aliases: setpos | setposition | goto:
+ Aliases: goto | setpos | setposition
- Arguments:
- x -- a number or a pair/vector of numbers
- y -- a number None
+ If y is None, x must be a pair of coordinates or a Vec2D, for
+ example as returned by pos(). If the pen is down, a line is drawn.
+ The turtle's heading does not change.
- call: goto(x, y) # two coordinates
- --or: goto((x, y)) # a pair (tuple) of coordinates
- --or: goto(vec) # e.g. as returned by pos()
-
- Move turtle to an absolute position. If the pen is down,
- a line will be drawn. The turtle's orientation does not change.
+ Arguments:
+ x -- a number or a pair of numbers
+ y -- a number or None
Example (for a Turtle instance named turtle):
- >>> tp = turtle.pos()
- >>> tp
- (0.00,0.00)
- >>> turtle.setpos(60,30)
- >>> turtle.pos()
- (60.00,30.00)
- >>> turtle.setpos((20,80))
- >>> turtle.pos()
- (20.00,80.00)
- >>> turtle.setpos(tp)
- >>> turtle.pos()
- (0.00,0.00)
+ >>> tp = turtle.pos()
+ >>> tp
+ (0.00,0.00)
+ >>> turtle.goto(60,30)
+ >>> turtle.pos()
+ (60.00,30.00)
+ >>> turtle.goto((20,80))
+ >>> turtle.pos()
+ (20.00,80.00)
+ >>> turtle.goto(tp)
+ >>> turtle.pos()
+ (0.00,0.00)
"""
if y is None:
self._goto(Vec2D(*x))
@@ -1854,76 +1863,79 @@ def goto(self, x, y=None):
self._goto(Vec2D(x, y))
def home(self):
- """Move turtle to the origin - coordinates (0,0).
+ """Move the turtle to the origin, coordinates (0,0).
- No arguments.
-
- Move turtle to the origin - coordinates (0,0) and set its
- heading to its start-orientation (which depends on mode).
+ The turtle's heading is set to its start orientation, which
+ depends on the turtle mode, see mode().
Example (for a Turtle instance named turtle):
- >>> turtle.home()
+ >>> turtle.heading()
+ 90.0
+ >>> turtle.position()
+ (0.00,-10.00)
+ >>> turtle.home()
+ >>> turtle.position()
+ (0.00,0.00)
+ >>> turtle.heading()
+ 0.0
"""
self.goto(0, 0)
self.setheading(0)
def setx(self, x):
- """Set the turtle's first coordinate to x
+ """Set the turtle's x coordinate to x.
- Argument:
- x -- a number (integer or float)
+ The y coordinate is unchanged.
- Set the turtle's first coordinate to x, leave second coordinate
- unchanged.
+ Argument:
+ x -- a number
Example (for a Turtle instance named turtle):
- >>> turtle.position()
- (0.00, 240.00)
- >>> turtle.setx(10)
- >>> turtle.position()
- (10.00, 240.00)
+ >>> turtle.position()
+ (0.00,240.00)
+ >>> turtle.setx(10)
+ >>> turtle.position()
+ (10.00,240.00)
"""
self._goto(Vec2D(x, self._position[1]))
def sety(self, y):
- """Set the turtle's second coordinate to y
+ """Set the turtle's y coordinate to y.
- Argument:
- y -- a number (integer or float)
+ The x coordinate is unchanged.
- Set the turtle's first coordinate to x, second coordinate remains
- unchanged.
+ Argument:
+ y -- a number
Example (for a Turtle instance named turtle):
- >>> turtle.position()
- (0.00, 40.00)
- >>> turtle.sety(-10)
- >>> turtle.position()
- (0.00, -10.00)
+ >>> turtle.position()
+ (0.00,40.00)
+ >>> turtle.sety(-10)
+ >>> turtle.position()
+ (0.00,-10.00)
"""
self._goto(Vec2D(self._position[0], y))
def distance(self, x, y=None):
"""Return the distance from the turtle to (x,y) in turtle step units.
- Arguments:
- x -- a number or a pair/vector of numbers or a turtle instance
- y -- a number None None
+ If y is None, x must be a pair of coordinates, a Vec2D, for example
+ as returned by pos(), or another turtle.
- call: distance(x, y) # two coordinates
- --or: distance((x, y)) # a pair (tuple) of coordinates
- --or: distance(vec) # e.g. as returned by pos()
- --or: distance(mypen) # where mypen is another turtle
+ Arguments:
+ x -- a number or a pair of numbers or a turtle instance
+ y -- a number if x is a number, else None
Example (for a Turtle instance named turtle):
- >>> turtle.pos()
- (0.00,0.00)
- >>> turtle.distance(30,40)
- 50.0
- >>> pen = Turtle()
- >>> pen.forward(77)
- >>> turtle.distance(pen)
- 77.0
+ >>> turtle.home()
+ >>> turtle.distance(30,40)
+ 50.0
+ >>> turtle.distance((30,40))
+ 50.0
+ >>> joe = Turtle()
+ >>> joe.forward(77)
+ >>> turtle.distance(joe)
+ 77.0
"""
if y is not None:
pos = Vec2D(x, y)
@@ -1936,26 +1948,21 @@ def distance(self, x, y=None):
return abs(pos - self._position)
def towards(self, x, y=None):
- """Return the angle of the line from the turtle's position to (x, y).
-
- Arguments:
- x -- a number or a pair/vector of numbers or a turtle instance
- y -- a number None None
+ """Return the angle of the line from the turtle's position to (x,y).
- call: distance(x, y) # two coordinates
- --or: distance((x, y)) # a pair (tuple) of coordinates
- --or: distance(vec) # e.g. as returned by pos()
- --or: distance(mypen) # where mypen is another turtle
+ If y is None, x must be a pair of coordinates, a Vec2D, for example
+ as returned by pos(), or another turtle. The angle is measured from
+ the turtle's start orientation, which depends on the turtle mode,
+ see mode().
- Return the angle, between the line from turtle-position to position
- specified by x, y and the turtle's start orientation. (Depends on
- modes - "standard" or "logo")
+ Arguments:
+ x -- a number or a pair of numbers or a turtle instance
+ y -- a number if x is a number, else None
Example (for a Turtle instance named turtle):
- >>> turtle.pos()
- (10.00, 10.00)
- >>> turtle.towards(0,0)
- 225.0
+ >>> turtle.goto(10, 10)
+ >>> turtle.towards(0,0)
+ 225.0
"""
if y is not None:
pos = Vec2D(x, y)
@@ -1971,14 +1978,15 @@ def towards(self, x, y=None):
return (self._angleOffset + self._angleOrient*result) % self._fullcircle
def heading(self):
- """ Return the turtle's current heading.
+ """Return the turtle's current heading.
- No arguments.
+ The value depends on the turtle mode, see mode().
Example (for a Turtle instance named turtle):
- >>> turtle.left(67)
- >>> turtle.heading()
- 67.0
+ >>> turtle.home()
+ >>> turtle.left(67)
+ >>> turtle.heading()
+ 67.0
"""
x, y = self._orient
result = round(math.degrees(math.atan2(y, x)), 10) % 360.0
@@ -1986,72 +1994,63 @@ def heading(self):
return (self._angleOffset + self._angleOrient*result) % self._fullcircle
def setheading(self, to_angle):
- """Set the orientation of the turtle to to_angle.
+ """Set the turtle's heading to to_angle.
- Aliases: setheading | seth
+ Aliases: setheading | seth
- Argument:
- to_angle -- a number (integer or float)
-
- Set the orientation of the turtle to to_angle.
Here are some common directions in degrees:
- standard - mode: logo-mode:
- -------------------|--------------------
- 0 - east 0 - north
- 90 - north 90 - east
- 180 - west 180 - south
- 270 - south 270 - west
+ standard mode logo mode
+ -------------------|---------------
+ 0 - east 0 - north
+ 90 - north 90 - east
+ 180 - west 180 - south
+ 270 - south 270 - west
+
+ Argument:
+ to_angle -- a number
Example (for a Turtle instance named turtle):
- >>> turtle.setheading(90)
- >>> turtle.heading()
- 90
+ >>> turtle.setheading(90)
+ >>> turtle.heading()
+ 90.0
"""
- angle = (to_angle - self.heading())*self._angleOrient
+ angle = (to_angle - self.heading()) * self._angleOrient
full = self._fullcircle
angle = (angle+full/2.)%full - full/2.
self._rotate(angle)
def circle(self, radius, extent = None, steps = None):
- """ Draw a circle with given radius.
+ """Draw a circle with the given radius.
- Arguments:
- radius -- a number
- extent (optional) -- a number
- steps (optional) -- an integer
-
- Draw a circle with given radius. The center is radius units left
- of the turtle; extent - an angle - determines which part of the
- circle is drawn. If extent is not given, draw the entire circle.
- If extent is not a full circle, one endpoint of the arc is the
- current pen position. Draw the arc in counterclockwise direction
- if radius is positive, otherwise in clockwise direction. Finally
- the direction of the turtle is changed by the amount of extent.
+ The center is radius units left of the turtle; extent, an angle,
+ determines which part of the circle is drawn. If extent is not
+ given, draw the entire circle. If extent is not a full circle, one
+ endpoint of the arc is the current pen position. Draw the arc in
+ the counterclockwise direction if radius is positive, otherwise in
+ the clockwise direction. Finally, the turtle's heading is changed by
+ extent.
As the circle is approximated by an inscribed regular polygon,
- steps determines the number of steps to use. If not given,
- it will be calculated automatically. Maybe used to draw regular
+ steps determines the number of steps to use. If not given, it
+ will be calculated automatically. May be used to draw regular
polygons.
- call: circle(radius) # full circle
- --or: circle(radius, extent) # arc
- --or: circle(radius, extent, steps)
- --or: circle(radius, steps=6) # 6-sided polygon
+ Arguments:
+ radius -- a number
+ extent -- a number or None
+ steps -- an integer or None
Example (for a Turtle instance named turtle):
- >>> turtle.circle(50)
- >>> turtle.circle(120, 180) # semicircle
+ >>> turtle.circle(50)
+ >>> turtle.circle(120, 180) # draw a semicircle
"""
- if self.undobuffer:
- self.undobuffer.push(["seq"])
- self.undobuffer.cumulate = True
speed = self.speed()
if extent is None:
extent = self._fullcircle
if steps is None:
frac = abs(extent)/self._fullcircle
- steps = 1+int(min(11+abs(radius)/6.0, 59.0)*frac)
+ steps = 1 + int(min(11 + abs(radius) / 6.0, 59.0) * frac)
w = 1.0 * extent / steps
w2 = 0.5 * w
l = 2.0 * radius * math.sin(math.radians(w2)*self._degreesPerAU)
@@ -2059,31 +2058,32 @@ def circle(self, radius, extent = None, steps = None):
l, w, w2 = -l, -w, -w2
tr = self._tracer()
dl = self._delay()
- if speed == 0:
- self._tracer(0, 0)
- else:
- self.speed(0)
- self._rotate(w2)
- for i in range(steps):
+ with self._undo_sequence():
+ if speed == 0:
+ self._tracer(0, 0)
+ else:
+ self.speed(0)
+ self._rotate(w2)
+ for i in range(steps):
+ self.speed(speed)
+ self._go(l)
+ self.speed(0)
+ self._rotate(w)
+ self._rotate(-w2)
+ if speed == 0:
+ self._tracer(tr, dl)
self.speed(speed)
- self._go(l)
- self.speed(0)
- self._rotate(w)
- self._rotate(-w2)
- if speed == 0:
- self._tracer(tr, dl)
- self.speed(speed)
- if self.undobuffer:
- self.undobuffer.cumulate = False
-## three dummy methods to be implemented by child class:
+ # Three dummy methods to be implemented by the child class:
def speed(self, s=0):
- """dummy method - to be overwritten by child class"""
+ """Dummy method - to be overwritten by the child class."""
def _tracer(self, a=None, b=None):
- """dummy method - to be overwritten by child class"""
+ """Dummy method - to be overwritten by the child class."""
def _delay(self, n=None):
- """dummy method - to be overwritten by child class"""
+ """Dummy method - to be overwritten by the child class."""
+
+ # Aliases for the commonly used commands:
fd = forward
bk = back
@@ -2096,10 +2096,12 @@ def _delay(self, n=None):
seth = setheading
-class TPen(object):
+class TPen:
"""Drawing part of the RawTurtle.
+
Implements drawing properties.
"""
+
def __init__(self, resizemode=_CFG["resizemode"]):
self._resizemode = resizemode # or "user" or "noresize"
self.undobuffer = None
@@ -2120,26 +2122,29 @@ def _reset(self, pencolor=_CFG["pencolor"],
self._outlinewidth = 1
def resizemode(self, rmode=None):
- """Set resizemode to one of the values: "auto", "user", "noresize".
-
- (Optional) Argument:
- rmode -- one of the strings "auto", "user", "noresize"
-
- Different resizemodes have the following effects:
- - "auto" adapts the appearance of the turtle
- corresponding to the value of pensize.
- - "user" adapts the appearance of the turtle according to the
- values of stretchfactor and outlinewidth (outline),
- which are set by shapesize()
- - "noresize" no adaption of the turtle's appearance takes place.
- If no argument is given, return current resizemode.
- resizemode("user") is called by a call of shapesize with arguments.
-
-
- Examples (for a Turtle instance named turtle):
- >>> turtle.resizemode("noresize")
- >>> turtle.resizemode()
- 'noresize'
+ """Set the resizemode to "auto", "user" or "noresize".
+
+ If rmode is not given, return the current resizemode. The
+ different resizemodes have the following effects:
+
+ - "auto": the turtle is resized according to the value of
+ pensize().
+ - "user": the turtle is resized according to the stretch factors
+ and outline width, which are set by shapesize().
+ - "noresize": the turtle is not resized.
+
+ resizemode("user") is called by shapesize() when used with
+ arguments.
+
+ Argument:
+ rmode -- a string or None
+
+ Example (for a Turtle instance named turtle):
+ >>> turtle.resizemode()
+ 'noresize'
+ >>> turtle.resizemode("auto")
+ >>> turtle.resizemode()
+ 'auto'
"""
if rmode is None:
return self._resizemode
@@ -2148,103 +2153,105 @@ def resizemode(self, rmode=None):
self.pen(resizemode=rmode)
def pensize(self, width=None):
- """Set or return the line thickness.
+ """Return or set the line thickness.
- Aliases: pensize | width
+ Aliases: pensize | width
- Argument:
- width -- positive number
+ If width is not given, return the current pensize. If resizemode
+ is set to "auto" and the turtle shape is a polygon, that polygon is
+ drawn with the same line thickness.
- Set the line thickness to width or return it. If resizemode is set
- to "auto" and turtleshape is a polygon, that polygon is drawn with
- the same line thickness. If no argument is given, current pensize
- is returned.
+ Argument:
+ width -- a positive number or None
Example (for a Turtle instance named turtle):
- >>> turtle.pensize()
- 1
- >>> turtle.pensize(10) # from here on lines of width 10 are drawn
+ >>> turtle.pensize()
+ 1
+ >>> turtle.pensize(10) # from here on lines of width 10 are drawn
"""
if width is None:
return self._pensize
self.pen(pensize=width)
-
def penup(self):
- """Pull the pen up -- no drawing when moving.
+ """Lift the pen.
Aliases: penup | pu | up
- No argument
-
- Example (for a Turtle instance named turtle):
- >>> turtle.penup()
+ The turtle does not draw when it moves.
"""
if not self._drawing:
return
self.pen(pendown=False)
def pendown(self):
- """Pull the pen down -- drawing when moving.
+ """Lower the pen.
Aliases: pendown | pd | down
- No argument.
-
- Example (for a Turtle instance named turtle):
- >>> turtle.pendown()
+ The turtle draws a line when it moves.
"""
if self._drawing:
return
self.pen(pendown=True)
def isdown(self):
- """Return True if pen is down, False if it's up.
-
- No argument.
+ """Return True if the pen is down, False if it's up.
Example (for a Turtle instance named turtle):
- >>> turtle.penup()
- >>> turtle.isdown()
- False
- >>> turtle.pendown()
- >>> turtle.isdown()
- True
+ >>> turtle.penup()
+ >>> turtle.isdown()
+ False
+ >>> turtle.pendown()
+ >>> turtle.isdown()
+ True
"""
return self._drawing
def speed(self, speed=None):
- """ Return or set the turtle's speed.
+ """Return or set the turtle's speed.
- Optional argument:
- speed -- an integer in the range 0..10 or a speedstring (see below)
+ If speed is not given, return the current speed. Otherwise set the
+ turtle's speed to an integer from 0 to 10. A number above 0.5 and
+ below 10.5 is rounded to the nearest integer. Any other number sets
+ the speed to 0. You can also use these names instead of numbers:
- Set the turtle's speed to an integer value in the range 0 .. 10.
- If no argument is given: return current speed.
+ "fastest": 0
+ "fast": 10
+ "normal": 6
+ "slow": 3
+ "slowest": 1
- If input is a number greater than 10 or smaller than 0.5,
- speed is set to 0.
- Speedstrings are mapped to speedvalues in the following way:
- 'fastest' : 0
- 'fast' : 10
- 'normal' : 6
- 'slow' : 3
- 'slowest' : 1
- speeds from 1 to 10 enforce increasingly faster animation of
- line drawing and turtle turning.
+ Speeds from 1 to 10 give increasingly faster animation of line
+ drawing and turtle turning. A speed of 0 means that no animation
+ takes place: forward() and back() make the turtle jump, and
+ likewise left() and right() make the turtle turn instantly.
- Attention:
- speed = 0 : *no* animation takes place. forward/back makes turtle jump
- and likewise left/right make the turtle turn instantly.
+ Argument:
+ speed -- an integer, a string or None
Example (for a Turtle instance named turtle):
- >>> turtle.speed(3)
- """
- speeds = {'fastest':0, 'fast':10, 'normal':6, 'slow':3, 'slowest':1 }
+ >>> turtle.speed()
+ 3
+ >>> turtle.speed('normal')
+ >>> turtle.speed()
+ 6
+ >>> turtle.speed(9)
+ >>> turtle.speed()
+ 9
+ """
+ speed_strings = {
+ 'fastest': 0,
+ 'fast': 10,
+ 'normal': 6,
+ 'slow': 3,
+ 'slowest': 1,
+ }
+
if speed is None:
return self._speed
- if speed in speeds:
- speed = speeds[speed]
+ if speed in speed_strings:
+ speed = speed_strings[speed]
elif 0.5 < speed < 10.5:
speed = int(round(speed))
else:
@@ -2254,32 +2261,30 @@ def speed(self, speed=None):
def color(self, *args):
"""Return or set the pencolor and fillcolor.
- Arguments:
- Several input formats are allowed.
- They use 0 to 3 arguments as follows:
+ Several input formats are allowed. They use 0 to 3 arguments as follows:
- color()
Return the current pencolor and the current fillcolor as
a pair of color specification strings or tuples as returned
by pencolor() and fillcolor().
- color(colorstring), color((r,g,b)), color(r,g,b)
- Inputs as in pencolor(), set both, fillcolor and pencolor,
- to the given value.
+ Inputs as in pencolor(). Set both the pencolor and the
+ fillcolor to the given value.
- color(colorstring1, colorstring2), color((r1,g1,b1), (r2,g2,b2))
Equivalent to pencolor(colorstring1) and fillcolor(colorstring2)
and analogously if the other input format is used.
- If turtleshape is a polygon, outline and interior of that polygon
- is drawn with the newly set colors.
- For more info see: pencolor, fillcolor
+ If the turtle shape is a polygon, the outline and interior of that
+ polygon are drawn with the newly set colors. For more information,
+ see pencolor() and fillcolor().
Example (for a Turtle instance named turtle):
- >>> turtle.color('red', 'green')
- >>> turtle.color()
- ('red', 'green')
- >>> colormode(255)
- >>> color(('#285078', '#a0c8f0'))
- >>> color()
- ((40.0, 80.0, 120.0), (160.0, 200.0, 240.0))
+ >>> turtle.color("red", "green")
+ >>> turtle.color()
+ ('red', 'green')
+ >>> colormode(255)
+ >>> turtle.color("#285078", "#a0c8f0")
+ >>> turtle.color()
+ ((40.0, 80.0, 120.0), (160.0, 200.0, 240.0))
"""
if args:
l = len(args)
@@ -2296,37 +2301,36 @@ def color(self, *args):
return self._color(self._pencolor), self._color(self._fillcolor)
def pencolor(self, *args):
- """ Return or set the pencolor.
+ """Return or set the pencolor.
- Arguments:
Four input formats are allowed:
- pencolor()
Return the current pencolor as color specification string or
as a tuple (see example). May be used as input to another
- color/pencolor/fillcolor/bgcolor call.
+ color(), pencolor(), fillcolor() or bgcolor() call.
- pencolor(colorstring)
- Set pencolor to colorstring, which is a Tk color
+ Set the pencolor to colorstring, which is a Tk color
specification string, such as "red", "yellow", or "#33cc8c".
- pencolor((r, g, b))
- Set pencolor to the RGB color represented by the tuple of
- r, g, and b. Each of r, g, and b must be in the range
- 0..colormode, where colormode is either 1.0 or 255 (see
+ Set the pencolor to the RGB color represented by the tuple of
+ r, g, and b. Each of r, g, and b must be between 0 and
+ colormode, where colormode is either 1.0 or 255 (see
colormode()).
- pencolor(r, g, b)
- Set pencolor to the RGB color represented by r, g, and b.
- Each of r, g, and b must be in the range 0..colormode.
+ Set the pencolor to the RGB color represented by r, g, and b.
+ Each of r, g, and b must be between 0 and colormode.
- If turtleshape is a polygon, the outline of that polygon is drawn
- with the newly set pencolor.
+ If the turtle shape is a polygon, the outline of that polygon is
+ drawn with the newly set pencolor.
Example (for a Turtle instance named turtle):
- >>> turtle.pencolor('brown')
- >>> turtle.pencolor()
- 'brown'
- >>> colormode(255)
- >>> turtle.pencolor('#32c18f')
- >>> turtle.pencolor()
- (50.0, 193.0, 143.0)
+ >>> turtle.pencolor("brown")
+ >>> turtle.pencolor()
+ 'brown'
+ >>> colormode(255)
+ >>> turtle.pencolor("#32c18f")
+ >>> turtle.pencolor()
+ (50.0, 193.0, 143.0)
"""
if args:
color = self._colorstr(args)
@@ -2337,37 +2341,36 @@ def pencolor(self, *args):
return self._color(self._pencolor)
def fillcolor(self, *args):
- """ Return or set the fillcolor.
+ """Return or set the fillcolor.
- Arguments:
Four input formats are allowed:
- fillcolor()
Return the current fillcolor as color specification string,
possibly in tuple format (see example). May be used as
- input to another color/pencolor/fillcolor/bgcolor call.
+ input to another color(), pencolor(), fillcolor() or bgcolor() call.
- fillcolor(colorstring)
- Set fillcolor to colorstring, which is a Tk color
+ Set the fillcolor to colorstring, which is a Tk color
specification string, such as "red", "yellow", or "#33cc8c".
- fillcolor((r, g, b))
- Set fillcolor to the RGB color represented by the tuple of
- r, g, and b. Each of r, g, and b must be in the range
- 0..colormode, where colormode is either 1.0 or 255 (see
+ Set the fillcolor to the RGB color represented by the tuple of
+ r, g, and b. Each of r, g, and b must be between 0 and
+ colormode, where colormode is either 1.0 or 255 (see
colormode()).
- fillcolor(r, g, b)
- Set fillcolor to the RGB color represented by r, g, and b.
- Each of r, g, and b must be in the range 0..colormode.
+ Set the fillcolor to the RGB color represented by r, g, and b.
+ Each of r, g, and b must be between 0 and colormode.
- If turtleshape is a polygon, the interior of that polygon is drawn
- with the newly set fillcolor.
+ If the turtle shape is a polygon, the interior of that polygon is
+ drawn with the newly set fillcolor.
Example (for a Turtle instance named turtle):
- >>> turtle.fillcolor('violet')
- >>> turtle.fillcolor()
- 'violet'
- >>> colormode(255)
- >>> turtle.fillcolor('#ffffff')
- >>> turtle.fillcolor()
- (255.0, 255.0, 255.0)
+ >>> turtle.fillcolor("violet")
+ >>> turtle.fillcolor()
+ 'violet'
+ >>> colormode(255)
+ >>> turtle.fillcolor("#ffffff")
+ >>> turtle.fillcolor()
+ (255.0, 255.0, 255.0)
"""
if args:
color = self._colorstr(args)
@@ -2378,7 +2381,8 @@ def fillcolor(self, *args):
return self._color(self._fillcolor)
def teleport(self, x=None, y=None, *, fill_gap: bool = False) -> None:
- """To be overwritten by child class RawTurtle.
+ """To be overwritten by the child class RawTurtle.
+
Includes no TNavigator references.
"""
pendown = self.isdown()
@@ -2387,92 +2391,78 @@ def teleport(self, x=None, y=None, *, fill_gap: bool = False) -> None:
self.pen(pendown=pendown)
def showturtle(self):
- """Makes the turtle visible.
+ """Make the turtle visible.
Aliases: showturtle | st
-
- No argument.
-
- Example (for a Turtle instance named turtle):
- >>> turtle.hideturtle()
- >>> turtle.showturtle()
"""
self.pen(shown=True)
def hideturtle(self):
- """Makes the turtle invisible.
+ """Make the turtle invisible.
Aliases: hideturtle | ht
- No argument.
-
- It's a good idea to do this while you're in the
- middle of a complicated drawing, because hiding
- the turtle speeds up the drawing observably.
-
- Example (for a Turtle instance named turtle):
- >>> turtle.hideturtle()
+ If the pen is down, movement still draws.
"""
self.pen(shown=False)
def isvisible(self):
- """Return True if the Turtle is shown, False if it's hidden.
-
- No argument.
+ """Return True if the turtle is visible, False if it's hidden.
Example (for a Turtle instance named turtle):
- >>> turtle.hideturtle()
- >>> print(turtle.isvisible())
- False
+ >>> turtle.hideturtle()
+ >>> turtle.isvisible()
+ False
+ >>> turtle.showturtle()
+ >>> turtle.isvisible()
+ True
"""
return self._shown
def pen(self, pen=None, **pendict):
"""Return or set the pen's attributes.
+ The attributes are returned as a dictionary with the following
+ keys and values:
+
+ - "shown": True or False
+ - "pendown": True or False
+ - "pencolor": a color string or a color tuple
+ - "fillcolor": a color string or a color tuple
+ - "pensize": a positive number
+ - "speed": a number from 0 to 10
+ - "resizemode": "auto", "user" or "noresize"
+ - "stretchfactor": a pair of positive numbers
+ - "shearfactor": a number
+ - "outline": a positive number
+ - "tilt": a number
+
+ Such a dictionary can be passed as pen to restore a former pen
+ state. The attributes can also be given as keyword arguments,
+ which can be used to set several of them in one statement.
+
Arguments:
- pen -- a dictionary with some or all of the below listed keys.
- **pendict -- one or more keyword-arguments with the below
- listed keys as keywords.
-
- Return or set the pen's attributes in a 'pen-dictionary'
- with the following key/value pairs:
- "shown" : True/False
- "pendown" : True/False
- "pencolor" : color-string or color-tuple
- "fillcolor" : color-string or color-tuple
- "pensize" : positive number
- "speed" : number in range 0..10
- "resizemode" : "auto" or "user" or "noresize"
- "stretchfactor": (positive number, positive number)
- "shearfactor": number
- "outline" : positive number
- "tilt" : number
-
- This dictionary can be used as argument for a subsequent
- pen()-call to restore the former pen-state. Moreover one
- or more of these attributes can be provided as keyword-arguments.
- This can be used to set several pen attributes in one statement.
-
-
- Examples (for a Turtle instance named turtle):
- >>> turtle.pen(fillcolor="black", pencolor="red", pensize=10)
- >>> turtle.pen()
- {'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,
- 'pencolor': 'red', 'pendown': True, 'fillcolor': 'black',
- 'stretchfactor': (1,1), 'speed': 3, 'shearfactor': 0.0}
- >>> penstate=turtle.pen()
- >>> turtle.color("yellow","")
- >>> turtle.penup()
- >>> turtle.pen()
- {'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,
- 'pencolor': 'yellow', 'pendown': False, 'fillcolor': '',
- 'stretchfactor': (1,1), 'speed': 3, 'shearfactor': 0.0}
- >>> p.pen(penstate, fillcolor="green")
- >>> p.pen()
- {'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,
- 'pencolor': 'red', 'pendown': True, 'fillcolor': 'green',
- 'stretchfactor': (1,1), 'speed': 3, 'shearfactor': 0.0}
+ pen -- a dictionary or None
+ pendict -- keyword arguments with the keys above
+
+ Example (for a Turtle instance named turtle):
+ >>> turtle.pen(fillcolor="black", pencolor="red", pensize=10)
+ >>> turtle.pen()
+ {'shown': True, 'pendown': True, 'pencolor': 'red',
+ 'fillcolor': 'black', 'pensize': 10, 'speed': 3,
+ 'resizemode': 'noresize', 'stretchfactor': (1.0, 1.0),
+ 'shearfactor': 0.0, 'outline': 1, 'tilt': 0.0}
+ >>> penstate = turtle.pen()
+ >>> turtle.color("yellow", "")
+ >>> turtle.penup()
+ >>> turtle.pen()["pencolor"]
+ 'yellow'
+ >>> # restore the saved pen state, but with a green fill
+ >>> turtle.pen(penstate, fillcolor="green")
+ >>> turtle.pen()["pencolor"]
+ 'red'
+ >>> turtle.pen()["fillcolor"]
+ 'green'
"""
_pd = {"shown" : self._shown,
"pendown" : self._drawing,
@@ -2552,16 +2542,18 @@ def pen(self, pen=None, **pendict):
-scx*sa, scy*(ca - shf*sa))
self._update()
-## three dummy methods to be implemented by child class:
+ # Three dummy methods to be implemented by the child class:
def _newLine(self, usePos = True):
- """dummy method - to be overwritten by child class"""
+ """Dummy method - to be overwritten by the child class."""
def _update(self, count=True, forced=False):
- """dummy method - to be overwritten by child class"""
+ """Dummy method - to be overwritten by the child class."""
def _color(self, args):
- """dummy method - to be overwritten by child class"""
+ """Dummy method - to be overwritten by the child class."""
def _colorstr(self, args):
- """dummy method - to be overwritten by child class"""
+ """Dummy method - to be overwritten by the child class."""
+
+ # Aliases for the commonly used commands:
width = pensize
up = penup
@@ -2572,9 +2564,8 @@ def _colorstr(self, args):
ht = hideturtle
-class _TurtleImage(object):
- """Helper class: Datatype to store Turtle attributes
- """
+class _TurtleImage:
+ """Helper class holding the canvas items that display a turtle's shape."""
def __init__(self, screen, shapeIndex):
self.screen = screen
@@ -2604,9 +2595,10 @@ def _setshape(self, shapeIndex):
class RawTurtle(TPen, TNavigator):
- """Animation part of the RawTurtle.
- Puts RawTurtle upon a TurtleScreen and provides tools for
- its animation.
+ """A turtle that draws on the given canvas or TurtleScreen.
+
+ Combines the navigation part (TNavigator) and the drawing part (TPen)
+ and adds the animation of the turtle on the screen.
"""
screens = []
@@ -2629,7 +2621,7 @@ def __init__(self, canvas=None,
self.screen = TurtleScreen(canvas)
RawTurtle.screens.append(self.screen)
else:
- raise TurtleGraphicsError("bad canvas argument %s" % canvas)
+ raise TurtleGraphicsError(f"Bad canvas argument {canvas!r}")
screen = self.screen
TNavigator.__init__(self, screen.mode())
@@ -2651,23 +2643,22 @@ def __init__(self, canvas=None,
self._update()
def reset(self):
- """Delete the turtle's drawings and restore its default values.
+ """Delete the turtle's drawings and re-center the turtle.
- No argument.
-
- Delete the turtle's drawings from the screen, re-center the turtle
- and set variables to the default values.
+ The turtle's settings are restored to their default values.
Example (for a Turtle instance named turtle):
- >>> turtle.position()
- (0.00,-22.00)
- >>> turtle.heading()
- 100.0
- >>> turtle.reset()
- >>> turtle.position()
- (0.00,0.00)
- >>> turtle.heading()
- 0.0
+ >>> turtle.goto(0,-22)
+ >>> turtle.left(100)
+ >>> turtle.position()
+ (0.00,-22.00)
+ >>> turtle.heading()
+ 100.0
+ >>> turtle.reset()
+ >>> turtle.position()
+ (0.00,0.00)
+ >>> turtle.heading()
+ 0.0
"""
TNavigator.reset(self)
TPen._reset(self)
@@ -2676,18 +2667,17 @@ def reset(self):
self._update()
def setundobuffer(self, size):
- """Set or disable undobuffer.
+ """Set or disable the undo buffer.
- Argument:
- size -- an integer or None
+ If size is an integer, an empty undo buffer of the given size is
+ installed. size is the maximum number of turtle actions that can
+ be undone by undo(). If size is None, the undo buffer is disabled.
- If size is an integer an empty undobuffer of given size is installed.
- Size gives the maximum number of turtle-actions that can be undone
- by the undo() function.
- If size is None, no undobuffer is present.
+ Argument:
+ size -- an integer or None
Example (for a Turtle instance named turtle):
- >>> turtle.setundobuffer(42)
+ >>> turtle.setundobuffer(42)
"""
if size is None or size <= 0:
self.undobuffer = None
@@ -2695,20 +2685,18 @@ def setundobuffer(self, size):
self.undobuffer = Tbuffer(size)
def undobufferentries(self):
- """Return count of entries in the undobuffer.
-
- No argument.
+ """Return the number of entries in the undo buffer.
Example (for a Turtle instance named turtle):
- >>> while undobufferentries():
- ... undo()
+ >>> while turtle.undobufferentries():
+ ... turtle.undo()
"""
if self.undobuffer is None:
return 0
return self.undobuffer.nr_of_items()
def _clear(self):
- """Delete all of pen's drawings"""
+ """Delete all of the pen's drawings."""
self._fillitem = self._fillpath = None
for item in self.items:
self.screen._delete(item)
@@ -2722,16 +2710,10 @@ def _clear(self):
def clear(self):
- """Delete the turtle's drawings from the screen. Do not move turtle.
-
- No arguments.
+ """Delete the turtle's drawings from the screen.
- Delete the turtle's drawings from the screen. Do not move turtle.
- State and position of the turtle as well as drawings of other
- turtles are not affected.
-
- Examples (for a Turtle instance named turtle):
- >>> turtle.clear()
+ The state and position of the turtle as well as the drawings of
+ other turtles are not affected.
"""
self._clear()
self._update()
@@ -2745,8 +2727,7 @@ def _update_data(self):
self._pencolor, self._pensize)
def _update(self):
- """Perform a Turtle-data update.
- """
+ """Perform a Turtle-data update."""
screen = self.screen
if screen._tracing == 0:
return
@@ -2763,24 +2744,7 @@ def _update(self):
screen._update()
def _tracer(self, flag=None, delay=None):
- """Turns turtle animation on/off and set delay for update drawings.
-
- Optional arguments:
- n -- nonnegative integer
- delay -- nonnegative integer
-
- If n is given, only each n-th regular screen update is really performed.
- (Can be used to accelerate the drawing of complex graphics.)
- Second arguments sets delay value (see RawTurtle.delay())
-
- Example (for a Turtle instance named turtle):
- >>> turtle.tracer(8, 25)
- >>> dist = 2
- >>> for i in range(200):
- ... turtle.fd(dist)
- ... turtle.rt(90)
- ... dist += 2
- """
+ """Forward flag and delay to the screen's tracer() method."""
return self.screen.tracer(flag, delay)
def _color(self, args):
@@ -2790,8 +2754,7 @@ def _colorstr(self, args):
return self.screen._colorstr(args)
def _cc(self, args):
- """Convert colortriples to hexstrings.
- """
+ """Convert colortriples to hexstrings."""
if isinstance(args, str):
return args
try:
@@ -2805,64 +2768,60 @@ def _cc(self, args):
return "#%02x%02x%02x" % (r, g, b)
def teleport(self, x=None, y=None, *, fill_gap: bool = False) -> None:
- """Instantly move turtle to an absolute position.
+ """Teleport, or instantly move, the turtle to an absolute position.
+
+ Unlike goto(), no line is drawn. If x or y is not given, that
+ coordinate is kept as it is. The turtle's heading does not change.
+
+ If the turtle is filling a shape, the shape drawn so far is
+ finished and filled before teleporting, and filling starts again
+ at the new position. Pass fill_gap=True to keep filling one shape
+ instead. The teleport then counts as an edge of the shape, as it
+ would with goto().
Arguments:
- x -- a number or None
- y -- a number None
- fill_gap -- a boolean This argument must be specified by name.
-
- call: teleport(x, y) # two coordinates
- --or: teleport(x) # teleport to x position, keeping y as is
- --or: teleport(y=y) # teleport to y position, keeping x as is
- --or: teleport(x, y, fill_gap=True)
- # teleport but fill the gap in between
-
- Move turtle to an absolute position. Unlike goto(x, y), a line will not
- be drawn. The turtle's orientation does not change. If currently
- filling, the polygon(s) teleported from will be filled after leaving,
- and filling will begin again after teleporting. This can be disabled
- with fill_gap=True, which makes the imaginary line traveled during
- teleporting act as a fill barrier like in goto(x, y).
+ x -- a number or None
+ y -- a number or None
+ fill_gap -- a boolean
Example (for a Turtle instance named turtle):
- >>> tp = turtle.pos()
- >>> tp
- (0.00,0.00)
- >>> turtle.teleport(60)
- >>> turtle.pos()
- (60.00,0.00)
- >>> turtle.teleport(y=10)
- >>> turtle.pos()
- (60.00,10.00)
- >>> turtle.teleport(20, 30)
- >>> turtle.pos()
- (20.00,30.00)
+ >>> tp = turtle.pos()
+ >>> tp
+ (0.00,0.00)
+ >>> turtle.teleport(60)
+ >>> turtle.pos()
+ (60.00,0.00)
+ >>> turtle.teleport(y=10)
+ >>> turtle.pos()
+ (60.00,10.00)
+ >>> turtle.teleport(20, 30)
+ >>> turtle.pos()
+ (20.00,30.00)
"""
pendown = self.isdown()
was_filling = self.filling()
- if pendown:
- self.pen(pendown=False)
- if was_filling and not fill_gap:
- self.end_fill()
- new_x = x if x is not None else self._position[0]
- new_y = y if y is not None else self._position[1]
- self._position = Vec2D(new_x, new_y)
- self.pen(pendown=pendown)
- if was_filling and not fill_gap:
- self.begin_fill()
+ with self._undo_sequence():
+ if pendown:
+ self.pen(pendown=False)
+ if was_filling and not fill_gap:
+ self.end_fill()
+ new_x = x if x is not None else self._position[0]
+ new_y = y if y is not None else self._position[1]
+ if self.undobuffer:
+ self.undobuffer.push(("teleport", self._position))
+ self._position = Vec2D(new_x, new_y)
+ self.pen(pendown=pendown)
+ if was_filling and not fill_gap:
+ self.begin_fill()
def clone(self):
"""Create and return a clone of the turtle.
- No argument.
+ The clone has the same position, heading and turtle properties.
- Create and return a clone of the turtle with same position, heading
- and turtle properties.
-
- Example (for a Turtle instance named mick):
- mick = Turtle()
- joe = mick.clone()
+ Example:
+ >>> leonel = Turtle()
+ >>> marco = leonel.clone()
"""
screen = self.screen
self._newLine(self._drawing)
@@ -2893,24 +2852,23 @@ def clone(self):
return q
def shape(self, name=None):
- """Set turtle shape to shape with given name / return current shapename.
+ """Set the turtle shape to the named shape.
- Optional argument:
- name -- a string, which is a valid shapename
+ If name is not given, return the name of the current shape. The
+ shape must exist in the TurtleScreen's shape list. Initially
+ there are the following shapes: "arrow", "turtle", "circle",
+ "square", "triangle" and "classic". To add shapes, see the Screen
+ method register_shape().
- Set turtle shape to shape with given name or, if name is not given,
- return name of current shape.
- Shape with name must exist in the TurtleScreen's shape dictionary.
- Initially there are the following polygon shapes:
- 'arrow', 'turtle', 'circle', 'square', 'triangle', 'classic'.
- To learn about how to deal with shapes see Screen-method register_shape.
+ Argument:
+ name -- a string or None
Example (for a Turtle instance named turtle):
- >>> turtle.shape()
- 'arrow'
- >>> turtle.shape("turtle")
- >>> turtle.shape()
- 'turtle'
+ >>> turtle.shape()
+ 'classic'
+ >>> turtle.shape("turtle")
+ >>> turtle.shape()
+ 'turtle'
"""
if name is None:
return self.turtle.shapeIndex
@@ -2920,25 +2878,39 @@ def shape(self, name=None):
self._update()
def shapesize(self, stretch_wid=None, stretch_len=None, outline=None):
- """Set/return turtle's stretchfactors/outline. Set resizemode to "user".
-
- Optional arguments:
- stretch_wid : positive number
- stretch_len : positive number
- outline : positive number
-
- Return or set the pen's attributes x/y-stretchfactors and/or outline.
- Set resizemode to "user".
- If and only if resizemode is set to "user", the turtle will be displayed
- stretched according to its stretchfactors:
- stretch_wid is stretchfactor perpendicular to orientation
- stretch_len is stretchfactor in direction of turtles orientation.
- outline determines the width of the shapes's outline.
-
- Examples (for a Turtle instance named turtle):
- >>> turtle.resizemode("user")
- >>> turtle.shapesize(5, 5, 12)
- >>> turtle.shapesize(outline=8)
+ """Return or set the turtle's stretch factors and outline width.
+
+ Aliases: shapesize | turtlesize
+
+ If no arguments are given, return the current values. Otherwise
+ set resizemode to "user", so that the turtle is displayed
+ stretched according to its stretch factors:
+
+ - stretch_wid: the stretch factor perpendicular to the turtle's
+ heading
+ - stretch_len: the stretch factor in the direction of the
+ turtle's heading
+ - outline: the width of the shape's outline
+
+ For example, shapesize(2, 1) makes the turtle twice as wide
+ without changing its length. If only stretch_wid is given,
+ stretch_len is set to the same value.
+
+ Arguments:
+ stretch_wid -- a positive number or None
+ stretch_len -- a positive number or None
+ outline -- a positive number or None
+
+ Example (for a Turtle instance named turtle):
+ >>> turtle.shapesize()
+ (1.0, 1.0, 1)
+ >>> turtle.resizemode("user")
+ >>> turtle.shapesize(5, 5, 12)
+ >>> turtle.shapesize()
+ (5, 5, 12)
+ >>> turtle.shapesize(outline=8)
+ >>> turtle.shapesize()
+ (5, 5, 8)
"""
if stretch_wid is stretch_len is outline is None:
stretch_wid, stretch_len = self._stretchfactor
@@ -2960,55 +2932,60 @@ def shapesize(self, stretch_wid=None, stretch_len=None, outline=None):
stretchfactor=stretchfactor, outline=outline)
def shearfactor(self, shear=None):
- """Set or return the current shearfactor.
-
- Optional argument: shear -- number, tangent of the shear angle
-
- Shear the turtleshape according to the given shearfactor shear,
- which is the tangent of the shear angle. DO NOT change the
- turtle's heading (direction of movement).
- If shear is not given: return the current shearfactor, i. e. the
- tangent of the shear angle, by which lines parallel to the
- heading of the turtle are sheared.
-
- Examples (for a Turtle instance named turtle):
- >>> turtle.shape("circle")
- >>> turtle.shapesize(5,2)
- >>> turtle.shearfactor(0.5)
- >>> turtle.shearfactor()
- >>> 0.5
+ """Return or set the current shear factor.
+
+ Shearing slants the turtle shape, like the slant of italic
+ letters. The shear factor says how much it is slanted: 0 is not
+ slanted at all, and the larger the number, the stronger the
+ slant. Negative numbers slant the other way. If shear is not
+ given, return the current shear factor. Otherwise slant the
+ turtle shape accordingly and set resizemode to "user". The
+ turtle's heading does not change. Precisely, the shear factor is
+ the tangent of the shear angle.
+
+ Argument:
+ shear -- a number or None
+
+ Example (for a Turtle instance named turtle):
+ >>> turtle.shape("circle")
+ >>> turtle.shapesize(5,2)
+ >>> turtle.shearfactor(0.5)
+ >>> turtle.shearfactor()
+ 0.5
"""
if shear is None:
return self._shearfactor
self.pen(resizemode="user", shearfactor=shear)
def tiltangle(self, angle=None):
- """Set or return the current tilt-angle.
-
- Optional argument: angle -- number
-
- Rotate the turtleshape to point in the direction specified by angle,
- regardless of its current tilt-angle. DO NOT change the turtle's
- heading (direction of movement).
- If angle is not given: return the current tilt-angle, i. e. the angle
- between the orientation of the turtleshape and the heading of the
- turtle (its direction of movement).
-
- Examples (for a Turtle instance named turtle):
- >>> turtle.shape("circle")
- >>> turtle.shapesize(5, 2)
- >>> turtle.tiltangle()
- 0.0
- >>> turtle.tiltangle(45)
- >>> turtle.tiltangle()
- 45.0
- >>> turtle.stamp()
- >>> turtle.fd(50)
- >>> turtle.tiltangle(-45)
- >>> turtle.tiltangle()
- 315.0
- >>> turtle.stamp()
- >>> turtle.fd(50)
+ """Return or set the current tilt angle.
+
+ The tilt angle is the angle between the direction the turtle shape
+ points in and the direction the turtle moves in. Normally the
+ shape points in the direction of movement, so the tilt angle is
+ 0. If angle is given, turn the turtle shape to that tilt angle, no
+ matter what it was before, and set resizemode to "user". The
+ turtle's heading does not change. If angle is not given, return
+ the current tilt angle.
+
+ Argument:
+ angle -- a number or None
+
+ Example (for a Turtle instance named turtle):
+ >>> turtle.shape("circle")
+ >>> turtle.shapesize(5, 2)
+ >>> turtle.tiltangle()
+ 0.0
+ >>> turtle.tiltangle(45)
+ >>> turtle.tiltangle()
+ 45.0
+ >>> stamp_id = turtle.stamp()
+ >>> turtle.fd(50)
+ >>> turtle.tiltangle(-45)
+ >>> turtle.tiltangle()
+ 315.0
+ >>> stamp_id = turtle.stamp()
+ >>> turtle.fd(50)
"""
if angle is None:
tilt = -math.degrees(self._tilt) * self._angleOrient
@@ -3019,43 +2996,47 @@ def tiltangle(self, angle=None):
self.pen(resizemode="user", tilt=tilt)
def tilt(self, angle):
- """Rotate the turtleshape by angle.
+ """Turn the turtle shape by angle from its current tilt angle.
+
+ The turtle's heading does not change, so the turtle keeps moving
+ in the same direction. See tiltangle().
Argument:
- angle - a number
-
- Rotate the turtleshape by angle from its current tilt-angle,
- but do NOT change the turtle's heading (direction of movement).
-
- Examples (for a Turtle instance named turtle):
- >>> turtle.shape("circle")
- >>> turtle.shapesize(5,2)
- >>> turtle.tilt(30)
- >>> turtle.fd(50)
- >>> turtle.tilt(30)
- >>> turtle.fd(50)
+ angle -- a number
+
+ Example (for a Turtle instance named turtle):
+ >>> turtle.shape("circle")
+ >>> turtle.shapesize(5,2)
+ >>> turtle.tilt(30)
+ >>> turtle.fd(50)
+ >>> turtle.tilt(30)
+ >>> turtle.fd(50)
"""
self.tiltangle(angle + self.tiltangle())
def shapetransform(self, t11=None, t12=None, t21=None, t22=None):
- """Set or return the current transformation matrix of the turtle shape.
-
- Optional arguments: t11, t12, t21, t22 -- numbers.
-
- If none of the matrix elements are given, return the transformation
- matrix.
- Otherwise set the given elements and transform the turtleshape
- according to the matrix consisting of first row t11, t12 and
- second row t21, 22.
- Modify stretchfactor, shearfactor and tiltangle according to the
- given matrix.
-
- Examples (for a Turtle instance named turtle):
- >>> turtle.shape("square")
- >>> turtle.shapesize(4,2)
- >>> turtle.shearfactor(-0.5)
- >>> turtle.shapetransform()
- (4.0, -1.0, -0.0, 2.0)
+ """Return or set the transformation matrix of the turtle shape.
+
+ The matrix combines the stretch factors, the shear factor and the
+ tilt angle of the turtle shape into four numbers: t11 and t12 form
+ its first row, t21 and t22 its second. If none of them are given,
+ return the current matrix as a tuple of four numbers. Otherwise
+ set the given elements and update the stretch factors, shear
+ factor and tilt angle accordingly. t11 * t22 - t12 * t21 must not
+ be zero, otherwise an error is raised.
+
+ Arguments:
+ t11 -- a number or None
+ t12 -- a number or None
+ t21 -- a number or None
+ t22 -- a number or None
+
+ Example (for a Turtle instance named turtle):
+ >>> turtle.shape("square")
+ >>> turtle.shapesize(4,2)
+ >>> turtle.shearfactor(-0.5)
+ >>> turtle.shapetransform()
+ (4.0, -1.0, -0.0, 2.0)
"""
if t11 is t12 is t21 is t22 is None:
return self._shapetrafo
@@ -3090,21 +3071,21 @@ def _polytrafo(self, poly):
for (x, y) in poly]
def get_shapepoly(self):
- """Return the current shape polygon as tuple of coordinate pairs.
+ """Return the points that form the outline of the current turtle shape
+ as a tuple of (x, y) coordinate pairs.
- No argument.
-
- Examples (for a Turtle instance named turtle):
- >>> turtle.shape("square")
- >>> turtle.shapetransform(4, -1, 0, 2)
- >>> turtle.get_shapepoly()
- ((50, -20), (30, 20), (-50, 20), (-30, -20))
+ These points can be used to define a new shape or parts of a
+ compound shape.
+ Example (for a Turtle instance named turtle):
+ >>> turtle.shape("square")
+ >>> turtle.shapetransform(4, -1, 0, 2)
+ >>> turtle.get_shapepoly()
+ ((50, -20), (30, 20), (-50, 20), (-30, -20))
"""
shape = self.screen._shapes[self.turtle.shapeIndex]
if shape._type == "polygon":
return self._getshapepoly(shape._data, shape._type == "compound")
- # else return None
def _getshapepoly(self, polygon, compound=False):
"""Calculate transformed shape polygon according to resizemode
@@ -3120,8 +3101,9 @@ def _getshapepoly(self, polygon, compound=False):
return tuple((t11*x + t12*y, t21*x + t22*y) for (x, y) in polygon)
def _drawturtle(self):
- """Manages the correct rendering of the turtle with respect to
- its shape, resizemode, stretch and tilt etc."""
+ """Draw the turtle according to its shape, resizemode, stretch
+ factors and tilt, or hide it if it is not shown.
+ """
screen = self.screen
shape = screen._shapes[self.turtle.shapeIndex]
ttype = shape._type
@@ -3160,19 +3142,15 @@ def _drawturtle(self):
############################## stamp stuff ###############################
def stamp(self):
- """Stamp a copy of the turtleshape onto the canvas and return its id.
+ """Stamp a copy of the turtle shape onto the canvas and return its id.
- No argument.
-
- Stamp a copy of the turtle shape onto the canvas at the current
- turtle position. Return a stamp_id for that stamp, which can be
- used to delete it by calling clearstamp(stamp_id).
+ The stamp is placed at the current turtle position. The returned
+ id can be used to delete the stamp with clearstamp().
Example (for a Turtle instance named turtle):
- >>> turtle.color("blue")
- >>> turtle.stamp()
- 13
- >>> turtle.fd(50)
+ >>> turtle.color("blue")
+ >>> stamp_id = turtle.stamp()
+ >>> turtle.fd(50)
"""
screen = self.screen
shape = screen._shapes[self.turtle.shapeIndex]
@@ -3180,9 +3158,12 @@ def stamp(self):
tshape = shape._data
if ttype == "polygon":
stitem = screen._createpoly()
- if self._resizemode == "noresize": w = 1
- elif self._resizemode == "auto": w = self._pensize
- else: w =self._outlinewidth
+ if self._resizemode == "noresize":
+ w = 1
+ elif self._resizemode == "auto":
+ w = self._pensize
+ else:
+ w =self._outlinewidth
shape = self._polytrafo(self._getshapepoly(tshape))
fc, oc = self._fillcolor, self._pencolor
screen._drawpoly(stitem, shape, fill=fc, outline=oc,
@@ -3201,12 +3182,12 @@ def stamp(self):
screen._drawpoly(item, poly, fill=self._cc(fc),
outline=self._cc(oc), width=self._outlinewidth, top=True)
self.stampItems.append(stitem)
- self.undobuffer.push(("stamp", stitem))
+ if self.undobuffer:
+ self.undobuffer.push(("stamp", stitem))
return stitem
def _clearstamp(self, stampid):
- """does the work for clearstamp() and clearstamps()
- """
+ """Does the work for clearstamp() and clearstamps()."""
if stampid in self.stampItems:
if isinstance(stampid, tuple):
for subitem in stampid:
@@ -3216,48 +3197,44 @@ def _clearstamp(self, stampid):
self.stampItems.remove(stampid)
# Delete stampitem from undobuffer if necessary
# if clearstamp is called directly.
- item = ("stamp", stampid)
- buf = self.undobuffer
- if item not in buf.buffer:
- return
- index = buf.buffer.index(item)
- buf.buffer.remove(item)
- if index <= buf.ptr:
- buf.ptr = (buf.ptr - 1) % buf.bufsize
- buf.buffer.insert((buf.ptr+1)%buf.bufsize, [None])
+ if self.undobuffer:
+ self.undobuffer.remove(("stamp", stampid))
def clearstamp(self, stampid):
- """Delete stamp with given stampid
+ """Delete the stamp with the given stampid.
+
+ stampid must be the return value of a previous stamp() call.
Argument:
- stampid - an integer, must be return value of previous stamp() call.
+ stampid -- an integer
Example (for a Turtle instance named turtle):
- >>> turtle.color("blue")
- >>> astamp = turtle.stamp()
- >>> turtle.fd(50)
- >>> turtle.clearstamp(astamp)
+ >>> turtle.color("blue")
+ >>> astamp = turtle.stamp()
+ >>> turtle.fd(50)
+ >>> turtle.clearstamp(astamp)
"""
self._clearstamp(stampid)
self._update()
def clearstamps(self, n=None):
- """Delete all or first/last n of turtle's stamps.
+ """Delete all or the first or last n of the turtle's stamps.
- Optional argument:
- n -- an integer
+ If n is not given, delete all stamps. If n is positive, delete the
+ first n stamps. If n is negative, delete the last n stamps, so -2
+ deletes the last two.
- If n is None, delete all of pen's stamps,
- else if n > 0 delete first n stamps
- else if n < 0 delete last n stamps.
+ Argument:
+ n -- an integer or None
Example (for a Turtle instance named turtle):
- >>> for i in range(8):
- ... turtle.stamp(); turtle.fd(30)
- ...
- >>> turtle.clearstamps(2)
- >>> turtle.clearstamps(-2)
- >>> turtle.clearstamps()
+ >>> for i in range(8):
+ ... unused_stamp_id = turtle.stamp()
+ ... turtle.fd(30)
+ ...
+ >>> turtle.clearstamps(2)
+ >>> turtle.clearstamps(-2)
+ >>> turtle.clearstamps()
"""
if n is None:
toDelete = self.stampItems[:]
@@ -3323,13 +3300,13 @@ def _goto(self, end):
self._update() #count=True)
def _undogoto(self, entry):
- """Reverse a _goto. Used for undo()
- """
+ """Reverse a _goto(). Used for undo()."""
old, new, go_modes, coodata = entry
drawing, pc, ps, filling = go_modes
cLI, cL, pl, items = coodata
screen = self.screen
if abs(self._position - new) > 0.5:
+ # XXX(Stan): Figure out what on earth this is.
print ("undogoto: HALLO-DA-STIMMT-WAS-NICHT!")
# restore former situation
self.currentLineItem = cLI
@@ -3388,8 +3365,7 @@ def _undogoto(self, entry):
self._update() #count=True)
def _rotate(self, angle):
- """Turns pen clockwise by angle.
- """
+ """Turn the turtle counterclockwise by angle."""
if self.undobuffer:
self.undobuffer.push(("rot", angle, self._degreesPerAU))
angle *= self._degreesPerAU
@@ -3406,9 +3382,10 @@ def _rotate(self, angle):
self._update()
def _newLine(self, usePos=True):
- """Closes current line item and starts a new one.
- Remark: if current line became too long, animation
- performance (via _drawline) slowed down considerably.
+ """Closes the current line item and starts a new one.
+
+ If the current line becomes too long, animation performance (via _drawline)
+ can slow down considerably.
"""
if len(self.currentLine) > 1:
self.screen._drawline(self.currentLineItem, self.currentLine,
@@ -3422,30 +3399,32 @@ def _newLine(self, usePos=True):
self.currentLine = [self._position]
def filling(self):
- """Return fillstate (True if filling, False else).
-
- No argument.
+ """Return True if the turtle is filling, False otherwise.
Example (for a Turtle instance named turtle):
- >>> turtle.begin_fill()
- >>> if turtle.filling():
- ... turtle.pensize(5)
- ... else:
- ... turtle.pensize(3)
+ >>> turtle.begin_fill()
+ >>> if turtle.filling():
+ ... turtle.pensize(5)
+ ... else:
+ ... turtle.pensize(3)
"""
return isinstance(self._fillpath, list)
@contextmanager
def fill(self):
- """A context manager for filling a shape.
-
- Implicitly ensures the code block is wrapped with
- begin_fill() and end_fill().
+ """Fill the shape drawn in the with block.
Example (for a Turtle instance named turtle):
- >>> turtle.color("black", "red")
- >>> with turtle.fill():
- ... turtle.circle(60)
+ >>> turtle.color("black", "red")
+ >>> with turtle.fill():
+ ... turtle.circle(80)
+
+ fill() is a context manager, so using it is the same as calling
+ begin_fill() before the block and end_fill() after it:
+ >>> turtle.color("black", "red")
+ >>> turtle.begin_fill()
+ >>> turtle.circle(80)
+ >>> turtle.end_fill()
"""
self.begin_fill()
try:
@@ -3454,15 +3433,15 @@ def fill(self):
self.end_fill()
def begin_fill(self):
- """Called just before drawing a shape to be filled.
+ """Call just before drawing a shape to be filled.
- No argument.
+ The shape is filled by the next call to end_fill().
Example (for a Turtle instance named turtle):
- >>> turtle.color("black", "red")
- >>> turtle.begin_fill()
- >>> turtle.circle(60)
- >>> turtle.end_fill()
+ >>> turtle.color("black", "red")
+ >>> turtle.begin_fill()
+ >>> turtle.circle(80)
+ >>> turtle.end_fill()
"""
if not self.filling():
self._fillitem = self.screen._createpoly()
@@ -3474,15 +3453,17 @@ def begin_fill(self):
self._update()
def end_fill(self):
- """Fill the shape drawn after the call begin_fill().
+ """Fill the shape drawn after the last call to begin_fill().
- No argument.
+ If the shape crosses itself or several shapes overlap, whether the
+ overlapping parts are filled depends on the operating system, the
+ type of overlap and how many there are.
Example (for a Turtle instance named turtle):
- >>> turtle.color("black", "red")
- >>> turtle.begin_fill()
- >>> turtle.circle(60)
- >>> turtle.end_fill()
+ >>> turtle.color("black", "red")
+ >>> turtle.begin_fill()
+ >>> turtle.circle(80)
+ >>> turtle.end_fill()
"""
if self.filling():
if len(self._fillpath) > 2:
@@ -3494,18 +3475,19 @@ def end_fill(self):
self._update()
def dot(self, size=None, *color):
- """Draw a dot with diameter size, using color.
+ """Draw a circular dot with diameter size, using color.
- Optional arguments:
- size -- an integer >= 1 (if given)
- color -- a colorstring or a numeric color tuple
+ If size is not given, the larger of pensize + 4 and 2 * pensize is
+ used. If color is not given, the current pencolor is used.
- Draw a circular dot with diameter size, using color.
- If size is not given, the maximum of pensize+4 and 2*pensize is used.
+ Arguments:
+ size -- a positive integer or None
+ color -- a colorstring or a numeric color tuple
Example (for a Turtle instance named turtle):
- >>> turtle.dot()
- >>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50)
+ >>> turtle.home()
+ >>> turtle.dot()
+ >>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50)
"""
if not color:
if isinstance(size, (str, tuple)):
@@ -3521,24 +3503,19 @@ def dot(self, size=None, *color):
color = self._colorstr(color)
# If screen were to gain a dot function, see GH #104218.
pen = self.pen()
- if self.undobuffer:
- self.undobuffer.push(["seq"])
- self.undobuffer.cumulate = True
- try:
- if self.resizemode() == 'auto':
- self.ht()
- self.pendown()
- self.pensize(size)
- self.pencolor(color)
- self.forward(0)
- finally:
- self.pen(pen)
- if self.undobuffer:
- self.undobuffer.cumulate = False
+ with self._undo_sequence():
+ try:
+ if self.resizemode() == 'auto':
+ self.ht()
+ self.pendown()
+ self.pensize(size)
+ self.pencolor(color)
+ self.forward(0)
+ finally:
+ self.pen(pen)
def _write(self, txt, align, font):
- """Performs the writing for write()
- """
+ """Performs the writing for write()."""
item, end = self.screen._write(self._position, txt, align, font,
self._pencolor)
self._update()
@@ -3550,46 +3527,47 @@ def _write(self, txt, align, font):
def write(self, arg, move=False, align="left", font=("Arial", 8, "normal")):
"""Write text at the current turtle position.
- Arguments:
- arg -- info, which is to be written to the TurtleScreen
- move (optional) -- True/False
- align (optional) -- one of the strings "left", "center" or right"
- font (optional) -- a triple (fontname, fontsize, fonttype)
+ The text is the string representation of arg. align is one of
+ the strings "left", "center" or "right" and says how the text is
+ placed relative to the turtle position. font is a triple of font
+ name, font size and font type. If move is True, the pen is moved
+ to the bottom-right corner of the text.
- Write text - the string representation of arg - at the current
- turtle position according to align ("left", "center" or right")
- and with the given font.
- If move is True, the pen is moved to the bottom-right corner
- of the text. By default, move is False.
+ Arguments:
+ arg -- an object
+ move -- a boolean
+ align -- a string
+ font -- a tuple of a string, an integer and a string
Example (for a Turtle instance named turtle):
- >>> turtle.write('Home = ', True, align="center")
- >>> turtle.write((0,0), True)
+ >>> turtle.write("Home = ", True, align="center")
+ >>> turtle.write((0,0), True)
"""
- if self.undobuffer:
- self.undobuffer.push(["seq"])
- self.undobuffer.cumulate = True
- end = self._write(str(arg), align.lower(), font)
- if move:
- x, y = self.pos()
- self.setpos(end, y)
- if self.undobuffer:
- self.undobuffer.cumulate = False
+ with self._undo_sequence():
+ end = self._write(str(arg), align.lower(), font)
+ if move:
+ x, y = self.pos()
+ self.setpos(end, y)
@contextmanager
def poly(self):
- """A context manager for recording the vertices of a polygon.
-
- Implicitly ensures that the code block is wrapped with
- begin_poly() and end_poly()
-
- Example (for a Turtle instance named turtle) where we create a
- triangle as the polygon and move the turtle 100 steps forward:
- >>> with turtle.poly():
- ... for side in range(3)
- ... turtle.forward(50)
- ... turtle.right(60)
- >>> turtle.forward(100)
+ """Record the vertices of a polygon drawn in the with block.
+
+ The first and last vertices will be connected.
+
+ Example (for a Turtle instance named turtle):
+ >>> with turtle.poly():
+ ... turtle.forward(100)
+ ... turtle.right(60)
+ ... turtle.forward(100)
+
+ poly() is a context manager, so using it is the same as calling
+ begin_poly() before the block and end_poly() after it:
+ >>> turtle.begin_poly()
+ >>> turtle.forward(100)
+ >>> turtle.right(60)
+ >>> turtle.forward(100)
+ >>> turtle.end_poly()
"""
self.begin_poly()
try:
@@ -3600,13 +3578,7 @@ def poly(self):
def begin_poly(self):
"""Start recording the vertices of a polygon.
- No argument.
-
- Start recording the vertices of a polygon. Current turtle position
- is first point of polygon.
-
- Example (for a Turtle instance named turtle):
- >>> turtle.begin_poly()
+ The current turtle position is the first vertex of the polygon.
"""
self._poly = [self._position]
self._creatingPoly = True
@@ -3614,59 +3586,56 @@ def begin_poly(self):
def end_poly(self):
"""Stop recording the vertices of a polygon.
- No argument.
-
- Stop recording the vertices of a polygon. Current turtle position is
- last point of polygon. This will be connected with the first point.
-
- Example (for a Turtle instance named turtle):
- >>> turtle.end_poly()
+ The current turtle position is the last vertex of the polygon.
+ This will be connected with the first vertex.
"""
self._creatingPoly = False
def get_poly(self):
- """Return the lastly recorded polygon.
-
- No argument.
+ """Return the last recorded polygon.
Example (for a Turtle instance named turtle):
- >>> p = turtle.get_poly()
- >>> turtle.register_shape("myFavouriteShape", p)
- """
- ## check if there is any poly?
+ >>> turtle.home()
+ >>> turtle.begin_poly()
+ >>> turtle.fd(100)
+ >>> turtle.left(20)
+ >>> turtle.fd(30)
+ >>> turtle.left(60)
+ >>> turtle.fd(50)
+ >>> turtle.end_poly()
+ >>> p = turtle.get_poly()
+ >>> register_shape("myFavouriteShape", p)
+ """
+ # Check if there are any poly?
if self._poly is not None:
return tuple(self._poly)
def getscreen(self):
- """Return the TurtleScreen object, the turtle is drawing on.
-
- No argument.
+ """Return the TurtleScreen object the turtle is drawing on.
- Return the TurtleScreen object, the turtle is drawing on.
So TurtleScreen-methods can be called for that object.
Example (for a Turtle instance named turtle):
- >>> ts = turtle.getscreen()
- >>> ts
-
- >>> ts.bgcolor("pink")
+ >>> ts = turtle.getscreen()
+ >>> ts
+
+ >>> ts.bgcolor("pink")
"""
return self.screen
def getturtle(self):
- """Return the Turtleobject itself.
+ """Return the Turtle object itself.
- No argument.
+ Aliases: getturtle | getpen
- Only reasonable use: as a function to return the 'anonymous turtle':
+ Call getturtle() to get the turtle used by functions such as
+ forward() and left().
Example:
- >>> pet = getturtle()
- >>> pet.fd(50)
- >>> pet
-
- >>> turtles()
- []
+ >>> pet = getturtle()
+ >>> pet.fd(50)
+ >>> pet
+
"""
return self
@@ -3678,80 +3647,91 @@ def getturtle(self):
################################################################
def _delay(self, delay=None):
- """Set delay value which determines speed of turtle animation.
- """
+ """Set the delay which determines the speed of turtle animation."""
return self.screen.delay(delay)
def onclick(self, fun, btn=1, add=None):
- """Bind fun to mouse-click event on this turtle on canvas.
+ """Bind fun to mouse-click events on this turtle.
+
+ fun is called with the coordinates of the clicked point on the
+ canvas. If fun is None, existing bindings are removed. btn is the
+ number of the mouse button and defaults to 1, the left mouse
+ button. If add is True, a new binding is added, otherwise it
+ replaces a previous binding.
Arguments:
- fun -- a function with two arguments, to which will be assigned
- the coordinates of the clicked point on the canvas.
- btn -- number of the mouse-button defaults to 1 (left mouse button).
- add -- True or False. If True, new binding will be added, otherwise
- it will replace a former binding.
-
- Example for the anonymous turtle, i. e. the procedural way:
-
- >>> def turn(x, y):
- ... left(360)
- ...
- >>> onclick(turn) # Now clicking into the turtle will turn it.
- >>> onclick(None) # event-binding will be removed
+ fun -- a function with two arguments or None
+ btn -- an integer
+ add -- a boolean or None
+
+ Example for the anonymous turtle, that is, the procedural way:
+ >>> def turn(x, y):
+ ... left(180)
+ ...
+ >>> onclick(turn) # Now clicking into the turtle will turn it.
+ >>> onclick(None) # event-binding will be removed
"""
self.screen._onclick(self.turtle._item, fun, btn, add)
self._update()
def onrelease(self, fun, btn=1, add=None):
- """Bind fun to mouse-button-release event on this turtle on canvas.
+ """Bind fun to mouse-button-release events on this turtle.
+
+ fun is called with the coordinates of the point on the canvas
+ where the mouse button is released. If fun is None, existing
+ bindings are removed. btn is the number of the mouse button and
+ defaults to 1, the left mouse button. If add is True, a new
+ binding is added, otherwise it replaces a previous binding.
Arguments:
- fun -- a function with two arguments, to which will be assigned
- the coordinates of the clicked point on the canvas.
- btn -- number of the mouse-button defaults to 1 (left mouse button).
+ fun -- a function with two arguments or None
+ btn -- an integer
+ add -- a boolean or None
Example (for a MyTurtle instance named joe):
- >>> class MyTurtle(Turtle):
- ... def glow(self,x,y):
- ... self.fillcolor("red")
- ... def unglow(self,x,y):
- ... self.fillcolor("")
- ...
- >>> joe = MyTurtle()
- >>> joe.onclick(joe.glow)
- >>> joe.onrelease(joe.unglow)
-
- Clicking on joe turns fillcolor red, unclicking turns it to
- transparent.
+ >>> class MyTurtle(Turtle):
+ ... def glow(self,x,y):
+ ... self.fillcolor("red")
+ ...
+ ... def unglow(self,x,y):
+ ... self.fillcolor("")
+ ...
+ >>> joe = MyTurtle()
+ >>> joe.onclick(joe.glow)
+ >>> joe.onrelease(joe.unglow)
+
+ Clicking on joe turns its fill color red, releasing the mouse button
+ turns it transparent again.
"""
self.screen._onrelease(self.turtle._item, fun, btn, add)
self._update()
def ondrag(self, fun, btn=1, add=None):
- """Bind fun to mouse-move event on this turtle on canvas.
+ """Bind fun to mouse-move events on this turtle.
- Arguments:
- fun -- a function with two arguments, to which will be assigned
- the coordinates of the clicked point on the canvas.
- btn -- number of the mouse-button defaults to 1 (left mouse button).
+ fun is called with the coordinates of the mouse pointer on the
+ canvas. If fun is None, existing bindings are removed. btn is the
+ number of the mouse button and defaults to 1, the left mouse
+ button. If add is True, a new binding is added, otherwise it
+ replaces a previous binding. Every sequence of mouse-move events on
+ a turtle is preceded by a mouse-click event on that turtle.
- Every sequence of mouse-move-events on a turtle is preceded by a
- mouse-click event on that turtle.
+ Arguments:
+ fun -- a function with two arguments or None
+ btn -- an integer
+ add -- a boolean or None
Example (for a Turtle instance named turtle):
- >>> turtle.ondrag(turtle.goto)
+ >>> turtle.ondrag(turtle.goto)
- Subsequently clicking and dragging a Turtle will move it
- across the screen thereby producing handdrawings (if pen is
- down).
+ Clicking and dragging the turtle then moves it across the screen,
+ drawing by hand if the pen is down.
"""
self.screen._ondrag(self.turtle._item, fun, btn, add)
def _undo(self, action, data):
- """Does the main part of the work for undo()
- """
+ """Does the main part of the work for undo()."""
if self.undobuffer is None:
return
if action == "rot":
@@ -3763,6 +3743,9 @@ def _undo(self, action, data):
self.clearstamp(stitem)
elif action == "go":
self._undogoto(data)
+ elif action == "teleport":
+ self._position = data[0]
+ self._update()
elif action in ["wri", "dot"]:
item = data[0]
self.screen._delete(item)
@@ -3782,21 +3765,19 @@ def _undo(self, action, data):
self.undobuffer.pop()
def undo(self):
- """undo (repeatedly) the last turtle action.
-
- No argument.
+ """Undo the last turtle action.
- undo (repeatedly) the last turtle action.
- Number of available undo actions is determined by the size of
- the undobuffer.
+ Calling undo() repeatedly undoes one action at a time. The number
+ of actions that can be undone is set by the size of the undo
+ buffer, see setundobuffer().
Example (for a Turtle instance named turtle):
- >>> for i in range(4):
- ... turtle.fd(50); turtle.lt(80)
- ...
- >>> for i in range(8):
- ... turtle.undo()
- ...
+ >>> for i in range(4):
+ ... turtle.fd(50); turtle.lt(80)
+ ...
+ >>> for i in range(8):
+ ... turtle.undo()
+ ...
"""
if self.undobuffer is None:
return
@@ -3817,9 +3798,10 @@ def undo(self):
### Screen - Singleton ########################
def Screen():
- """Return the singleton screen object.
- If none exists at the moment, create a new one and return it,
- else return the existing one."""
+ """Return the single screen object.
+
+ If it does not exist yet, create it. Otherwise return the existing one.
+ """
if Turtle._screen is None:
Turtle._screen = _Screen()
return Turtle._screen
@@ -3849,28 +3831,32 @@ def __init__(self):
def setup(self, width=_CFG["width"], height=_CFG["height"],
startx=_CFG["leftright"], starty=_CFG["topbottom"]):
- """ Set the size and position of the main window.
+ """Set the size and position of the main window.
- Arguments:
- width: as integer a size in pixels, as float a fraction of the screen.
- Default is 50% of screen.
- height: as integer the height in pixels, as float a fraction of the
- screen. Default is 75% of screen.
- startx: if positive, starting position in pixels from the left
- edge of the screen, if negative from the right edge
- Default, startx=None is to center window horizontally.
- starty: if positive, starting position in pixels from the top
- edge of the screen, if negative from the bottom edge
- Default, starty=None is to center window vertically.
+ width and height are the size of the window. As integers they are
+ sizes in pixels, as floats they are fractions of the screen, so
+ 0.5 is half the screen. The defaults are 50% of the screen width
+ and 75% of its height.
- Examples (for a Screen instance named screen):
- >>> screen.setup (width=200, height=200, startx=0, starty=0)
+ startx and starty are the position of the window. If positive,
+ they are the distance in pixels from the left and top edges of the
+ screen, if negative from the right and bottom edges. If None, the
+ window is centered in that direction.
- sets window to 200x200 pixels, in upper left of screen
+ The default values of all arguments are stored in the
+ configuration dictionary and can be changed with a turtle.cfg file.
- >>> screen.setup(width=.75, height=0.5, startx=None, starty=None)
+ Arguments:
+ width -- an integer or a float
+ height -- an integer or a float
+ startx -- an integer or None
+ starty -- an integer or None
- sets window to 75% of screen by 50% of screen and centers
+ Example (for a Screen instance named screen):
+ >>> screen.setup(width=200, height=200, startx=0, starty=0)
+ >>> # sets window to 200x200 pixels, in upper left of screen
+ >>> screen.setup(width=0.75, height=0.5)
+ >>> # sets window to 75% of screen by 50% of screen and centers
"""
if not hasattr(self._root, "set_geometry"):
return
@@ -3888,17 +3874,17 @@ def setup(self, width=_CFG["width"], height=_CFG["height"],
self.update()
def title(self, titlestring):
- """Set title of turtle-window
+ """Set the title of the turtle window to titlestring.
- Argument:
- titlestring -- a string, to appear in the titlebar of the
- turtle graphics window.
+ The title is shown in the title bar of the turtle graphics window.
+ This is a method of the Screen class. It is not available for
+ TurtleScreen objects.
- This is a method of Screen-class. Not available for TurtleScreen-
- objects.
+ Argument:
+ titlestring -- a string
Example (for a Screen instance named screen):
- >>> screen.title("Welcome to the turtle-zoo!")
+ >>> screen.title("Welcome to the turtle zoo!")
"""
if _Screen._root is not None:
_Screen._root.title(titlestring)
@@ -3915,31 +3901,18 @@ def _destroy(self):
root.destroy()
def bye(self):
- """Shut the turtlegraphics window.
-
- Example (for a TurtleScreen instance named screen):
- >>> screen.bye()
- """
+ """Close the turtle graphics window."""
self._destroy()
def exitonclick(self):
- """Go into mainloop until the mouse is clicked.
-
- No arguments.
-
- Bind bye() method to mouseclick on TurtleScreen.
- If "using_IDLE" - value in configuration dictionary is False
- (default value), enter mainloop.
- If IDLE with -n switch (no subprocess) is used, this value should be
- set to True in turtle.cfg. In this case IDLE's mainloop
- is active also for the client script.
+ """Bind bye() to mouse clicks on the screen and start the event loop.
- This is a method of the Screen-class and not available for
- TurtleScreen instances.
-
- Example (for a Screen instance named screen):
- >>> screen.exitonclick()
+ Clicking on the screen then closes the turtle graphics window. If
+ the configuration value using_IDLE is True, the event loop is not
+ started, see mainloop().
+ This is a method of the Screen class. It is not available for
+ TurtleScreen objects.
"""
def exitGracefully(x, y):
"""Screen.bye() with two dummy-parameters"""
@@ -3975,16 +3948,15 @@ def __init__(self,
Pen = Turtle
def write_docstringdict(filename="turtle_docstringdict"):
- """Create and write docstring-dictionary to file.
+ """Write the docstring dictionary to a Python script.
- Optional argument:
- filename -- a string, used as filename
- default value is turtle_docstringdict
+ The dictionary is written to the file filename.py. It is intended to
+ serve as a template for translating the docstrings into different
+ languages. This function has to be called explicitly. It is not used
+ by the turtle graphics classes.
- Has to be called explicitly, (not used by the turtle-graphics classes)
- The docstring dictionary will be written to the Python script .py
- It is intended to serve as a template for translation of the docstrings
- into different languages.
+ Argument:
+ filename -- a string
"""
docsdict = {}
@@ -4009,23 +3981,29 @@ def write_docstringdict(filename="turtle_docstringdict"):
f.close()
def read_docstrings(lang):
- """Read in docstrings from lang-specific docstring dictionary.
+ """Read in docstrings from a language-specific docstring dictionary.
Transfer docstrings, translated to lang, from a dictionary-file
to the methods of classes Screen and Turtle and - in revised form -
to the corresponding functions.
+
+ Entries naming a method which does not exist in this version are
+ ignored.
"""
- modname = "turtle_docstringdict_%(language)s" % {'language':lang.lower()}
- module = __import__(modname)
+ module = __import__(f"turtle_docstringdict_{lang.lower()}")
docsdict = module.docsdict
for key in docsdict:
try:
# eval(key).im_func.__doc__ = docsdict[key]
eval(key).__doc__ = docsdict[key]
+ except AttributeError:
+ pass
except Exception:
print("Bad docstring-entry: %s" % key)
_LANGUAGE = _CFG["language"]
+if not sys.flags.ignore_environment:
+ _LANGUAGE = environ.get("PYTHON_TURTLE_LANG") or _LANGUAGE
try:
if _LANGUAGE != "english":
@@ -4038,10 +4016,10 @@ def read_docstrings(lang):
def getmethparlist(ob):
- """Get strings describing the arguments for the given object
+ """Get strings describing the arguments for the given object.
Returns a pair of strings representing function parameter lists
- including parenthesis. The first string is suitable for use in
+ including parentheses. The first string is suitable for use in
function definition and the second is suitable for use in function
call. The "self" parameter is not included.
"""
@@ -4074,8 +4052,7 @@ def getmethparlist(ob):
return str(func_sig), call_text
def _turtle_docrevise(docstr):
- """To reduce docstrings from RawTurtle class for functions
- """
+ """To reduce docstrings from the RawTurtle class for functions."""
import re
if docstr is None:
return None
@@ -4086,8 +4063,7 @@ def _turtle_docrevise(docstr):
return newdocstr
def _screen_docrevise(docstr):
- """To reduce docstrings from TurtleScreen class for functions
- """
+ """To reduce docstrings from the TurtleScreen class for functions."""
import re
if docstr is None:
return None
diff --git a/Lib/turtledemo/__main__.py b/Lib/turtledemo/__main__.py
index 7c2d753f4c31113..cffc08f59b99d26 100644
--- a/Lib/turtledemo/__main__.py
+++ b/Lib/turtledemo/__main__.py
@@ -333,7 +333,7 @@ def loadfile(self, filename):
modname = 'turtledemo.' + filename
__import__(modname)
self.module = sys.modules[modname]
- with open(self.module.__file__, 'r') as f:
+ with open(self.module.__file__, encoding='utf-8') as f:
chars = f.read()
self.text.delete("1.0", "end")
self.text.insert("1.0", chars)
diff --git a/Lib/turtledemo/sorting_animate.py b/Lib/turtledemo/sorting_animate.py
index e0a2877cd5d621a..8bfaa74b719c6b5 100644
--- a/Lib/turtledemo/sorting_animate.py
+++ b/Lib/turtledemo/sorting_animate.py
@@ -178,7 +178,6 @@ def enable_keys():
onkey(start_ssort, "s")
onkey(start_qsort, "q")
onkey(randomize, "r")
- onkey(bye, "space")
def main():
getscreen().clearscreen()
@@ -191,7 +190,7 @@ def main():
return "EVENTLOOP"
instructions1 = "press i for insertion sort, s for selection sort, q for quicksort"
-instructions2 = "spacebar to quit, r to randomize"
+instructions2 = "r to randomize"
if __name__=="__main__":
msg = main()
diff --git a/Lib/typing.py b/Lib/typing.py
index 933336ff4cf37e2..b8545cae052e6f9 100644
--- a/Lib/typing.py
+++ b/Lib/typing.py
@@ -19,11 +19,13 @@
"""
from abc import abstractmethod, ABCMeta
+import atexit
import collections
from collections import defaultdict
import collections.abc
import copyreg
import functools
+import keyword
import operator
import sys
import types
@@ -121,7 +123,6 @@
'TextIO',
# One-off things.
- 'AnyStr',
'assert_type',
'assert_never',
'cast',
@@ -392,6 +393,16 @@ def _flatten_literal_params(parameters):
_caches = {}
+def _clear_caches():
+ for cleanup in _cleanups:
+ cleanup()
+
+
+# Release the LRU caches at shutdown, they otherwise redistribute reference
+# leaks of one extension to types of unrelated ones. See GH-151728.
+atexit.register(_clear_caches)
+
+
def _tp_cache(func=None, /, *, typed=False):
"""Internal wrapper caching __getitem__ of generic types.
@@ -463,6 +474,9 @@ def _eval_type(t, globalns, localns, type_params, *, recursive_guard=frozenset()
type_params=type_params, owner=owner,
_recursive_guard=recursive_guard, format=format)
if isinstance(t, (_GenericAlias, GenericAlias, Union)):
+ if isinstance(t, _LiteralGenericAlias):
+ # Unlike other generic aliases, Literal arguments aren't type expressions
+ return t
if isinstance(t, GenericAlias):
args = tuple(
_make_forward_ref(arg, parent_fwdref=parent_fwdref) if isinstance(arg, str) else arg
@@ -483,7 +497,7 @@ def _eval_type(t, globalns, localns, type_params, *, recursive_guard=frozenset()
if isinstance(t, GenericAlias):
return _rebuild_generic_alias(t, ev_args)
if isinstance(t, Union):
- return functools.reduce(operator.or_, ev_args)
+ return Union[ev_args]
else:
return t.copy_with(ev_args)
return t
@@ -775,13 +789,16 @@ def open_helper(file: str, mode: MODE) -> str:
# There is no '_type_check' call because arguments to Literal[...] are
# values, not types.
parameters = _flatten_literal_params(parameters)
+ value_and_type_parameters = list(_value_and_type_iter(parameters))
+ deduplicated_parameters = tuple(
+ p
+ for p, _ in _deduplicate(
+ value_and_type_parameters,
+ unhashable_fallback=True,
+ )
+ )
- try:
- parameters = tuple(p for p, _ in _deduplicate(list(_value_and_type_iter(parameters))))
- except TypeError: # unhashable parameters
- pass
-
- return _LiteralGenericAlias(self, parameters)
+ return _LiteralGenericAlias(self, deduplicated_parameters)
@_SpecialForm
@@ -984,8 +1001,12 @@ def _make_forward_ref(code, *, parent_fwdref=None, **kwargs):
if parent_fwdref.__owner__ is not None:
kwargs['owner'] = parent_fwdref.__owner__
forward_ref = annotationlib.ForwardRef(code, **kwargs)
- # For compatibility, eagerly compile the forwardref's code.
- forward_ref.__forward_code__
+ # For compatibility, eagerly compile the forwardref's code so that any
+ # SyntaxError is raised immediately rather than when the forward
+ # reference is evaluated. Similar to 'ForwardRef.evaluate()', we only compile
+ # it if necessary:
+ if not (code.isidentifier() and not keyword.iskeyword(code)):
+ forward_ref.__forward_code__
return forward_ref
@@ -2532,7 +2553,7 @@ def _strip_annotations(t):
stripped_args = tuple(_strip_annotations(a) for a in t.__args__)
if stripped_args == t.__args__:
return t
- return functools.reduce(operator.or_, stripped_args)
+ return Union[stripped_args]
return t
@@ -2818,11 +2839,6 @@ class Disjoint3(Disjoint1, Disjoint2): pass # Type checker error
CT_co = TypeVar('CT_co', covariant=True, bound=type)
-# A useful type variable with constraints. This represents string types.
-# (This one *is* for export!)
-AnyStr = TypeVar('AnyStr', bytes, str)
-
-
# Various ABCs mimicking those in collections.abc.
_alias = _SpecialGenericAlias
@@ -3526,8 +3542,9 @@ def __ror__(self, other):
# Constant that's True when type checking, but False here.
TYPE_CHECKING = False
-
-class IO(Generic[AnyStr]):
+# Since `AnyStr` public API is deprecated since 3.16 and will be removed
+# in 3.21, we need to keep `IO` protocol the same as it used to be:
+class IO[AnyStr: (bytes, str)]:
"""Generic base class for TextIO and BinaryIO.
This is an abstract, generic version of the return of open().
@@ -3927,6 +3944,20 @@ def __subclasscheck__(self, cls):
)
return ByteString
+ elif attr == "AnyStr":
+ import warnings
+
+ warnings._deprecated(
+ "typing.AnyStr",
+ message=(
+ "{name!r} is deprecated and slated for removal "
+ "in Python {remove}. Use PEP 695 type parameters "
+ "with constraints instead"
+ ),
+ remove=(3, 21),
+ )
+ AnyStr = globals()["AnyStr"] = TypeVar('AnyStr', bytes, str)
+ return AnyStr
else:
raise AttributeError(f"module {__name__!r} has no attribute {attr!r}")
globals()[attr] = obj
diff --git a/Lib/unittest/main.py b/Lib/unittest/main.py
index 6eeebf9657a3c7b..850c825a7366579 100644
--- a/Lib/unittest/main.py
+++ b/Lib/unittest/main.py
@@ -161,9 +161,12 @@ def _initArgParsers(self):
def _getParentArgParser(self):
parser = argparse.ArgumentParser(add_help=False)
+ # Counted, not a constant: the namespace is the TestProgram, whose
+ # verbosity is already 1, so -v still gives 2 and -vv gives 3.
parser.add_argument('-v', '--verbose', dest='verbosity',
- action='store_const', const=2,
- help='Verbose output')
+ action='count', default=1,
+ help='Verbose output, twice to also report '
+ 'the examples of a doctest')
parser.add_argument('-q', '--quiet', dest='verbosity',
action='store_const', const=0,
help='Quiet output')
diff --git a/Lib/unittest/mock.py b/Lib/unittest/mock.py
index 49011faaa51eaed..d3d47ff81e85969 100644
--- a/Lib/unittest/mock.py
+++ b/Lib/unittest/mock.py
@@ -35,7 +35,7 @@
import threading
from annotationlib import Format
from dataclasses import fields, is_dataclass
-from types import CodeType, ModuleType, MethodType
+from types import CodeType, LazyImportType, ModuleType, MethodType
from unittest.util import safe_repr
from functools import wraps, partial
from threading import RLock
@@ -595,7 +595,7 @@ def __set_return_value(self, value):
__return_value_doc = "The value to be returned when the mock is called."
return_value = property(__get_return_value, __set_return_value,
- __return_value_doc)
+ doc=__return_value_doc)
@property
@@ -798,7 +798,7 @@ def __dir__(self):
from_type = [e for e in from_type if not e.startswith('_')]
from_dict = [e for e in from_dict if not e.startswith('_') or
_is_magic(e)]
- return sorted(set(extras + from_type + from_dict + from_child_mocks))
+ return sorted({*extras, *from_type, *from_dict, *from_child_mocks})
def __setattr__(self, name, value):
@@ -1507,6 +1507,10 @@ def __enter__(self):
original, local = self.get_original()
+ if (isinstance(original, LazyImportType)
+ and (spec is True or spec_set is True or autospec is True)):
+ original = original.resolve()
+
if new is DEFAULT and autospec is None:
inherit = False
if spec is True:
diff --git a/Lib/unittest/result.py b/Lib/unittest/result.py
index b8ea396db6772ed..a787686a5bea4ce 100644
--- a/Lib/unittest/result.py
+++ b/Lib/unittest/result.py
@@ -37,6 +37,9 @@ class TestResult(object):
_moduleSetUpFailed = False
def __init__(self, stream=None, descriptions=None, verbosity=None):
self.failfast = False
+ # How much the test runner reports: 0 -- quiet, 1 -- progress dots,
+ # 2 -- test names, 3 -- also the examples of a doctest.
+ self.verbosity = 1 if verbosity is None else verbosity
self.failures = []
self.errors = []
self.testsRun = 0
diff --git a/Lib/unittest/runner.py b/Lib/unittest/runner.py
index 893fcba968c3ef8..f19d7b6e446d2ac 100644
--- a/Lib/unittest/runner.py
+++ b/Lib/unittest/runner.py
@@ -244,6 +244,9 @@ def run(self, test):
result.failfast = self.failfast
result.buffer = self.buffer
result.tb_locals = self.tb_locals
+ # Not left to _makeResult(): a result class is free to filter the
+ # verbosity which its constructor gets.
+ result.verbosity = self.verbosity
with warnings.catch_warnings():
if self.warnings:
# if self.warnings is set, use it to filter all the warnings
diff --git a/Lib/urllib/error.py b/Lib/urllib/error.py
index beb32d0df48610d..cc9a9254d760f7f 100644
--- a/Lib/urllib/error.py
+++ b/Lib/urllib/error.py
@@ -11,6 +11,7 @@
response.
"""
import io
+import sys
import urllib.response
__all__ = ['URLError', 'HTTPError', 'ContentTooShortError']
@@ -27,6 +28,13 @@ def __init__(self, reason, filename=None):
self.reason = reason
if filename is not None:
self.filename = filename
+ if isinstance(reason, OSError):
+ # OSError.__init__() is not called, so copy the attributes
+ # it would have set from the wrapped error (gh-50720).
+ self.errno = reason.errno
+ self.strerror = reason.strerror
+ if sys.platform == 'win32':
+ self.winerror = reason.winerror
def __str__(self):
return '' % self.reason
diff --git a/Lib/urllib/parse.py b/Lib/urllib/parse.py
index 4247b9a4b07fa3f..f6c94060054e48f 100644
--- a/Lib/urllib/parse.py
+++ b/Lib/urllib/parse.py
@@ -125,6 +125,13 @@ def _coerce_args(*args):
# - encoding function otherwise
str_input = None
for arg in args:
+ if not (arg is None or isinstance(arg, str) or hasattr(arg, 'decode')):
+ if arg:
+ raise TypeError("Expected str, bytes or None, "
+ f"not {type(arg).__name__}")
+ warnings.warn(f"Accepting {type(arg).__name__} objects with false "
+ f"value in urllib.parse is deprecated as of 3.16",
+ DeprecationWarning, stacklevel=3)
if arg:
if str_input is None:
str_input = isinstance(arg, str)
@@ -140,6 +147,27 @@ def _coerce_args(*args):
return args + (_noop,)
return _decode_args(args) + (_encode_result,)
+def _parse_hostinfo(netloc):
+ _, _, hostinfo = netloc.rpartition('@')
+ _, have_open_br, bracketed = hostinfo.partition('[')
+ if have_open_br:
+ hostname, _, port = bracketed.partition(']')
+ _, _, port = port.partition(':')
+ else:
+ hostname, _, port = hostinfo.partition(':')
+ if not port:
+ port = None
+ return hostname, port
+
+def _validate_port(port):
+ if port.isdigit() and port.isascii():
+ port = int(port)
+ else:
+ raise ValueError(f"Port could not be cast to integer value as {port!r}")
+ if not (0 <= port <= 65535):
+ raise ValueError("Port out of range 0-65535")
+ return port
+
# Result objects are more helpful than simple tuples
class _ResultMixinStr(object):
"""Standard approach to encoding parsed results from str to bytes"""
@@ -198,12 +226,7 @@ def hostname(self):
def port(self):
port = self._hostinfo[1]
if port is not None:
- if port.isdigit() and port.isascii():
- port = int(port)
- else:
- raise ValueError(f"Port could not be cast to integer value as {port!r}")
- if not (0 <= port <= 65535):
- raise ValueError("Port out of range 0-65535")
+ port = _validate_port(port)
return port
__class_getitem__ = classmethod(types.GenericAlias)
@@ -231,16 +254,7 @@ def _hostinfo(self):
netloc = self.netloc
if netloc is None:
return None, None
- _, _, hostinfo = netloc.rpartition('@')
- _, have_open_br, bracketed = hostinfo.partition('[')
- if have_open_br:
- hostname, _, port = bracketed.partition(']')
- _, _, port = port.partition(':')
- else:
- hostname, _, port = hostinfo.partition(':')
- if not port:
- port = None
- return hostname, port
+ return _parse_hostinfo(netloc)
class _NetlocResultMixinBytes(_NetlocResultMixinBase, _ResultMixinBytes):
@@ -506,9 +520,7 @@ def _splitnetloc(url, start=0):
delim = min(delim, wdelim) # use earliest delim position
return url[start:delim], url[delim:] # return (domain, rest)
-def _checknetloc(netloc):
- if not netloc or netloc.isascii():
- return
+def _checknetloc_nfkc(netloc):
# looking for characters like \u2100 that expand to 'a/c'
# IDNA uses NFKC equivalence, so normalize for this check
import unicodedata
@@ -524,6 +536,16 @@ def _checknetloc(netloc):
raise ValueError("netloc '" + netloc + "' contains invalid " +
"characters under NFKC normalization")
+def _checknetloc(netloc):
+ if not netloc:
+ return
+ if not netloc.isascii():
+ _checknetloc_nfkc(netloc)
+
+ _, port = _parse_hostinfo(netloc)
+ if port is not None:
+ _validate_port(port)
+
def _check_bracketed_netloc(netloc):
# Note that this function must mirror the splitting
# done in NetlocResultMixins._hostinfo().
@@ -697,12 +719,12 @@ def _urlunsplit(scheme, netloc, url, query, fragment):
def urljoin(base, url, allow_fragments=True):
"""Join a base URL and a possibly relative URL to form an absolute
interpretation of the latter."""
+ base, url, _coerce_result = _coerce_args(base, url)
if not base:
- return url
+ return _coerce_result(url)
if not url:
- return base
+ return _coerce_result(base)
- base, url, _coerce_result = _coerce_args(base, url)
bscheme, bnetloc, bpath, bquery, bfragment = \
_urlsplit(base, None, allow_fragments)
scheme, netloc, path, query, fragment = \
diff --git a/Lib/urllib/request.py b/Lib/urllib/request.py
index 660301fef612588..26c27fd5b2c3ab6 100644
--- a/Lib/urllib/request.py
+++ b/Lib/urllib/request.py
@@ -101,7 +101,8 @@
from urllib.parse import (
urlparse, urlsplit, urljoin, unwrap, quote, unquote,
_splittype, _splithost, _splitport, _splituser, _splitpasswd,
- _splitattr, _splitvalue, _splittag,
+ _splitattr, _splitvalue, _splittag, _splitnetloc,
+ _WHATWG_C0_CONTROL_OR_SPACE, _UNSAFE_URL_BYTES_TO_REMOVE,
unquote_to_bytes, urlunparse)
from urllib.response import addinfourl, addclosehook
@@ -274,7 +275,7 @@ def request_host(request):
"""
url = request.full_url
- host = urlparse(url)[1]
+ host = urlparse(url).netloc
if host == "":
host = request.get_header("Host", "")
@@ -356,8 +357,10 @@ def get_full_url(self):
return self.full_url
def set_proxy(self, host, type):
- if self.type == 'https' and not self._tunnel_host:
- self._tunnel_host = self.host
+ if self.type == 'https':
+ # A retried request keeps the tunnel host set on the first pass.
+ if not self._tunnel_host:
+ self._tunnel_host = self.host
else:
self.type= type
self.selector = self.full_url
@@ -815,16 +818,17 @@ def add_password(self, realm, uri, user, passwd):
self.passwd[realm] = {}
for default_port in True, False:
reduced_uri = tuple(
- self.reduce_uri(u, default_port) for u in uri)
+ self._reduce_uri_with_scheme(u, default_port) for u in uri)
self.passwd[realm][reduced_uri] = (user, passwd)
def find_user_password(self, realm, authuri):
domains = self.passwd.get(realm, {})
for default_port in True, False:
- reduced_authuri = self.reduce_uri(authuri, default_port)
+ reduced_authuri = self._reduce_uri_with_scheme(
+ authuri, default_port)
for uris, authinfo in domains.items():
for uri in uris:
- if self.is_suburi(uri, reduced_authuri):
+ if self._is_suburi_with_scheme(uri, reduced_authuri):
return authinfo
return None, None
@@ -832,11 +836,11 @@ def reduce_uri(self, uri, default_port=True):
"""Accept authority or URI and extract only the authority and path."""
# note HTTP URLs do not have a userinfo component
parts = urlsplit(uri)
- if parts[1]:
+ if parts.netloc:
# URI
- scheme = parts[0]
- authority = parts[1]
- path = parts[2] or '/'
+ scheme = parts.scheme
+ authority = parts.netloc
+ path = parts.path or '/'
else:
# host or host:port
scheme = None
@@ -851,6 +855,17 @@ def reduce_uri(self, uri, default_port=True):
authority = "%s:%d" % (host, dport)
return authority, path
+ def _reduce_uri_with_scheme(self, uri, default_port=True):
+ parts = urlsplit(uri)
+ scheme = parts[0] if parts[1] else None
+ return (scheme or None, *self.reduce_uri(uri, default_port))
+
+ def _is_suburi_with_scheme(self, base, test):
+ if (base[0] is not None and test[0] is not None and
+ base[0] != test[0]):
+ return False
+ return self.is_suburi(base[1:], test[1:])
+
def is_suburi(self, base, test):
"""Check if test is below base in a URI tree
@@ -896,14 +911,15 @@ def update_authenticated(self, uri, is_authenticated=False):
for default_port in True, False:
for u in uri:
- reduced_uri = self.reduce_uri(u, default_port)
+ reduced_uri = self._reduce_uri_with_scheme(u, default_port)
self.authenticated[reduced_uri] = is_authenticated
def is_authenticated(self, authuri):
for default_port in True, False:
- reduced_authuri = self.reduce_uri(authuri, default_port)
+ reduced_authuri = self._reduce_uri_with_scheme(
+ authuri, default_port)
for uri in self.authenticated:
- if self.is_suburi(uri, reduced_authuri):
+ if self._is_suburi_with_scheme(uri, reduced_authuri):
return self.authenticated[uri]
@@ -1035,6 +1051,9 @@ class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
auth_header = 'Proxy-authorization'
def http_error_407(self, req, fp, code, msg, headers):
+ # gh-158907: a 407 from a direct origin is not a proxy challenge
+ if not req.has_proxy() and not req._tunnel_host:
+ return None
# http_error_auth_reqed requires that there is no userinfo component in
# authority. Assume there isn't one, since urllib.request does not (and
# should not, RFC 3986 s. 3.2.1) support requests for URLs containing
@@ -1072,25 +1091,87 @@ def __init__(self, passwd=None):
def reset_retry_count(self):
self.retried = 0
+ def _parse_challenges(self, header):
+ # Yield (scheme, challenge) for each challenge in a WWW-Authenticate
+ # header value. Commas separate both challenges and the auth-params
+ # of a challenge, so an element which starts with a token that is not
+ # followed by "=" starts a new challenge (RFC 9110, section 11.6.1).
+ #
+ # For example, the header value
+ #
+ # Basic realm="a", Digest realm="b", nonce="n"
+ #
+ # is split on commas into the elements 'Basic realm="a"',
+ # 'Digest realm="b"' and 'nonce="n"'. "Basic" and "Digest" are not
+ # followed by "=", so they start challenges; 'nonce="n"' continues
+ # the Digest one. This yields:
+ #
+ # ('Basic', 'Basic realm="a"')
+ # ('Digest', 'Digest realm="b", nonce="n"')
+ elements = []
+ start = 0
+ quote = escape = False
+ for i, c in enumerate(header):
+ if escape:
+ escape = False
+ elif quote:
+ if c == '\\':
+ escape = True
+ elif c == '"':
+ quote = False
+ elif c == '"':
+ quote = True
+ elif c == ',':
+ elements.append((start, i))
+ start = i + 1
+ elements.append((start, len(header)))
+
+ scheme = begin = end = None
+ for elt_start, elt_end in elements:
+ words = header[elt_start:elt_end].split(None, 1)
+ if not words:
+ continue
+ rest = words[1] if len(words) > 1 else ''
+ if '=' not in words[0] and not rest.startswith('='):
+ if scheme is not None:
+ yield scheme, header[begin:end].strip()
+ scheme = words[0]
+ begin = elt_start
+ end = elt_end
+ if scheme is not None:
+ yield scheme, header[begin:end].strip()
+
def http_error_auth_reqed(self, auth_header, host, req, headers):
- authreq = headers.get(auth_header, None)
+ authreqs = headers.get_all(auth_header)
if self.retried > 5:
# Don't fail endlessly - if we failed once, we'll probably
# fail a second time. Hm. Unless the Password Manager is
# prompting for the information. Crap. This isn't great
# but it's better than the current 'repeat until recursion
# depth exceeded' approach
- raise HTTPError(req.full_url, 401, "digest auth failed",
+ if auth_header.lower() == 'proxy-authenticate':
+ code = 407
+ else:
+ code = 401
+ raise HTTPError(req.full_url, code, "digest auth failed",
headers, None)
else:
self.retried += 1
- if authreq:
- scheme = authreq.split()[0]
- if scheme.lower() == 'digest':
- return self.retry_http_digest_auth(req, authreq)
- elif scheme.lower() != 'basic':
- raise ValueError("AbstractDigestAuthHandler does not support"
- " the following scheme: '%s'" % scheme)
+ if not authreqs:
+ return None
+ unsupported = None
+ basic_found = False
+ for authreq in authreqs:
+ for scheme, challenge in self._parse_challenges(authreq):
+ if scheme.lower() == 'digest':
+ return self.retry_http_digest_auth(req, challenge)
+ if scheme.lower() == 'basic':
+ basic_found = True
+ elif unsupported is None:
+ unsupported = scheme
+ if unsupported is not None and not basic_found:
+ raise ValueError("AbstractDigestAuthHandler does not support"
+ " the following scheme: '%s'" % unsupported)
def retry_http_digest_auth(self, req, auth):
token, challenge = auth.split(' ', 1)
@@ -1131,7 +1212,13 @@ def get_authorization(self, req, chal):
if H is None:
return None
- user, pw = self.passwd.find_user_password(realm, req.full_url)
+ # proxy auth is looked up by the proxy's authority
+ # req.host, set by Request.set_proxy()
+ if self.auth_header == 'Proxy-Authorization':
+ authority = req.host
+ else:
+ authority = req.full_url
+ user, pw = self.passwd.find_user_password(realm, authority)
if user is None:
return None
@@ -1141,10 +1228,24 @@ def get_authorization(self, req, chal):
else:
entdig = None
+ # The digest-uri is the request-target as sent on the request line:
+ # the path, or the absolute URL when the request goes through an
+ # HTTP proxy. RFC 7616, Section 3.4 allows both. An empty path is
+ # sent as '/' by http.client, so use the same here.
+
+ if self.auth_header == 'Proxy-Authorization' and req._tunnel_host:
+ # For an https URL the proxy authenticates the CONNECT request,
+ # whose request-target is host:port, as sent by http.client.
+ method = 'CONNECT'
+ host, port = _splitport(req._tunnel_host)
+ uri = '%s:%s' % (host.encode('idna').decode('ascii'),
+ port or http.client.HTTPS_PORT)
+ else:
+ method = req.get_method()
+ uri = req.selector or '/'
+
A1 = "%s:%s:%s" % (user, realm, pw)
- A2 = "%s:%s" % (req.get_method(),
- # XXX selector: what about proxies and full urls
- req.selector)
+ A2 = "%s:%s" % (method, uri)
# NOTE: As per RFC 2617, when server sends "auth,auth-int", the client could use either `auth`
# or `auth-int` to the response back. we use `auth` to send the response back.
if qop is None:
@@ -1166,8 +1267,7 @@ def get_authorization(self, req, chal):
# XXX should the partial digests be encoded too?
base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \
- 'response="%s"' % (user, realm, nonce, req.selector,
- respdig)
+ 'response="%s"' % (user, realm, nonce, uri, respdig)
if opaque:
base += ', opaque="%s"' % opaque
if entdig:
@@ -1209,7 +1309,7 @@ class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
handler_order = 490 # before Basic auth
def http_error_401(self, req, fp, code, msg, headers):
- host = urlparse(req.full_url)[1]
+ host = urlparse(req.full_url).netloc
retry = self.http_error_auth_reqed('www-authenticate',
host, req, headers)
self.reset_retry_count()
@@ -1222,12 +1322,35 @@ class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
handler_order = 490 # before Basic auth
def http_error_407(self, req, fp, code, msg, headers):
+ # gh-158907: a 407 from a direct origin is not a proxy challenge
+ if not req.has_proxy() and not req._tunnel_host:
+ return None
host = req.host
retry = self.http_error_auth_reqed('proxy-authenticate',
host, req, headers)
self.reset_retry_count()
return retry
+class _ProxyTunnelResponse(io.BytesIO):
+ """The proxy's error response to CONNECT, as an empty-bodied response."""
+
+ def __init__(self, err, url):
+ super().__init__()
+ self.url = url
+ self.code = self.status = err.code
+ self.msg = self.reason = err.reason
+ self.headers = err.headers
+
+ def info(self):
+ return self.headers
+
+ def geturl(self):
+ return self.url
+
+ def getcode(self):
+ return self.code
+
+
class AbstractHTTPHandler(BaseHandler):
def __init__(self, debuglevel=None):
@@ -1321,6 +1444,12 @@ def do_open(self, http_class, req, **http_conn_args):
try:
h.request(req.get_method(), req.selector, req.data, headers,
encode_chunked=req.has_header('Transfer-encoding'))
+ except http.client.ProxyTunnelError as err:
+ if err.code != 407:
+ raise URLError(err)
+ # Pass the proxy's challenge to CONNECT on to the
+ # http_error_407 handlers, like any other error response.
+ return _ProxyTunnelResponse(err, req.full_url)
except OSError as err: # timeout error
raise URLError(err)
r = h.getresponse()
@@ -1668,7 +1797,22 @@ def url2pathname(url, *, require_scheme=False, resolve_host=False):
"""
if not require_scheme:
url = 'file:' + url
- scheme, authority, url = urlsplit(url)[:3] # Discard query and fragment.
+ # Match urlsplit()'s own control-character handling up front, so the
+ # except branch below can reuse this same cleaned-up string.
+ url = url.lstrip(_WHATWG_C0_CONTROL_OR_SPACE)
+ for b in _UNSAFE_URL_BYTES_TO_REMOVE:
+ url = url.replace(b, '')
+ try:
+ scheme, authority, url = urlsplit(url)[:3] # Discard query and fragment.
+ except ValueError:
+ # The authority here is not a real host[:port] pair -- it may
+ # hold a Windows drive letter (e.g. 'C:\\') -- so urlsplit()'s
+ # eager port check doesn't apply; split without it instead.
+ scheme, _, url = url.partition(':')
+ scheme = scheme.lower()
+ authority = ''
+ if url[:2] == '//':
+ authority, url = _splitnetloc(url, 2)
if scheme != 'file':
raise URLError("URL is missing a 'file:' scheme")
if os.name == 'nt':
diff --git a/Lib/urllib/robotparser.py b/Lib/urllib/robotparser.py
index 8d0311d96f5e0b4..d50cb70e03813ea 100644
--- a/Lib/urllib/robotparser.py
+++ b/Lib/urllib/robotparser.py
@@ -30,6 +30,8 @@ class RobotFileParser:
def __init__(self, url=''):
self.entries = []
self.groups = {}
+ # Merged entries in self.groups -> number of agents sharing them.
+ self._merged_refs = {}
self.sitemaps = []
self.default_entry = None
self.disallow_all = False
@@ -62,7 +64,9 @@ def set_url(self, url):
if isinstance(url, urllib.request.Request):
url = url.full_url
- self.host, self.path = urllib.parse.urlsplit(url)[1:3]
+ parts = urllib.parse.urlsplit(url)
+ self.host = parts.netloc
+ self.path = parts.path
def read(self):
"""Reads the robots.txt URL and feeds it to the parser."""
@@ -88,12 +92,32 @@ def read(self):
def _add_entry(self, entry):
self.entries.append(entry)
+ to_merge = {}
for agent in entry.useragents:
agent = agent.lower()
- if agent not in self.groups:
+ old = self.groups.get(agent)
+ if old is None:
self.groups[agent] = entry
- else:
- self.groups[agent] = merge_entries(self.groups[agent], entry)
+ elif old is not entry:
+ to_merge.setdefault(old, set()).add(agent)
+ if not to_merge:
+ return
+ refs = self._merged_refs
+ entry_agents = set(entry.useragents)
+ for old, agents in to_merge.items():
+ if refs.get(old) == len(agents):
+ # No other agent shares this merged entry, so it can be
+ # extended in place instead of being copied again.
+ _merge_into(old, entry, entry_agents)
+ continue
+ new = merge_entries(old, entry, entry_agents)
+ for agent in agents:
+ self.groups[agent] = new
+ refs[new] = len(agents)
+ if old in refs:
+ refs[old] -= len(agents)
+ if not refs[old]:
+ del refs[old]
def parse(self, lines):
"""Parse the input lines from a robots.txt file.
@@ -172,7 +196,8 @@ def _find_entry(self, useragent):
entry = self.groups.get(useragent.lower())
if entry is not None:
return entry
- for entry in self.groups.values():
+ # Many agents can share the same entry; check each entry only once.
+ for entry in dict.fromkeys(self.groups.values()):
if entry.applies_to(useragent):
return entry
return self.groups.get('*')
@@ -359,10 +384,21 @@ def translate_pattern(path):
parts[-1] = f'.*{parts[-1]}'
return ''.join(parts)
-def merge_entries(e1, e2):
+def merge_entries(e1, e2, e2_agents=None):
entry = Entry()
- entry.useragents = list(filter(set(e2.useragents).__contains__, e1.useragents))
- entry.rulelines = e1.rulelines + e2.rulelines
- entry.delay = e1.delay if e2.delay is None else e2.delay
- entry.req_rate = e1.req_rate if e2.req_rate is None else e2.req_rate
+ entry.useragents = e1.useragents
+ entry.rulelines = e1.rulelines.copy()
+ entry.delay = e1.delay
+ entry.req_rate = e1.req_rate
+ _merge_into(entry, e2, e2_agents)
return entry
+
+def _merge_into(e1, e2, e2_agents=None):
+ if e2_agents is None:
+ e2_agents = set(e2.useragents)
+ e1.useragents = list(filter(e2_agents.__contains__, e1.useragents))
+ e1.rulelines.extend(e2.rulelines)
+ if e2.delay is not None:
+ e1.delay = e2.delay
+ if e2.req_rate is not None:
+ e1.req_rate = e2.req_rate
diff --git a/Lib/uuid.py b/Lib/uuid.py
index 4bdcb67775a2ea1..485f5bd8477cdd3 100644
--- a/Lib/uuid.py
+++ b/Lib/uuid.py
@@ -43,7 +43,7 @@
>>> x.bytes
b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'
- # make a UUID from a 16-byte string
+ # make a UUID from a 16-byte bytes object
>>> uuid.UUID(bytes=x.bytes)
UUID('00010203-0405-0607-0809-0a0b0c0d0e0f')
@@ -59,11 +59,11 @@
import os
import sys
import time
+lazy import warnings
from enum import Enum, _simple_enum
-
-__author__ = 'Ka-Ping Yee '
+# Original author: Ka-Ping Yee
# The recognized platforms - known behaviors
if sys.platform in {'win32', 'darwin', 'emscripten', 'wasi'}:
@@ -99,6 +99,7 @@ class SafeUUID:
_UINT_128_MAX = (1 << 128) - 1
+
# 128-bit mask to clear the variant and version bits of a UUID integral value
_RFC_4122_CLEARFLAGS_MASK = ~((0xf000 << 64) | (0xc000 << 48))
# RFC 4122 variant bits and version bits to activate on a UUID integral value.
@@ -110,6 +111,46 @@ class SafeUUID:
_RFC_4122_VERSION_7_FLAGS = ((7 << 76) | (0x8000 << 48))
_RFC_4122_VERSION_8_FLAGS = ((8 << 76) | (0x8000 << 48))
+_random_hook = None
+_time_hook = None
+
+
+def _gen_random(size):
+ if _random_hook is None:
+ return os.urandom(size)
+ else:
+ return _random_hook(size)
+
+
+def _gen_time():
+ if _time_hook is None:
+ return time.time_ns()
+ else:
+ return _time_hook()
+
+
+def _install_py_hooks(*, random_func, time_func):
+ global _random_hook
+ global _time_hook
+ global _last_timestamp_v7
+ _random_hook = random_func
+ _time_hook = time_func
+ # Reset _last_timestamp_v7 for repeatability of tests
+ _last_timestamp_v7 = None
+
+
+# Import optional C extension at toplevel, to help disabling it when testing
+try:
+ import _uuid
+ _generate_time_safe = getattr(_uuid, "generate_time_safe", None)
+ _has_stable_extractable_node = _uuid.has_stable_extractable_node
+ _UuidCreate = getattr(_uuid, "UuidCreate", None)
+except ImportError:
+ _uuid = None
+ _generate_time_safe = None
+ _has_stable_extractable_node = False
+ _UuidCreate = None
+
class UUID:
"""Instances of the UUID class represent UUIDs as specified in RFC 4122.
@@ -118,19 +159,19 @@ class UUID:
'12345678-1234-1234-1234-123456789abc'. The UUID constructor accepts
five possible forms: a similar string of hexadecimal digits, or a tuple
of six integer fields (with 32-bit, 16-bit, 16-bit, 8-bit, 8-bit, and
- 48-bit values respectively) as an argument named 'fields', or a string
- of 16 bytes (with all the integer fields in big-endian order) as an
- argument named 'bytes', or a string of 16 bytes (with the first three
- fields in little-endian order) as an argument named 'bytes_le', or a
- single 128-bit integer as an argument named 'int'.
+ 48-bit values respectively) as an argument named 'fields', or a 16-byte
+ bytes object (with all the integer fields in big-endian order) as an
+ argument named 'bytes', or a 16-byte bytes object (with the first three
+ fields in little-endian order) as an argument named 'bytes_le', or a single
+ 128-bit integer as an argument named 'int'.
UUIDs have these read-only attributes:
- bytes the UUID as a 16-byte string (containing the six
+ bytes the UUID as a 16-byte bytes object (containing the six
integer fields in big-endian byte order)
- bytes_le the UUID as a 16-byte string (with time_low, time_mid,
- and time_hi_version in little-endian byte order)
+ bytes_le the UUID as a 16-byte bytes object (with time_low,
+ time_mid, and time_hi_version in little-endian byte order)
fields a tuple of the six integer fields of the UUID,
which are also available as six individual attributes
@@ -179,7 +220,7 @@ def __init__(self, hex=None, bytes=None, bytes_le=None, fields=None,
int=None, version=None,
*, is_safe=SafeUUID.unknown):
r"""Create a UUID from either a string of 32 hexadecimal digits,
- a string of 16 bytes as the 'bytes' argument, a string of 16 bytes
+ a 16-byte bytes object as the 'bytes' argument, a 16-byte bytes object
in little-endian order as the 'bytes_le' argument, a tuple of six
integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version,
8-bit clock_seq_hi_variant, 8-bit clock_seq_low, 48-bit node) as
@@ -191,9 +232,9 @@ def __init__(self, hex=None, bytes=None, bytes_le=None, fields=None,
UUID('{12345678-1234-5678-1234-567812345678}')
UUID('12345678123456781234567812345678')
UUID('urn:uuid:12345678-1234-5678-1234-567812345678')
- UUID(bytes='\x12\x34\x56\x78'*4)
- UUID(bytes_le='\x78\x56\x34\x12\x34\x12\x78\x56' +
- '\x12\x34\x56\x78\x12\x34\x56\x78')
+ UUID(bytes=b'\x12\x34\x56\x78'*4)
+ UUID(bytes_le=b'\x78\x56\x34\x12\x34\x12\x78\x56' +
+ b'\x12\x34\x56\x78\x12\x34\x56\x78')
UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678))
UUID(int=0x12345678123456781234567812345678)
@@ -219,22 +260,24 @@ def __init__(self, hex=None, bytes=None, bytes_le=None, fields=None,
raise ValueError('badly formed hexadecimal UUID string')
int = int_(hex, 16)
elif bytes_le is not None:
+ if not isinstance(bytes_le, bytes_):
+ raise TypeError('bytes_le must be a bytes object')
if len(bytes_le) != 16:
raise ValueError('bytes_le is not a 16-char string')
- assert isinstance(bytes_le, bytes_), repr(bytes_le)
bytes = (bytes_le[4-1::-1] + bytes_le[6-1:4-1:-1] +
bytes_le[8-1:6-1:-1] + bytes_le[8:])
int = int_.from_bytes(bytes) # big endian
elif bytes is not None:
+ if not isinstance(bytes, bytes_):
+ raise TypeError('bytes must be a bytes object')
if len(bytes) != 16:
raise ValueError('bytes is not a 16-char string')
- assert isinstance(bytes, bytes_), repr(bytes)
int = int_.from_bytes(bytes) # big endian
elif fields is not None:
if len(fields) != 6:
raise ValueError('fields is not a 6-tuple')
(time_low, time_mid, time_hi_version,
- clock_seq_hi_variant, clock_seq_low, node) = fields
+ clock_seq_hi_variant, clock_seq_low, node) = fields
if not 0 <= time_low < (1 << 32):
raise ValueError('field 1 out of range (need a 32-bit value)')
if not 0 <= time_mid < (1 << 16):
@@ -249,7 +292,7 @@ def __init__(self, hex=None, bytes=None, bytes_le=None, fields=None,
raise ValueError('field 6 out of range (need a 48-bit value)')
clock_seq = (clock_seq_hi_variant << 8) | clock_seq_low
int = ((time_low << 96) | (time_mid << 80) |
- (time_hi_version << 64) | (clock_seq << 48) | node)
+ (time_hi_version << 64) | (clock_seq << 48) | node)
if not 0 <= int <= _UINT_128_MAX:
raise ValueError('int is out of range (need a 128-bit value)')
if version is not None:
@@ -629,19 +672,6 @@ def _netstat_getnode():
return _find_mac_under_heading('netstat', '-ian', b'Address')
-# Import optional C extension at toplevel, to help disabling it when testing
-try:
- import _uuid
- _generate_time_safe = getattr(_uuid, "generate_time_safe", None)
- _has_stable_extractable_node = _uuid.has_stable_extractable_node
- _UuidCreate = getattr(_uuid, "UuidCreate", None)
-except ImportError:
- _uuid = None
- _generate_time_safe = None
- _has_stable_extractable_node = False
- _UuidCreate = None
-
-
def _unix_getnode():
"""Get the hardware address on Unix using the _uuid extension module."""
if _generate_time_safe and _has_stable_extractable_node:
@@ -774,7 +804,7 @@ def uuid3(namespace, name):
def uuid4():
"""Generate a random UUID."""
- int_uuid_4 = int.from_bytes(os.urandom(16))
+ int_uuid_4 = int.from_bytes(_gen_random(16))
int_uuid_4 &= _RFC_4122_CLEARFLAGS_MASK
int_uuid_4 |= _RFC_4122_VERSION_4_FLAGS
return UUID._from_int(int_uuid_4)
@@ -834,7 +864,8 @@ def uuid6(node=None, clock_seq=None):
_last_counter_v7 = 0 # 42-bit counter
def _uuid7_get_counter_and_tail():
- rand = int.from_bytes(os.urandom(10))
+ rand = int.from_bytes(_gen_random(10))
+
# 42-bit counter with MSB set to 0
counter = (rand >> 32) & 0x1ff_ffff_ffff
# 32-bit random data
@@ -863,7 +894,7 @@ def uuid7():
global _last_timestamp_v7
global _last_counter_v7
- nanoseconds = time.time_ns()
+ nanoseconds = _gen_time()
timestamp_ms = nanoseconds // 1_000_000
if _last_timestamp_v7 is None or timestamp_ms > _last_timestamp_v7:
@@ -879,7 +910,7 @@ def uuid7():
counter, tail = _uuid7_get_counter_and_tail()
else:
# 32-bit random data
- tail = int.from_bytes(os.urandom(4))
+ tail = int.from_bytes(_gen_random(4))
unix_ts_ms = timestamp_ms & 0xffff_ffff_ffff
counter_msbs = counter >> 30
@@ -932,6 +963,21 @@ def uuid8(a=None, b=None, c=None):
return UUID._from_int(int_uuid_8)
+_py_uuid4 = uuid4
+_py_uuid7 = uuid7
+_py_UUID = UUID
+try:
+ from _uuid import UUID, uuid4, uuid7
+ from _uuid import _install_c_hooks as _install_c_hooks
+except ImportError:
+ _c_UUID = None
+ _c_uuid4 = None
+ _c_uuid7 = None
+else:
+ _c_UUID = UUID
+ _c_uuid4 = uuid4
+ _c_uuid7 = uuid7
+
def main():
"""Run the uuid command line interface."""
uuid_funcs = {
@@ -1009,5 +1055,12 @@ def main():
NIL = UUID('00000000-0000-0000-0000-000000000000')
MAX = UUID('ffffffff-ffff-ffff-ffff-ffffffffffff')
+def __getattr__(name):
+ if name == "__author__":
+ warnings._deprecated("__author__", remove=(3, 20))
+ return 'Ka-Ping Yee' # Do not change
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+
+
if __name__ == "__main__":
main()
diff --git a/Lib/venv/__init__.py b/Lib/venv/__init__.py
index bd2762d55ef6961..0e9ee18892b9338 100644
--- a/Lib/venv/__init__.py
+++ b/Lib/venv/__init__.py
@@ -27,16 +27,15 @@ class EnvBuilder:
By default, the builder makes the system (global) site-packages dir
*un*available to the created environment.
- If invoked using the Python -m option, the default is to use copying
- on Windows platforms but symlinks elsewhere. If instantiated some
- other way, the default is to *not* use symlinks.
+ By default, the builder uses copying on Windows platforms but symlinks
+ elsewhere, matching the behaviour when invoked using the Python -m option.
:param system_site_packages: If True, the system (global) site-packages
dir is available to created environments.
:param clear: If True, delete the contents of the environment directory if
it already exists, before environment creation.
:param symlinks: If True, attempt to symlink rather than copy files into
- virtual environment.
+ virtual environment. If None, use the platform default.
:param upgrade: If True, upgrade an existing virtual environment.
:param with_pip: If True, ensure pip is installed in the virtual
environment
@@ -47,11 +46,11 @@ class EnvBuilder:
"""
def __init__(self, system_site_packages=False, clear=False,
- symlinks=False, upgrade=False, with_pip=False, prompt=None,
+ symlinks=None, upgrade=False, with_pip=False, prompt=None,
upgrade_deps=False, *, scm_ignore_files=frozenset()):
self.system_site_packages = system_site_packages
self.clear = clear
- self.symlinks = symlinks
+ self.symlinks = os.name != 'nt' if symlinks is None else symlinks
self.upgrade = upgrade
self.with_pip = with_pip
self.orig_prompt = prompt
@@ -142,6 +141,12 @@ def ensure_directories(self, env_dir):
"""
def create_if_needed(d):
+ path = env_dir
+ for part in os.path.relpath(d, env_dir).split(os.sep)[:-1]:
+ path = os.path.join(path, part)
+ if os.path.islink(path) or os.path.isjunction(path):
+ raise ValueError(f'Refusing to create a venv in {env_dir} '
+ f'because {path} is a link.')
if not os.path.exists(d):
os.makedirs(d)
elif os.path.islink(d) or os.path.isfile(d):
@@ -267,6 +272,8 @@ def symlink_or_copy(self, src, dst, relative_symlinks_ok=False):
switch to a different set of files instead.)
"""
assert os.name != 'nt'
+ if os.path.islink(dst) and not os.path.exists(dst):
+ os.unlink(dst)
force_copy = not self.symlinks
if not force_copy:
try:
@@ -445,14 +452,15 @@ def setup_python(self, context):
def _call_new_python(self, context, *py_args, **kwargs):
"""Executes the newly created Python using safe-ish options"""
# gh-98251: We do not want to just use '-I' because that masks
- # legitimate user preferences (such as not writing bytecode). All we
- # really need is to ensure that the path variables do not overrule
- # normal venv handling.
+ # legitimate user preferences (such as not writing bytecode).
args = [context.env_exec_cmd, *py_args]
kwargs['env'] = env = os.environ.copy()
env['VIRTUAL_ENV'] = context.env_dir
env.pop('PYTHONHOME', None)
env.pop('PYTHONPATH', None)
+ # Keep the working directory off sys.path, including in the
+ # subprocess that ensurepip starts to run pip.
+ env['PYTHONSAFEPATH'] = '1'
kwargs['cwd'] = context.env_dir
kwargs['executable'] = context.env_exec_cmd
subprocess.check_output(args, **kwargs)
@@ -519,6 +527,11 @@ def quote_ps1(s):
def quote_bat(s):
return s
+ def quote_fish(s):
+ # gh-160782: fish reads \\ and \' as escapes inside single quotes
+ s = s.replace('\\', '\\\\').replace("'", "\\'")
+ return f"'{s}'"
+
# gh-124651: need to quote the template strings properly
quote = shlex.quote
script_path = context.script_path
@@ -526,6 +539,8 @@ def quote_bat(s):
quote = quote_ps1
elif script_path.endswith('.bat'):
quote = quote_bat
+ elif script_path.endswith('.fish'):
+ quote = quote_fish
else:
# fallbacks to POSIX shell compliant quote
quote = shlex.quote
@@ -592,11 +607,10 @@ def skip_file(f):
'may be binary: %s', srcfile, e)
continue
if new_data == data:
- shutil.copy(srcfile, dstfile)
+ shutil.copyfile(srcfile, dstfile)
else:
with open(dstfile, 'wb') as f:
f.write(new_data)
- shutil.copymode(srcfile, dstfile)
def upgrade_dependencies(self, context):
logger.debug(
@@ -607,7 +621,7 @@ def upgrade_dependencies(self, context):
def create(env_dir, system_site_packages=False, clear=False,
- symlinks=False, with_pip=False, prompt=None, upgrade_deps=False,
+ symlinks=None, with_pip=False, prompt=None, upgrade_deps=False,
*, scm_ignore_files=frozenset()):
"""Create a virtual environment in a directory."""
builder = EnvBuilder(system_site_packages=system_site_packages,
diff --git a/Lib/venv/scripts/posix/activate.csh b/Lib/venv/scripts/posix/activate.csh
index 2a3fa835476ab9b..7226034df0f3941 100644
--- a/Lib/venv/scripts/posix/activate.csh
+++ b/Lib/venv/scripts/posix/activate.csh
@@ -16,10 +16,12 @@ setenv PATH "$VIRTUAL_ENV/"__VENV_BIN_NAME__":$PATH"
setenv VIRTUAL_ENV_PROMPT __VENV_PROMPT__
-set _OLD_VIRTUAL_PROMPT="$prompt"
+if ($?prompt) then
+ set _OLD_VIRTUAL_PROMPT="$prompt"
-if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then
- set prompt = "("__VENV_PROMPT__") $prompt:q"
+ if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then
+ set prompt = "("__VENV_PROMPT__") $prompt:q"
+ endif
endif
alias pydoc python -m pydoc
diff --git a/Lib/weakref.py b/Lib/weakref.py
index af7244553c908ce..fc895d4033300ba 100644
--- a/Lib/weakref.py
+++ b/Lib/weakref.py
@@ -22,6 +22,7 @@
from _weakrefset import WeakSet
import _collections_abc # Import after _weakref to avoid circular import.
+import copyreg
import sys
import itertools
@@ -35,6 +36,12 @@
_collections_abc.MutableSet.register(WeakSet)
+
+# Pickle reconstructs a reference to a dead object as this singleton -- all
+# dead references are interchangeable. Born dead: nothing else holds the set.
+_dead_ref = ref(set())
+
+
class WeakMethod(ref):
"""
A custom `weakref.ref` subclass which simulates a weak reference to
@@ -89,12 +96,34 @@ def __ne__(self, other):
__hash__ = ref.__hash__
+# Pickling support for weak methods. A WeakMethod is reduced to a weak
+# reference to its instance; the bound method is rebuilt on unpickling by
+# looking the function up on the instance. The callback is not preserved.
+
+def _restore_weakmethod(obj_ref, name):
+ return WeakMethod(getattr(obj_ref(), name))
+
+
+def _reduce_weakmethod(self):
+ meth = self()
+ if meth is None:
+ raise TypeError(
+ "cannot pickle a weak reference to a dead object")
+ return (_restore_weakmethod, (ref(meth.__self__), meth.__func__.__name__))
+
+copyreg.pickle(WeakMethod, _reduce_weakmethod)
+
+
class WeakValueDictionary(_collections_abc.MutableMapping):
"""Mapping class that references values weakly.
Entries in the dictionary will be discarded when no strong
reference to the value exists anymore
"""
+ # Slots give __getstate__() a uniform (dict, slots) shape for __reduce__.
+ # __dict__ carries user attributes; the removal callback needs __weakref__.
+ __slots__ = '__dict__', '__weakref__', 'data', '_remove'
+
# We inherit the constructor without worrying about the input
# dictionary; since it uses our .update() method, we get the right
# checks (if the other dictionary is a WeakValueDictionary,
@@ -157,6 +186,16 @@ def __deepcopy__(self, memo):
new[deepcopy(key, memo)] = o
return new
+ def __reduce__(self):
+ # Pickle the values as weak references; data and _remove are rebuilt
+ # by the reconstructor. Copying uses __copy__/__deepcopy__ instead.
+ dict, slots = self.__getstate__()
+ for name in ('data', '_remove'):
+ slots.pop(name, None)
+ state = (dict, slots) if dict or slots else None
+ items = [(key, ref(o)) for key, o in self.items()]
+ return (_restore_weakvaluedict, (self.__class__, items), state)
+
def get(self, key, default=None):
try:
wr = self.data[key]
@@ -274,6 +313,16 @@ def __ror__(self, other):
return NotImplemented
+def _restore_weakvaluedict(cls, items):
+ self = cls.__new__(cls)
+ WeakValueDictionary.__init__(self)
+ for key, r in items:
+ o = r()
+ if o is not None:
+ self[key] = o
+ return self
+
+
class KeyedRef(ref):
"""Specialized reference that includes a key corresponding to the value.
@@ -305,6 +354,8 @@ class WeakKeyDictionary(_collections_abc.MutableMapping):
can be especially useful with objects that override attribute
accesses.
"""
+ # See the comment on WeakValueDictionary.__slots__.
+ __slots__ = '__dict__', '__weakref__', 'data', '_remove'
def __init__(self, dict=None):
self.data = {}
@@ -353,6 +404,16 @@ def __deepcopy__(self, memo):
new[o] = deepcopy(value, memo)
return new
+ def __reduce__(self):
+ # Pickle the keys as weak references; data and _remove are rebuilt
+ # by the reconstructor. Copying uses __copy__/__deepcopy__ instead.
+ dict, slots = self.__getstate__()
+ for name in ('data', '_remove'):
+ slots.pop(name, None)
+ state = (dict, slots) if dict or slots else None
+ items = [(ref(key), value) for key, value in self.items()]
+ return (_restore_weakkeydict, (self.__class__, items), state)
+
def get(self, key, default=None):
return self.data.get(ref(key),default)
@@ -439,6 +500,16 @@ def __ror__(self, other):
return NotImplemented
+def _restore_weakkeydict(cls, items):
+ self = cls.__new__(cls)
+ WeakKeyDictionary.__init__(self)
+ for r, value in items:
+ key = r()
+ if key is not None:
+ self[key] = value
+ return self
+
+
class finalize:
"""Class for finalization of weakrefable objects
diff --git a/Lib/webbrowser.py b/Lib/webbrowser.py
index ec8b544a6b05235..260208440230dca 100644
--- a/Lib/webbrowser.py
+++ b/Lib/webbrowser.py
@@ -505,7 +505,8 @@ def register_standard_browsers():
# macOS can use below Unix support (but we prefer using the macOS
# specific stuff)
- if sys.platform == "ios":
+ if sys.platform in {"ios", "visionos"}:
+ # iOS and visionOS provide a browser; tvOS and watchOS don't.
register("iosbrowser", None, IOSBrowser(), preferred=True)
if sys.platform == "serenityos":
@@ -744,9 +745,10 @@ def open(self, url, new=0, autoraise=True):
return not rc
#
-# Platform support for iOS
+# Platform support for Apple Mobile platforms that provide a browser
+# (i.e., iOS and visionOS)
#
-if sys.platform == "ios":
+if sys.platform in {"ios", "visionos"}:
from _ios_support import objc
if objc:
# If objc exists, we know ctypes is also importable.
diff --git a/Lib/wsgiref/validate.py b/Lib/wsgiref/validate.py
index 1a1853cd63a0d2a..cc572e8a179d1eb 100644
--- a/Lib/wsgiref/validate.py
+++ b/Lib/wsgiref/validate.py
@@ -334,7 +334,7 @@ def check_environ(environ):
# @@: these need filling out:
if environ['REQUEST_METHOD'] not in (
- 'GET', 'HEAD', 'POST', 'OPTIONS', 'PATCH', 'PUT', 'DELETE', 'TRACE'):
+ 'GET', 'HEAD', 'POST', 'OPTIONS', 'PATCH', 'PUT', 'DELETE', 'QUERY', 'TRACE'):
warnings.warn(
"Unknown REQUEST_METHOD: %r" % environ['REQUEST_METHOD'],
WSGIWarning)
diff --git a/Lib/xml/dom/expatbuilder.py b/Lib/xml/dom/expatbuilder.py
index 7dd667bf3fbe042..e3917c1cc682880 100644
--- a/Lib/xml/dom/expatbuilder.py
+++ b/Lib/xml/dom/expatbuilder.py
@@ -30,7 +30,8 @@
from xml.dom import xmlbuilder, minidom, Node
from xml.dom import EMPTY_NAMESPACE, EMPTY_PREFIX, XMLNS_NAMESPACE
from xml.parsers import expat
-from xml.dom.minidom import _append_child, _set_attribute_node
+from xml.dom.minidom import (_append_child, _set_attribute_node,
+ _XML_WHITESPACE)
from xml.dom.NodeFilter import NodeFilter
TEXT_NODE = Node.TEXT_NODE
@@ -159,7 +160,6 @@ def getParser(self):
self._intern_setdefault = self._parser.intern.setdefault
self._parser.buffer_text = True
self._parser.ordered_attributes = True
- self._parser.specified_attributes = True
self.install(self._parser)
return self._parser
@@ -352,11 +352,13 @@ def start_element_handler(self, name, attributes):
self.curNode = node
if attributes:
+ specified = self.getParser().GetSpecifiedAttributeCount()
for i in range(0, len(attributes), 2):
a = minidom.Attr(attributes[i], EMPTY_NAMESPACE,
None, EMPTY_PREFIX)
value = attributes[i+1]
a.value = value
+ a.specified = i < specified
a.ownerDocument = self.document
_set_attribute_node(node, a)
@@ -412,7 +414,8 @@ def _handle_white_text_nodes(self, node, info):
# whitespace.
L = []
for child in node.childNodes:
- if child.nodeType == TEXT_NODE and not child.data.strip():
+ if (child.nodeType == TEXT_NODE
+ and not child.data.strip(_XML_WHITESPACE)):
L.append(child)
# Remove ignorable whitespace from the tree.
@@ -760,6 +763,7 @@ def start_element_handler(self, name, attributes):
node._ensure_attributes()
_attrs = node._attrs
_attrsNS = node._attrsNS
+ specified = self.getParser().GetSpecifiedAttributeCount()
for i in range(0, len(attributes), 2):
aname = attributes[i]
value = attributes[i+1]
@@ -775,6 +779,7 @@ def start_element_handler(self, name, attributes):
_attrsNS[(EMPTY_NAMESPACE, aname)] = a
a.ownerDocument = self.document
a.value = value
+ a.specified = i < specified
a.ownerElement = node
if __debug__:
diff --git a/Lib/xml/dom/minidom.py b/Lib/xml/dom/minidom.py
index 16b33b90184dc59..fb6c1462fc5e9e6 100644
--- a/Lib/xml/dom/minidom.py
+++ b/Lib/xml/dom/minidom.py
@@ -16,9 +16,11 @@
"""
import io
+import xml
import xml.dom
-from xml.dom import EMPTY_NAMESPACE, EMPTY_PREFIX, XMLNS_NAMESPACE, domreg
+from xml.dom import (EMPTY_NAMESPACE, EMPTY_PREFIX, XML_NAMESPACE,
+ XMLNS_NAMESPACE, domreg)
from xml.dom.minicompat import *
from xml.dom.xmlbuilder import DOMImplementationLS, DocumentLS
@@ -30,6 +32,9 @@
_nodeTypes_with_children = (xml.dom.Node.ELEMENT_NODE,
xml.dom.Node.ENTITY_REFERENCE_NODE)
+# The white space characters of the XML specification (see XML 1.0, 2.3).
+_XML_WHITESPACE = " \t\r\n"
+
class Node(xml.dom.Node):
namespaceURI = None # this is non-null only for elements and attributes
@@ -79,15 +84,32 @@ def _get_lastChild(self):
if self.childNodes:
return self.childNodes[-1]
+ def _check_new_child(self, newChild, oldChild=None):
+ # Common checks for insertBefore(), appendChild() and replaceChild().
+ doc = self.ownerDocument or self
+ newChildDoc = newChild.ownerDocument
+ if newChildDoc is not doc and newChildDoc is not None:
+ raise xml.dom.WrongDocumentErr(
+ "%s was created by a different document" % repr(newChild))
+ if newChild.nodeType not in self._child_node_types:
+ raise xml.dom.HierarchyRequestErr(
+ "%s cannot be child of %s" % (repr(newChild), repr(self)))
+ if newChild is self:
+ raise xml.dom.HierarchyRequestErr(
+ "%s cannot be child of itself" % repr(self))
+ # A node without children cannot be an ancestor, and testing this
+ # first keeps appending leaf nodes linear in the depth of the tree.
+ if newChild.childNodes and _is_ancestor(newChild, self):
+ raise xml.dom.HierarchyRequestErr(
+ "%s is an ancestor of %s" % (repr(newChild), repr(self)))
+
def insertBefore(self, newChild, refChild):
if newChild.nodeType == self.DOCUMENT_FRAGMENT_NODE:
for c in tuple(newChild.childNodes):
self.insertBefore(c, refChild)
### The DOM does not clearly specify what to return in this case
return newChild
- if newChild.nodeType not in self._child_node_types:
- raise xml.dom.HierarchyRequestErr(
- "%s cannot be child of %s" % (repr(newChild), repr(self)))
+ self._check_new_child(newChild)
if newChild.parentNode is not None:
newChild.parentNode.removeChild(newChild)
if refChild is None:
@@ -117,10 +139,8 @@ def appendChild(self, node):
self.appendChild(c)
### The DOM does not clearly specify what to return in this case
return node
- if node.nodeType not in self._child_node_types:
- raise xml.dom.HierarchyRequestErr(
- "%s cannot be child of %s" % (repr(node), repr(self)))
- elif node.nodeType in _nodeTypes_with_children:
+ self._check_new_child(node)
+ if node.nodeType in _nodeTypes_with_children:
_clear_id_cache(self)
if node.parentNode is not None:
node.parentNode.removeChild(node)
@@ -133,11 +153,9 @@ def replaceChild(self, newChild, oldChild):
refChild = oldChild.nextSibling
self.removeChild(oldChild)
return self.insertBefore(newChild, refChild)
- if newChild.nodeType not in self._child_node_types:
- raise xml.dom.HierarchyRequestErr(
- "%s cannot be child of %s" % (repr(newChild), repr(self)))
if newChild is oldChild:
return
+ self._check_new_child(newChild, oldChild)
if newChild.parentNode is not None:
newChild.parentNode.removeChild(newChild)
try:
@@ -282,6 +300,72 @@ def __exit__(self, et, ev, tb):
defproperty(Node, "localName", doc="Namespace-local name of this node.")
+# PubidChar (see XML 1.0, 2.3, [13]).
+_PUBID_CHARS = frozenset(
+ " \r\n-'()+,./:=?;!*#@$_%"
+ "0123456789"
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "abcdefghijklmnopqrstuvwxyz")
+
+
+def _quote_literal(text):
+ """Quote a system literal or a public identifier.
+
+ A literal is delimited with a quote which it does not contain
+ (see XML 1.0, 2.3, [11] and [12]).
+ """
+ if "'" not in text:
+ return "'%s'" % text
+ if '"' not in text:
+ return '"%s"' % text
+ raise ValueError("a literal cannot contain both quotes: %r" % (text,))
+
+
+def _check_name(name):
+ if not xml.is_valid_name(name):
+ raise xml.dom.InvalidCharacterErr(
+ "%r is not a valid XML name" % (name,))
+
+
+def _check_prefix(prefix, namespaceURI, attribute=False):
+ if not xml.is_valid_name(prefix) or ':' in prefix:
+ raise xml.dom.InvalidCharacterErr(
+ "%r is not a valid namespace prefix" % (prefix,))
+ if not namespaceURI:
+ raise xml.dom.NamespaceErr(
+ "cannot use the prefix %r with an empty namespace" % (prefix,))
+ if prefix == "xml" and namespaceURI != XML_NAMESPACE:
+ raise xml.dom.NamespaceErr(
+ "illegal use of the 'xml' prefix for the wrong namespace")
+ if attribute and (prefix == "xmlns") != (namespaceURI == XMLNS_NAMESPACE):
+ raise xml.dom.NamespaceErr(
+ "illegal use of the 'xmlns' prefix for the wrong namespace")
+
+
+def _check_qualified_name(namespaceURI, qualifiedName, attribute=False):
+ """Check a namespace URI and a qualified name (see DOM Level 2 Core)."""
+ _check_name(qualifiedName)
+ prefix, sep, localName = qualifiedName.partition(':')
+ if sep:
+ if not localName or ':' in localName or not xml.is_valid_name(localName):
+ raise xml.dom.NamespaceErr(
+ "%r is not a valid qualified name" % (qualifiedName,))
+ _check_prefix(prefix, namespaceURI, attribute)
+ elif attribute and (qualifiedName == "xmlns") != (namespaceURI == XMLNS_NAMESPACE):
+ raise xml.dom.NamespaceErr(
+ "illegal use of the 'xmlns' attribute for the wrong namespace")
+
+
+def _is_ancestor(node, other):
+ "Returns true iff node is an ancestor of other."
+ other = other.parentNode
+ while other is not None:
+ if other is node:
+ return True
+ other = other.parentNode
+ return False
+
+
def _append_child(self, node):
# fast path with less checks; usable by DOM builders if careful
childNodes = self.childNodes
@@ -316,6 +400,109 @@ def _write_data(writer, text, attr):
text = text.replace("\t", " ")
writer.write(text)
+
+# The "xml" prefix is bound by definition and is never declared.
+_ROOT_NSMAP = {"xml": XML_NAMESPACE}
+
+
+def _bind_namespace(nsmap, inherited, prefix, uri):
+ """Bind *prefix* in *nsmap*, copying it if it is still the inherited one."""
+ if nsmap is inherited:
+ nsmap = dict(inherited)
+ nsmap[prefix] = uri
+ return nsmap
+
+
+def _in_scope_namespaces(element):
+ """Return the namespaces in scope for *element*, as written by writexml."""
+ ancestors = []
+ node = element.parentNode
+ while node is not None and node.nodeType == Node.ELEMENT_NODE:
+ ancestors.append(node)
+ node = node.parentNode
+ nsmap = _ROOT_NSMAP
+ for node in reversed(ancestors):
+ nsmap, _ = _fixup_namespaces(node, nsmap)
+ return nsmap
+
+
+def _fixup_namespaces(element, nsmap):
+ """Compute namespace declarations missing for the serialized element.
+
+ *nsmap* is the mapping of prefixes to namespace URIs in scope for the
+ element. Return the mapping in scope for its children and the list of
+ (name, value) pairs of the attributes to be written, starting with the
+ added namespace declarations. The element and its attributes are not
+ modified.
+ """
+ attrs = element._attrs
+ uri = element.namespaceURI
+ if not attrs and not uri and not nsmap.get(None):
+ # Neither the element nor its attributes need a declaration.
+ return nsmap, ()
+
+ inherited = nsmap
+ declarations = []
+ # (name, value, namespace URI, attribute) of the attributes to write.
+ entries = []
+ if attrs:
+ for attr in attrs.values():
+ name = attr.name
+ attr_uri = attr.namespaceURI
+ if (attr_uri == XMLNS_NAMESPACE or name == "xmlns"
+ or name.startswith("xmlns:")):
+ # Declarations already present in the document take precedence.
+ nsmap = _bind_namespace(
+ nsmap, inherited,
+ attr.localName if attr.prefix else None, attr.value)
+ attr_uri = None
+ elif attr_uri == XML_NAMESPACE:
+ # The xml prefix is bound by definition.
+ attr_uri = None
+ entries.append((name, attr.value, attr_uri, attr))
+
+ if uri:
+ prefix, _, _ = element.tagName.rpartition(':')
+ prefix = prefix or None
+ if nsmap.get(prefix) != uri:
+ nsmap = _bind_namespace(nsmap, inherited, prefix, uri)
+ declarations.append(("xmlns:" + prefix if prefix else "xmlns", uri))
+ elif nsmap.get(None) and ':' not in element.tagName:
+ # The element is in no namespace, undeclare the default one.
+ nsmap = _bind_namespace(nsmap, inherited, None, None)
+ declarations.append(("xmlns", ""))
+
+ items = []
+ prefixes = None # namespace URI -> prefix, built only when needed
+ n = 0
+ for name, value, attr_uri, attr in entries:
+ if attr_uri is not None:
+ # Unprefixed attributes are in no namespace, so an attribute
+ # in a namespace always needs a prefix.
+ prefix, _, _ = name.rpartition(':')
+ if not prefix:
+ # Reuse a prefix bound to the namespace, or invent one.
+ if prefixes is None:
+ prefixes = {u: p for p, u in nsmap.items()
+ if p is not None}
+ prefix = prefixes.get(attr_uri)
+ if prefix is None:
+ while nsmap.get("ns%d" % n) is not None:
+ n += 1
+ prefix = "ns%d" % n
+ name = "%s:%s" % (prefix, attr.localName)
+ if nsmap.get(prefix) != attr_uri:
+ nsmap = _bind_namespace(nsmap, inherited, prefix, attr_uri)
+ declarations.append(("xmlns:" + prefix, attr_uri))
+ if prefixes is not None:
+ prefixes[attr_uri] = prefix
+ items.append((name, value))
+
+ if declarations:
+ return nsmap, declarations + items
+ return nsmap, items
+
+
def _get_elements_by_tagName_helper(parent, name, rc):
for node in parent.childNodes:
if node.nodeType == Node.ELEMENT_NODE and \
@@ -344,12 +531,15 @@ class DocumentFragment(Node):
Node.CDATA_SECTION_NODE,
Node.ENTITY_REFERENCE_NODE,
Node.PROCESSING_INSTRUCTION_NODE,
- Node.COMMENT_NODE,
- Node.NOTATION_NODE)
+ Node.COMMENT_NODE)
def __init__(self):
self.childNodes = NodeList()
+ def writexml(self, writer, indent="", addindent="", newl=""):
+ for node in self.childNodes:
+ node.writexml(writer, indent, addindent, newl)
+
class Attr(Node):
__slots__=('_name', '_value', 'namespaceURI',
@@ -412,11 +602,8 @@ def _get_prefix(self):
return self._prefix
def _set_prefix(self, prefix):
- nsuri = self.namespaceURI
- if prefix == "xmlns":
- if nsuri and nsuri != XMLNS_NAMESPACE:
- raise xml.dom.NamespaceErr(
- "illegal use of 'xmlns' prefix for the wrong namespace")
+ if prefix is not None:
+ _check_prefix(prefix, self.namespaceURI, True)
self._prefix = prefix
if prefix is None:
newName = self.localName
@@ -620,6 +807,12 @@ def setNamedItem(self, node):
if not isinstance(node, Attr):
raise xml.dom.HierarchyRequestErr(
"%s cannot be child of %s" % (repr(node), repr(self)))
+ owner = self._ownerElement
+ if node.ownerDocument not in (None, owner.ownerDocument):
+ raise xml.dom.WrongDocumentErr(
+ "%s was created by another document" % repr(node))
+ if node.ownerElement not in (None, owner):
+ raise xml.dom.InuseAttributeErr("attribute node already owned")
old = self._attrs.get(node.name)
if old:
old.unlink()
@@ -758,6 +951,7 @@ def getAttributeNS(self, namespaceURI, localName):
def setAttribute(self, attname, value):
attr = self.getAttributeNode(attname)
if attr is None:
+ _check_name(attname)
attr = Attr(attname)
attr.value = value # also sets nodeValue
attr.ownerDocument = self.ownerDocument
@@ -768,6 +962,7 @@ def setAttribute(self, attname, value):
_clear_id_cache(self)
def setAttributeNS(self, namespaceURI, qualifiedName, value):
+ _check_qualified_name(namespaceURI, qualifiedName, True)
prefix, localname = _nssplit(qualifiedName)
attr = self.getAttributeNodeNS(namespaceURI, localname)
if attr is None:
@@ -795,6 +990,9 @@ def getAttributeNodeNS(self, namespaceURI, localName):
return self._attrsNS.get((namespaceURI, localName))
def setAttributeNode(self, attr):
+ if attr.ownerDocument not in (None, self.ownerDocument):
+ raise xml.dom.WrongDocumentErr(
+ "%s was created by another document" % repr(attr))
if attr.ownerElement not in (None, self):
raise xml.dom.InuseAttributeErr("attribute node already owned")
self._ensure_attributes()
@@ -816,22 +1014,17 @@ def setAttributeNode(self, attr):
setAttributeNodeNS = setAttributeNode
def removeAttribute(self, name):
- if self._attrsNS is None:
- raise xml.dom.NotFoundErr()
- try:
- attr = self._attrs[name]
- except KeyError:
- raise xml.dom.NotFoundErr()
- self.removeAttributeNode(attr)
+ # The DOM specifies that removing an absent attribute has no effect.
+ if self._attrs is not None:
+ attr = self._attrs.get(name)
+ if attr is not None:
+ self.removeAttributeNode(attr)
def removeAttributeNS(self, namespaceURI, localName):
- if self._attrsNS is None:
- raise xml.dom.NotFoundErr()
- try:
- attr = self._attrsNS[(namespaceURI, localName)]
- except KeyError:
- raise xml.dom.NotFoundErr()
- self.removeAttributeNode(attr)
+ if self._attrsNS is not None:
+ attr = self._attrsNS.get((namespaceURI, localName))
+ if attr is not None:
+ self.removeAttributeNode(attr)
def removeAttributeNode(self, node):
if node is None:
@@ -879,7 +1072,8 @@ def getElementsByTagNameNS(self, namespaceURI, localName):
def __repr__(self):
return "" % (self.tagName, id(self))
- def writexml(self, writer, indent="", addindent="", newl=""):
+ def writexml(self, writer, indent="", addindent="", newl="", *,
+ _nsmap=None):
"""Write an XML element to a file-like object
Write the element to the writer object that must provide
@@ -888,13 +1082,14 @@ def writexml(self, writer, indent="", addindent="", newl=""):
# indent = current indentation
# addindent = indentation to add to higher levels
# newl = newline string
+ if _nsmap is None:
+ _nsmap = _in_scope_namespaces(self)
writer.write(indent+"<" + self.tagName)
- attrs = self._get_attributes()
-
- for a_name in attrs.keys():
+ nsmap, items = _fixup_namespaces(self, _nsmap)
+ for a_name, value in items:
writer.write(" %s=\"" % a_name)
- _write_data(writer, attrs[a_name].value, True)
+ _write_data(writer, value, True)
writer.write("\"")
if self.childNodes:
writer.write(">")
@@ -902,15 +1097,46 @@ def writexml(self, writer, indent="", addindent="", newl=""):
self.childNodes[0].nodeType in (
Node.TEXT_NODE, Node.CDATA_SECTION_NODE)):
self.childNodes[0].writexml(writer, '', '', '')
+ elif self._preserves_whitespace():
+ # Adding whitespace here would change the content.
+ for node in self.childNodes:
+ node.writexml(writer, '', '', '')
else:
writer.write(newl)
for node in self.childNodes:
- node.writexml(writer, indent+addindent, addindent, newl)
+ if type(node).writexml is Element.writexml:
+ # Pass the namespaces in scope to the standard
+ # implementation; an overridden writexml() has the
+ # documented signature and computes them itself.
+ node.writexml(writer, indent+addindent, addindent,
+ newl, _nsmap=nsmap)
+ else:
+ node.writexml(writer, indent+addindent, addindent,
+ newl)
writer.write(indent)
writer.write("%s>%s" % (self.tagName, newl))
else:
writer.write("/>%s"%(newl))
+ def _preserves_whitespace(self):
+ """Returns true iff whitespace in the content is significant.
+
+ This is the case if the element is marked with xml:space="preserve",
+ if the DTD declares that its content model is not element content,
+ or, in absence of such declaration, if it contains text.
+ """
+ if self.getAttribute("xml:space") == "preserve":
+ return True
+ doc = self.ownerDocument
+ info = doc and doc._get_elem_info(self)
+ if info is not None:
+ # Only whitespace in element content is ignorable
+ # (see XML 1.0, 3.2.1).
+ return not info.isElementContent()
+ return any(node.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE)
+ and node.data.strip(_XML_WHITESPACE)
+ for node in self.childNodes)
+
def _get_attributes(self):
self._ensure_attributes()
return NamedNodeMap(self._attrs, self._attrsNS, self)
@@ -1023,7 +1249,20 @@ def _set_nodeName(self, value):
nodeName = property(_get_nodeName, _set_nodeName)
def writexml(self, writer, indent="", addindent="", newl=""):
- writer.write("%s%s %s?>%s" % (indent,self.target, self.data, newl))
+ target = self.target
+ # PITarget is a Name, except the names matching "xml" in any case
+ # (see XML 1.0, 2.6, [17]).
+ _check_name(target)
+ if target.lower() == "xml":
+ raise ValueError("%r is a reserved processing instruction target"
+ % (target,))
+ data = self.data
+ # The data cannot contain "?>", which ends the instruction
+ # (see XML 1.0, 2.6, [16]).
+ if "?>" in data:
+ raise ValueError("'?>' is not allowed in a processing "
+ "instruction node")
+ writer.write("%s%s %s?>%s" % (indent, target, data, newl))
class CharacterData(Childless, Node):
@@ -1174,7 +1413,7 @@ def replaceWholeText(self, content):
return None
def _get_isWhitespaceInElementContent(self):
- if self.data.strip():
+ if self.data.strip(_XML_WHITESPACE):
return False
elem = _get_containing_element(self)
if elem is None:
@@ -1218,9 +1457,14 @@ def __init__(self, data):
self._data = data
def writexml(self, writer, indent="", addindent="", newl=""):
- if "--" in self.data:
+ data = self.data
+ # The data cannot contain "--", and cannot end with "-", which
+ # would be fused with the closing "-->" (see XML 1.0, 2.5, [15]).
+ if "--" in data:
raise ValueError("'--' is not allowed in a comment node")
- writer.write("%s%s" % (indent, self.data, newl))
+ if data.endswith("-"):
+ raise ValueError("a comment node cannot end with '-'")
+ writer.write("%s%s" % (indent, data, newl))
class CDATASection(Text):
@@ -1366,10 +1610,20 @@ def writexml(self, writer, indent="", addindent="", newl=""):
writer.write("\n" % (
- declared_encoding,))
+ if standalone is None:
+ sddecl = ""
+ else:
+ sddecl = " standalone='%s'" % (
+ "yes" if standalone else "no",)
+ write("\n" % (
+ declared_encoding, sddecl))
if method == "text":
_serialize_text(write, self._root)
else:
- qnames, namespaces = _namespaces(self._root, default_namespace)
+ qnames, attr_qnames, namespaces = _namespaces(
+ self._root, default_namespace)
serialize = _serialize[method]
- serialize(write, self._root, qnames, namespaces,
+ serialize(write, self._root, qnames, attr_qnames, namespaces,
short_empty_elements=short_empty_elements)
- def write_c14n(self, file):
- # lxml.etree compatibility. use output method instead
- return self.write(file, method="c14n")
-
# --------------------------------------------------------------------
# serialization support
@@ -811,28 +821,59 @@ def _namespaces(elem, default_namespace=None):
# maps qnames to *encoded* prefix:local names
qnames = {None: None}
+ # The default namespace declaration does not apply to attribute names,
+ # so they are encoded separately: an unqualified name is left as is,
+ # and a qualified name always gets a prefix.
+ attr_qnames = {None: None} if default_namespace else qnames
- # maps uri:s to prefixes
+ # maps prefixes to uri:s
namespaces = {}
+ # maps uri:s to prefixes, "" is the prefix of the default namespace
+ prefixes = {}
+ # maps uri:s to prefixes usable in attribute names
+ attr_prefixes = {} if default_namespace else prefixes
if default_namespace:
- namespaces[default_namespace] = ""
-
- def add_qname(qname):
+ namespaces[""] = default_namespace
+ prefixes[default_namespace] = ""
+
+ def get_prefix(uri, isattr):
+ # find or create the prefix for the namespace uri
+ if isattr:
+ prefix = attr_prefixes.get(uri)
+ if prefix is None:
+ # the empty prefix is of no use for an attribute name
+ prefix = prefixes.get(uri) or None
+ else:
+ prefix = prefixes.get(uri)
+ if prefix is not None:
+ return prefix
+ prefix = _namespace_map.get(uri)
+ if prefix is None or not prefix and (isattr or default_namespace):
+ # the empty prefix is of no use for an attribute name,
+ # and the default namespace is used for other uri
+ prefix = "ns%d" % len(namespaces)
+ if prefix != "xml":
+ namespaces[prefix] = uri
+ if isattr:
+ attr_prefixes[uri] = prefix
+ prefixes.setdefault(uri, prefix)
+ return prefix
+
+ def add_qname(qname, isattr=False):
# calculate serialized qname representation
try:
if qname[:1] == "{":
uri, tag = qname[1:].rsplit("}", 1)
- prefix = namespaces.get(uri)
- if prefix is None:
- prefix = _namespace_map.get(uri)
- if prefix is None:
- prefix = "ns%d" % len(namespaces)
- if prefix != "xml":
- namespaces[uri] = prefix
+ prefix = get_prefix(uri, isattr)
if prefix:
- qnames[qname] = "%s:%s" % (prefix, tag)
+ if isattr:
+ attr_qnames[qname] = "%s:%s" % (prefix, tag)
+ else:
+ qnames[qname] = "%s:%s" % (prefix, tag)
else:
qnames[qname] = tag # default element
+ elif isattr:
+ attr_qnames[qname] = qname
else:
if default_namespace:
# FIXME: can this be handled in XML 1.0?
@@ -858,16 +899,16 @@ def add_qname(qname):
for key, value in elem.items():
if isinstance(key, QName):
key = key.text
- if key not in qnames:
- add_qname(key)
+ if key not in attr_qnames:
+ add_qname(key, isattr=True)
if isinstance(value, QName) and value.text not in qnames:
add_qname(value.text)
text = elem.text
if isinstance(text, QName) and text.text not in qnames:
add_qname(text.text)
- return qnames, namespaces
+ return qnames, attr_qnames, namespaces
-def _serialize_xml(write, elem, qnames, namespaces,
+def _serialize_xml(write, elem, qnames, attr_qnames, namespaces,
short_empty_elements, **kwargs):
tag = elem.tag
text = elem.text
@@ -881,15 +922,14 @@ def _serialize_xml(write, elem, qnames, namespaces,
if text:
write(_escape_cdata(text))
for e in elem:
- _serialize_xml(write, e, qnames, None,
+ _serialize_xml(write, e, qnames, attr_qnames, None,
short_empty_elements=short_empty_elements)
else:
write("<" + tag)
items = list(elem.items())
if items or namespaces:
if namespaces:
- for v, k in sorted(namespaces.items(),
- key=lambda x: x[1]): # sort on prefix
+ for k, v in sorted(namespaces.items()): # sort on prefix
if k:
k = ":" + k
write(" xmlns%s=\"%s\"" % (
@@ -903,13 +943,13 @@ def _serialize_xml(write, elem, qnames, namespaces,
v = qnames[v.text]
else:
v = _escape_attrib(v)
- write(" %s=\"%s\"" % (qnames[k], v))
+ write(" %s=\"%s\"" % (attr_qnames[k], v))
if text or len(elem) or not short_empty_elements:
write(">")
if text:
write(_escape_cdata(text))
for e in elem:
- _serialize_xml(write, e, qnames, None,
+ _serialize_xml(write, e, qnames, attr_qnames, None,
short_empty_elements=short_empty_elements)
write("" + tag + ">")
else:
@@ -924,7 +964,7 @@ def _serialize_xml(write, elem, qnames, namespaces,
"img", "input", "isindex", "link", "meta", "param", "source",
"track", "wbr", "plaintext"}
-def _serialize_html(write, elem, qnames, namespaces, **kwargs):
+def _serialize_html(write, elem, qnames, attr_qnames, namespaces, **kwargs):
tag = elem.tag
text = elem.text
if tag is Comment:
@@ -937,14 +977,13 @@ def _serialize_html(write, elem, qnames, namespaces, **kwargs):
if text:
write(_escape_cdata(text))
for e in elem:
- _serialize_html(write, e, qnames, None)
+ _serialize_html(write, e, qnames, attr_qnames, None)
else:
write("<" + tag)
items = list(elem.items())
if items or namespaces:
if namespaces:
- for v, k in sorted(namespaces.items(),
- key=lambda x: x[1]): # sort on prefix
+ for k, v in sorted(namespaces.items()): # sort on prefix
if k:
k = ":" + k
write(" xmlns%s=\"%s\"" % (
@@ -954,7 +993,7 @@ def _serialize_html(write, elem, qnames, namespaces, **kwargs):
for k, v in items:
if isinstance(k, QName):
k = k.text
- k = qnames[k]
+ k = attr_qnames[k]
if v is None:
write(" %s" % k) # empty attr
else:
@@ -971,7 +1010,7 @@ def _serialize_html(write, elem, qnames, namespaces, **kwargs):
else:
write(_escape_cdata(text))
for e in elem:
- _serialize_html(write, e, qnames, None)
+ _serialize_html(write, e, qnames, attr_qnames, None)
if ltag not in HTML_EMPTY:
write("" + tag + ">")
if elem.tail:
@@ -987,8 +1026,6 @@ def _serialize_text(write, elem):
"xml": _serialize_xml,
"html": _serialize_html,
"text": _serialize_text,
-# this optional method is imported at the end of the module
-# "c14n": _serialize_c14n,
}
@@ -1092,7 +1129,7 @@ def _escape_attrib_html(text):
def tostring(element, encoding=None, method=None, *,
xml_declaration=None, default_namespace=None,
- short_empty_elements=True):
+ short_empty_elements=True, standalone=None):
"""Generate string representation of XML element.
All subelements are included. If encoding is "unicode", a string
@@ -1100,8 +1137,10 @@ def tostring(element, encoding=None, method=None, *,
*element* is an Element instance, *encoding* is an optional output
encoding defaulting to US-ASCII, *method* is an optional output which
- can be one of "xml" (default), "html", "text" or "c14n",
- *default_namespace* sets the default XML namespace (for "xmlns").
+ can be one of "xml" (default), "html" or "text",
+ *default_namespace* sets the default XML namespace (for "xmlns"),
+ *standalone* is the value of the standalone document declaration
+ in the XML declaration (omitted if None).
Returns an (optionally) encoded string containing the XML data.
@@ -1111,7 +1150,8 @@ def tostring(element, encoding=None, method=None, *,
xml_declaration=xml_declaration,
default_namespace=default_namespace,
method=method,
- short_empty_elements=short_empty_elements)
+ short_empty_elements=short_empty_elements,
+ standalone=standalone)
return stream.getvalue()
class _ListDataStream(io.BufferedIOBase):
@@ -1133,14 +1173,15 @@ def tell(self):
def tostringlist(element, encoding=None, method=None, *,
xml_declaration=None, default_namespace=None,
- short_empty_elements=True):
+ short_empty_elements=True, standalone=None):
lst = []
stream = _ListDataStream(lst)
ElementTree(element).write(stream, encoding,
xml_declaration=xml_declaration,
default_namespace=default_namespace,
method=method,
- short_empty_elements=short_empty_elements)
+ short_empty_elements=short_empty_elements,
+ standalone=standalone)
return lst
@@ -1188,7 +1229,20 @@ def indent(tree, space=" ", level=0):
# Reduce the memory consumption by reusing indentation strings.
indentations = ["\n" + level * space]
+ def _preserves_whitespace(elem):
+ # True iff whitespace in the content of the element is significant.
+ if elem.get(_XML_SPACE) == "preserve":
+ return True
+ if elem.text and elem.text.strip(_XML_WHITESPACE):
+ return True
+ return any(child.tail and child.tail.strip(_XML_WHITESPACE)
+ for child in elem)
+
def _indent_children(elem, level):
+ if _preserves_whitespace(elem):
+ # Adding whitespace here would change the content.
+ return
+
# Start a new indentation level for the first child.
child_level = level + 1
try:
@@ -1197,18 +1251,15 @@ def _indent_children(elem, level):
child_indentation = indentations[level] + space
indentations.append(child_indentation)
- if not elem.text or not elem.text.strip():
- elem.text = child_indentation
+ elem.text = child_indentation
for child in elem:
if len(child):
_indent_children(child, child_level)
- if not child.tail or not child.tail.strip():
- child.tail = child_indentation
+ child.tail = child_indentation
# Dedent after the last child by overwriting the previous indentation.
- if not child.tail.strip():
- child.tail = indentations[level]
+ child.tail = indentations[level]
_indent_children(tree, 0)
@@ -1231,7 +1282,7 @@ def parse(source, parser=None):
return tree
-def iterparse(source, events=None, parser=None):
+def iterparse(source, events=None, parser=None, *, target=None):
"""Incrementally parse XML document into ElementTree.
This class also reports what's going on to the user based on the
@@ -1242,14 +1293,14 @@ def iterparse(source, events=None, parser=None):
*source* is a filename or file object containing XML data, *events* is
a list of events to report back, *parser* is an optional parser
- instance.
+ instance, *target* is an optional target of the standard parser.
Returns an iterator providing (event, elem) pairs.
"""
# Use the internal, undocumented _parser argument for now; When the
# parser argument of iterparse is removed, this can be killed.
- pullparser = XMLPullParser(events=events, _parser=parser)
+ pullparser = XMLPullParser(events=events, target=target, _parser=parser)
if not hasattr(source, "read"):
source = open(source, "rb")
@@ -1301,13 +1352,19 @@ def __del__(self, _warn=warnings.warn):
class XMLPullParser:
- def __init__(self, events=None, *, _parser=None):
+ def __init__(self, events=None, *, target=None, _parser=None):
# The _parser argument is for internal use only and must not be relied
# upon in user code. It will be removed in a future release.
# See https://bugs.python.org/issue17741 for more details.
self._events_queue = collections.deque()
- self._parser = _parser or XMLParser(target=TreeBuilder())
+ if _parser is None:
+ if target is None:
+ target = TreeBuilder()
+ _parser = XMLParser(target=target)
+ elif target is not None:
+ raise ValueError("can't specify both parser and target")
+ self._parser = _parser
# wire up the parser for event reporting
if events is None:
events = ("end",)
@@ -1583,10 +1640,10 @@ def __init__(self, *, target=None, encoding=None):
parser.CommentHandler = target.comment
if hasattr(target, 'pi'):
parser.ProcessingInstructionHandler = target.pi
+ parser.StartDoctypeDeclHandler = self._start_doctype
# Configure pyexpat: buffering, new-style attribute handling.
parser.buffer_text = 1
parser.ordered_attributes = 1
- self._doctype = None
self.entity = {}
try:
self.version = "Expat %d.%d.%d" % expat.version_info
@@ -1603,6 +1660,10 @@ def _setevents(self, events_queue, events_to_report):
parser = self._parser
append = events_queue.append
for event_name in events_to_report:
+ if (event_name in ("start", "end", "comment", "pi")
+ and not hasattr(self.target, event_name)):
+ raise TypeError("the target does not support %r events"
+ % event_name)
if event_name == "start":
parser.ordered_attributes = 1
def handler(tag, attrib_in, event=event_name, append=append,
@@ -1635,19 +1696,20 @@ def handler(prefix, event=event_name, append=append):
append((event, None))
parser.EndNamespaceDeclHandler = handler
elif event_name == 'comment':
- def handler(text, event=event_name, append=append, self=self):
- append((event, self.target.comment(text)))
+ def handler(text, event=event_name, append=append,
+ comment=self.target.comment):
+ append((event, comment(text)))
parser.CommentHandler = handler
elif event_name == 'pi':
def handler(pi_target, data, event=event_name, append=append,
- self=self):
- append((event, self.target.pi(pi_target, data)))
+ pi=self.target.pi):
+ append((event, pi(pi_target, data)))
parser.ProcessingInstructionHandler = handler
else:
raise ValueError("unknown event %r" % event_name)
def _raiseerror(self, value):
- err = ParseError(value)
+ err = ParseError(str(value))
err.code = value.code
err.position = value.lineno, value.offset
raise err
@@ -1705,38 +1767,15 @@ def _default(self, text):
err.lineno = self.parser.ErrorLineNumber
err.offset = self.parser.ErrorColumnNumber
raise err
- elif prefix == "<" and text[:9] == "":
- self._doctype = None
- return
- text = text.strip()
- if not text:
- return
- self._doctype.append(text)
- n = len(self._doctype)
- if n > 2:
- type = self._doctype[1]
- if type == "PUBLIC" and n == 4:
- name, type, pubid, system = self._doctype
- if pubid:
- pubid = pubid[1:-1]
- elif type == "SYSTEM" and n == 3:
- name, type, system = self._doctype
- pubid = None
- else:
- return
- if hasattr(self.target, "doctype"):
- self.target.doctype(name, pubid, system[1:-1])
- elif hasattr(self, "doctype"):
- warnings.warn(
- "The doctype() method of XMLParser is ignored. "
- "Define doctype() method on the TreeBuilder target.",
- RuntimeWarning)
- self._doctype = None
+ def _start_doctype(self, name, system, pubid, has_internal_subset):
+ if hasattr(self.target, "doctype"):
+ self.target.doctype(name, pubid, system)
+ elif hasattr(self, "doctype"):
+ warnings.warn(
+ "The doctype() method of XMLParser is ignored. "
+ "Define doctype() method on the TreeBuilder target.",
+ RuntimeWarning)
def feed(self, data):
"""Feed encoded data to parser."""
@@ -1928,7 +1967,7 @@ def _flush(self, _join_text=''.join):
data = _join_text(self._data)
del self._data[:]
if self._strip_text and not self._preserve_space[-1]:
- data = data.strip()
+ data = data.strip(_XML_WHITESPACE)
if self._pending_start is not None:
args, self._pending_start = self._pending_start, None
qname_text = data if data and _looks_like_prefix_name(data) else None
diff --git a/Lib/xml/sax/__init__.py b/Lib/xml/sax/__init__.py
index fe4582c6f8b758c..45f69c6bc223c5f 100644
--- a/Lib/xml/sax/__init__.py
+++ b/Lib/xml/sax/__init__.py
@@ -27,12 +27,21 @@
def parse(source, handler, errorHandler=ErrorHandler()):
+ """Parse an XML document with the default parser.
+
+ source is a system identifier, a path-like object or a file object,
+ handler is a ContentHandler instance, and errorHandler is an
+ ErrorHandler instance. All work is done by the handler."""
parser = make_parser()
parser.setContentHandler(handler)
parser.setErrorHandler(errorHandler)
parser.parse(source)
def parseString(string, handler, errorHandler=ErrorHandler()):
+ """Parse an XML document from a string with the default parser.
+
+ string is a str or a bytes-like object, the other arguments are the
+ same as for parse()."""
import io
if errorHandler is None:
errorHandler = ErrorHandler()
diff --git a/Lib/xml/sax/saxutils.py b/Lib/xml/sax/saxutils.py
index c1612ea1cebc5d0..8225989d60ecec8 100644
--- a/Lib/xml/sax/saxutils.py
+++ b/Lib/xml/sax/saxutils.py
@@ -3,9 +3,12 @@
convenience of application and driver writers.
"""
-import os, urllib.parse, urllib.request
-import io
import codecs
+import io
+import os
+import sys
+lazy import urllib.parse
+lazy import urllib.request
from . import handler
from . import xmlreader
@@ -70,7 +73,6 @@ def quoteattr(data, entities={}):
def _gettextwriter(out, encoding):
if out is None:
- import sys
return sys.stdout
if isinstance(out, io.TextIOBase):
@@ -110,6 +112,7 @@ def __getattr__(self, name):
write_through=True)
class XMLGenerator(handler.ContentHandler):
+ """Content handler which writes the events back as an XML document."""
def __init__(self, out=None, encoding="iso-8859-1", short_empty_elements=False):
handler.ContentHandler.__init__(self)
@@ -186,9 +189,9 @@ def startElementNS(self, name, qname, attrs):
for prefix, uri in self._undeclared_ns_maps:
if prefix:
- self._write(' xmlns:%s="%s"' % (prefix, uri))
+ self._write(' xmlns:%s=%s' % (prefix, quoteattr(uri)))
else:
- self._write(' xmlns="%s"' % uri)
+ self._write(' xmlns=%s' % quoteattr(uri))
self._undeclared_ns_maps = []
for (name, value) in attrs.items():
diff --git a/Lib/xml/sax/xmlreader.py b/Lib/xml/sax/xmlreader.py
index e906121d23b9ef3..98e93113fbb5ab9 100644
--- a/Lib/xml/sax/xmlreader.py
+++ b/Lib/xml/sax/xmlreader.py
@@ -89,7 +89,7 @@ def setProperty(self, name, value):
raise SAXNotRecognizedException("Property '%s' not recognized" % name)
class IncrementalParser(XMLReader):
- """This interface adds three extra methods to the XMLReader
+ """This interface adds four extra methods to the XMLReader
interface that allow XML parsers to support incremental
parsing. Support for this interface is optional, since not all
underlying XML parsers support this functionality.
@@ -104,7 +104,7 @@ class IncrementalParser(XMLReader):
is, after parse has been called and before it returns.
By default, the class also implements the parse method of the XMLReader
- interface using the feed, close and reset methods of the
+ interface using the prepareParser, feed and close methods of the
IncrementalParser interface as a convenience to SAX 2.0 driver
writers."""
@@ -274,6 +274,7 @@ def getCharacterStream(self):
# ===== ATTRIBUTESIMPL =====
class AttributesImpl:
+ """Implementation of the Attributes interface."""
def __init__(self, attrs):
"""Non-NS-aware implementation.
diff --git a/Lib/xmlrpc/client.py b/Lib/xmlrpc/client.py
index 84e4e4d11a7319e..0d26ad03c51e735 100644
--- a/Lib/xmlrpc/client.py
+++ b/Lib/xmlrpc/client.py
@@ -677,7 +677,9 @@ def end(self, tag):
f = self.dispatch[tag.split(':')[-1]]
except KeyError:
return # unknown tag ?
- return f(self, "".join(self._data))
+ data = "".join(self._data)
+ self._data.clear()
+ return f(self, data)
#
# accelerator support
diff --git a/Lib/xmlrpc/server.py b/Lib/xmlrpc/server.py
index 3e6871157d09299..5ef68640a09ba4b 100644
--- a/Lib/xmlrpc/server.py
+++ b/Lib/xmlrpc/server.py
@@ -752,7 +752,7 @@ def docroutine(self, object, name, mod=None,
anchor = (cl and cl.__name__ or '') + '-' + name
note = ''
- title = '%s' % (
+ title = '%s' % (
self.escape(anchor), self.escape(name))
if callable(object):
@@ -766,13 +766,13 @@ def docroutine(self, object, name, mod=None,
else:
docstring = pydoc.getdoc(object)
- decl = title + argspec + (note and self.grey(
- '%s' % note))
+ decl = title + argspec + (note and
+ '%s' % note)
doc = self.markup(
docstring, self.preformat, funcs, classes, methods)
- doc = doc and '
%s
' % doc
- return '
%s
%s
\n' % (decl, doc)
+ doc = doc and '
%s
' % doc
+ return '
%s
%s
\n' % (decl, doc)
def docserver(self, server_name, package_documentation, methods):
"""Produce HTML documentation for an XML-RPC server."""
@@ -783,12 +783,11 @@ def docserver(self, server_name, package_documentation, methods):
fdict[value] = fdict[key]
server_name = self.escape(server_name)
- head = '%s' % server_name
- result = self.heading(head)
+ result = self.heading(server_name)
doc = self.markup(package_documentation, self.preformat, fdict)
- doc = doc and '%s' % doc
- result = result + '
%s
\n' % doc
+ doc = doc and '
%s
\n' % doc
+ result = result + doc
contents = []
method_items = sorted(methods.items())
@@ -807,12 +806,15 @@ def page(self, title, contents):
'' %
css_path)
return '''\
-
+
+
Python: %s
-%s%s''' % (title, css_link, contents)
+%s
+%s
+''' % (title, css_link, contents)
class XMLRPCDocGenerator:
"""Generates documentation for an XML-RPC server.
diff --git a/Lib/zipapp.py b/Lib/zipapp.py
index a1cef18ada9d05d..39e765d1ffdc6d4 100644
--- a/Lib/zipapp.py
+++ b/Lib/zipapp.py
@@ -69,7 +69,7 @@ def _copy_archive(archive, new_archive, interpreter=None):
dst.write(first_2)
shutil.copyfileobj(src, dst)
- if interpreter and isinstance(new_archive, str):
+ if interpreter and isinstance(new_archive, (str, os.PathLike)):
os.chmod(new_archive, os.stat(new_archive).st_mode | stat.S_IEXEC)
diff --git a/Lib/zipfile/__init__.py b/Lib/zipfile/__init__.py
index 418933a2e8d9e87..4909e680621ed71 100644
--- a/Lib/zipfile/__init__.py
+++ b/Lib/zipfile/__init__.py
@@ -12,6 +12,7 @@
import sys
import threading
import time
+import warnings # must stay eager to support finalization
try:
import zlib # We may need its compression method
@@ -239,8 +240,9 @@ def _check_zipfile(fp):
return True # Empty zipfiles are still zipfiles
elif endrec[_ECD_DISK_NUMBER] == endrec[_ECD_DISK_START]:
# Central directory is on the same disk
- fp.seek(sum(_handle_prepended_data(endrec)))
- if endrec[_ECD_SIZE] >= sizeCentralDir:
+ start_dir = sum(_handle_prepended_data(endrec))
+ if start_dir >= 0 and endrec[_ECD_SIZE] >= sizeCentralDir:
+ fp.seek(start_dir)
data = fp.read(sizeCentralDir) # CD is where we expect it to be
if len(data) == sizeCentralDir:
centdir = struct.unpack(structCentralDir, data) # CD is the right size
@@ -575,11 +577,11 @@ def FileHeader(self, zip64=None):
def _encodeFilenameFlags(self):
if self.flag_bits & _MASK_UTF_FILENAME:
- encoding = 'ascii'
+ encoding = 'utf-8'
else:
encoding = 'cp437'
try:
- return self.filename.encode(encoding), self.flag_bits & ~_MASK_UTF_FILENAME
+ return self.filename.encode(encoding), self.flag_bits
except UnicodeEncodeError:
return self.filename.encode('utf-8'), self.flag_bits | _MASK_UTF_FILENAME
@@ -619,7 +621,6 @@ def _decodeExtra(self, filename_crc):
if up_unicode_name:
self.filename = _sanitize_filename(up_unicode_name)
else:
- import warnings
warnings.warn("Empty unicode path extra field (0x7075)", stacklevel=2)
except struct.error as e:
raise BadZipFile("Corrupt unicode path extra field (0x7075)") from e
@@ -689,7 +690,7 @@ def _for_archive(self, archive):
self.external_attr = 0o40775 << 16 # drwxrwxr-x
self.external_attr |= 0x10 # MS-DOS directory flag
else:
- self.external_attr = 0o600 << 16 # ?rw-------
+ self.external_attr = 0o100600 << 16 # -rw-------
return self
def is_dir(self):
@@ -801,7 +802,16 @@ def unused_data(self):
except AttributeError:
return b''
- def decompress(self, data):
+ @property
+ def needs_input(self):
+ # While the LZMA properties header is still being buffered, more input
+ # is required; afterwards defer to the wrapped decompressor so a bounded
+ # decompress() call can be drained across reads.
+ if self._decomp is None:
+ return True
+ return self._decomp.needs_input
+
+ def decompress(self, data, max_length=-1):
if self._decomp is None:
self._unconsumed += data
if len(self._unconsumed) <= 4:
@@ -817,7 +827,7 @@ def decompress(self, data):
data = self._unconsumed[4 + psize:]
del self._unconsumed
- result = self._decomp.decompress(data)
+ result = self._decomp.decompress(data, max_length)
self.eof = self._decomp.eof
return result
@@ -1186,8 +1196,15 @@ def _read1(self, n):
data = self._decompressor.unconsumed_tail
if n > len(data):
data += self._read2(n - len(data))
- else:
+ elif self._compress_type == ZIP_STORED:
data = self._read2(n)
+ else:
+ # bzip2/lzma/zstd: a bounded decompress() call may leave input
+ # buffered inside the decompressor; drain that before reading more.
+ if getattr(self._decompressor, "needs_input", True):
+ data = self._read2(n)
+ else:
+ data = b''
if self._compress_type == ZIP_STORED:
self._eof = self._compress_left <= 0
@@ -1200,8 +1217,26 @@ def _read1(self, n):
if self._eof:
data += self._decompressor.flush()
else:
- data = self._decompressor.decompress(data)
- self._eof = self._decompressor.eof or self._compress_left <= 0
+ # Bound the output of a single decompress() call (mirroring the
+ # DEFLATE path above) so that a small compressed member cannot
+ # expand into one unbounded read.
+ try:
+ data = self._decompressor.decompress(data, max(n, self.MIN_READ_SIZE))
+ except TypeError:
+ # See MonkeypatchedDecompressorTests in test_core.py
+ warnings._deprecated(
+ 'one-argument decompress()',
+ 'The decompress() method of '
+ + type(self._decompressor).__name__
+ + ' should take two arguments, data and max_length.'
+ + ' One-argument calls will stop working before'
+ + ' Python 3.21.',
+ remove=(3, 21),
+ stacklevel=4)
+ data = self._decompressor.decompress(data)
+ self._eof = (self._decompressor.eof or
+ self._compress_left <= 0 and
+ getattr(self._decompressor, "needs_input", True))
data = data[:self._left]
self._left -= len(data)
@@ -1523,7 +1558,7 @@ def repack(self, zfile, removed=None):
zinfo.header_offset, entry_size, used_entry_size)
if used_entry_size > entry_size:
raise BadZipFile(
- f"Overlapped entries: {zinfo.orig_filename!r} ")
+ f"Overlapped entries: {zinfo.orig_filename!r}")
if removed is not None and zinfo not in removed_zinfos:
used_entry_size = entry_size
@@ -2152,7 +2187,6 @@ def comment(self, comment):
raise TypeError("comment: expected bytes, got %s" % type(comment).__name__)
# check for valid comment length
if len(comment) > ZIP_MAX_COMMENT:
- import warnings
warnings.warn('Archive comment is too long; truncating to %d bytes'
% ZIP_MAX_COMMENT, stacklevel=2)
comment = comment[:ZIP_MAX_COMMENT]
@@ -2240,10 +2274,16 @@ def open(self, name, mode="r", pwd=None, *, force_zip64=False):
'File name in directory %r and header %r differ.'
% (zinfo.orig_filename, fname))
+ local_method = fheader[_FH_COMPRESSION_METHOD]
+ if local_method != zinfo.compress_type:
+ raise BadZipFile(
+ f"Compression method for {zinfo.orig_filename!r} differs "
+ f"between the central directory ({zinfo.compress_type}) "
+ f"and the local file header ({local_method}).")
+
if (zinfo._end_offset is not None and
zef_file.tell() + zinfo.compress_size > zinfo._end_offset):
if zinfo._end_offset == zinfo.header_offset:
- import warnings
warnings.warn(
f"Overlapped entries: {zinfo.orig_filename!r} "
f"(possible zip bomb)",
@@ -2286,7 +2326,9 @@ def _open_to_write(self, zinfo, force_zip64=False):
zinfo.compress_size = 0
zinfo.CRC = 0
- zinfo.flag_bits = _MASK_UTF_FILENAME
+ zinfo.flag_bits &= _MASK_UTF_FILENAME
+ if not zinfo.filename.isascii():
+ zinfo.flag_bits |= _MASK_UTF_FILENAME
if zinfo.compress_type == ZIP_LZMA:
# Compressed data includes an end-of-stream (EOS) marker
zinfo.flag_bits |= _MASK_COMPRESS_OPTION_1
@@ -2397,15 +2439,16 @@ def repack(self, removed=None, *, strict_descriptor=True,
truncation."""
if self.mode != 'a':
raise ValueError("repack() requires mode 'a'")
- if not self.fp:
- raise ValueError(
- "Attempt to write to ZIP archive that was already closed")
- if self._writing:
- raise ValueError(
- "Can't write to ZIP archive while an open writing handle exists"
- )
with self._lock:
+ if not self.fp:
+ raise ValueError(
+ "Attempt to write to ZIP archive that was already closed")
+ if self._writing or self._fileRefCnt > 1:
+ raise ValueError(
+ "Can't repack ZIP archive while an open handle exists"
+ )
+
self._writing = True
try:
repacker = _ZipRepacker(
@@ -2493,7 +2536,6 @@ def _extract_member(self, member, targetpath, pwd):
def _writecheck(self, zinfo):
"""Check for errors before writing a file to the archive."""
if zinfo.filename in self.NameToInfo:
- import warnings
warnings.warn('Duplicate name: %r' % zinfo.filename, stacklevel=3)
if self.mode not in ('w', 'x', 'a'):
raise ValueError("write() requires mode 'w', 'x', or 'a'")
@@ -2598,6 +2640,15 @@ def mkdir(self, zinfo_or_directory_name, mode=511):
else:
raise TypeError("Expected type str or ZipInfo")
+ if not self.fp:
+ raise ValueError(
+ "Attempt to write to ZIP archive that was already closed"
+ )
+ if self._writing:
+ raise ValueError(
+ "Can't write to ZIP archive while an open writing handle exists."
+ )
+
with self._lock:
if self._seekable:
self.fp.seek(self.start_dir)
@@ -2614,9 +2665,18 @@ def mkdir(self, zinfo_or_directory_name, mode=511):
self.fp.write(zinfo.FileHeader(False))
self.start_dir = self.fp.tell()
- def __del__(self):
+ def __del__(self, _warn=warnings.warn):
"""Call the "close()" method in case the user forgot."""
- self.close()
+ # gh-81954: Warn if writable ZipFile is implicitly closed.
+ # GC cleanup order is non-deterministic and can result in data loss.
+ try:
+ # Wrap within a try to ensure the file is closed even if
+ # warnings raises.
+ if self.fp is not None and self.mode in ('w', 'x', 'a'):
+ _warn(f"unclosed ZipFile {self!r}",
+ ResourceWarning, source=self, stacklevel=2)
+ finally:
+ self.close()
def close(self):
"""Close the file, and for mode 'w', 'x' and 'a' write the ending
@@ -2875,6 +2935,10 @@ def _get_code(self, pathname, basename):
def main(args=None):
import argparse
+ import runpy
+
+ # Prevent shadowing stdlib modules from extracted files
+ runpy._remove_sys_path0()
description = 'A simple command-line interface for zipfile module.'
parser = argparse.ArgumentParser(description=description)
diff --git a/Lib/zipfile/_path/__init__.py b/Lib/zipfile/_path/__init__.py
index faae4c84cae5ed2..aba7bf91ccf47f8 100644
--- a/Lib/zipfile/_path/__init__.py
+++ b/Lib/zipfile/_path/__init__.py
@@ -14,10 +14,9 @@
import posixpath
import re
import stat
-import sys
import zipfile
-from ._functools import save_method_args
+from ._functools import none_as, save_method_args
from .glob import Translator
__all__ = ['Path']
@@ -66,7 +65,7 @@ def _ancestry(path):
path = path.rstrip(posixpath.sep)
while path.rstrip(posixpath.sep):
yield path
- path, tail = posixpath.split(path)
+ path, _tail = posixpath.split(path)
_dedupe = dict.fromkeys
@@ -156,10 +155,7 @@ def make(cls, source):
return cls(source)
# Only allow for FastLookup when supplied zipfile is read-only
- if 'r' not in source.mode:
- cls = CompleteDirs
-
- source.__class__ = cls
+ source.__class__ = cls if 'r' in source.mode else CompleteDirs
return source
@classmethod
@@ -195,12 +191,7 @@ def _name_set_prop(self):
def _extract_text_encoding(encoding=None, *args, **kwargs):
- # compute stack level so that the caller of the caller sees any warning.
- is_pypy = sys.implementation.name == 'pypy'
- # PyPy no longer special cased after 7.3.19 (or maybe 7.3.18)
- # See jaraco/zipp#143
- is_old_pypi = is_pypy and sys.pypy_version_info < (7, 3, 19)
- stack_level = 3 + is_old_pypi
+ stack_level = 3
return io.text_encoding(encoding, stack_level), args, kwargs
@@ -276,7 +267,7 @@ class Path:
resolve to the zipfile.
>>> str(path)
- 'mem/abcde.zip/'
+ 'mem/abcde.zip'
>>> path.name
'abcde.zip'
>>> path.filename == pathlib.Path('mem/abcde.zip')
@@ -403,7 +394,7 @@ def exists(self):
def iterdir(self):
if not self.is_dir():
- raise ValueError("Can't listdir a file")
+ raise NotADirectoryError("Can't listdir a file")
subs = map(self._next, self.root.namelist())
return filter(self._is_child, subs)
@@ -434,7 +425,8 @@ def relative_to(self, other, *extra):
return posixpath.relpath(str(self), str(other.joinpath(*extra)))
def __str__(self):
- return posixpath.join(self.root.filename, self.at)
+ root = none_as(self.root.filename, ':zipfile:')
+ return posixpath.join(root, self.at) if self.at else root
def __repr__(self):
return self.__repr.format(self=self)
diff --git a/Lib/zipfile/_path/_functools.py b/Lib/zipfile/_path/_functools.py
index 7390be21873e4ba..7d82636ac8d627a 100644
--- a/Lib/zipfile/_path/_functools.py
+++ b/Lib/zipfile/_path/_functools.py
@@ -18,3 +18,14 @@ def wrapper(self, /, *args, **kwargs):
return method(self, *args, **kwargs)
return wrapper
+
+
+# from jaraco.functools 4.3
+def none_as(value, replacement=None):
+ """
+ >>> none_as(None, 'foo')
+ 'foo'
+ >>> none_as('bar', 'foo')
+ 'bar'
+ """
+ return replacement if value is None else value
diff --git a/Lib/zipfile/_path/glob.py b/Lib/zipfile/_path/glob.py
index bd2839304b7db2a..5239772a600f8ba 100644
--- a/Lib/zipfile/_path/glob.py
+++ b/Lib/zipfile/_path/glob.py
@@ -1,3 +1,4 @@
+import fnmatch
import os
import re
@@ -67,8 +68,32 @@ def replace(self, match):
"""
Perform the replacements for a match from :func:`separate`.
"""
- return match.group('set') or (
- re.escape(match.group(0))
+ handler = self._replace_set if match.group('set') else self._replace_plain
+ return handler(match.group(0))
+
+ def _replace_set(self, character_set):
+ r"""
+ Translate a character set using shell-style semantics.
+
+ Glob character sets treat a leading ``!`` as negation and ``^``
+ as a literal (unlike regex), so defer to fnmatch, but guard
+ against matching a separator.
+
+ >>> Translator('/')._replace_set('[!a]')
+ '(?![/])[^a]'
+ >>> Translator('/')._replace_set('[^a]')
+ '(?![/])[\\^a]'
+ """
+ translated = _strip_fnmatch(fnmatch.translate(character_set))
+ return rf'(?![{re.escape(self.seps)}]){translated}'
+
+ def _replace_plain(self, text):
+ """
+ Escape the text, translating any wildcards.
+ """
+ return (
+ re
+ .escape(text)
.replace('\\*\\*', r'.*')
.replace('\\*', rf'[^{re.escape(self.seps)}]*')
.replace('\\?', r'[^/]')
@@ -111,3 +136,15 @@ def separate(pattern):
['a', '[?]', 'txt']
"""
return re.finditer(r'([^\[]+)|(?P[\[].*?[\]])|([\[][^\]]*$)', pattern)
+
+
+def _strip_fnmatch(translated):
+ r"""
+ Strip fnmatch's outer group and end marker.
+
+ >>> _strip_fnmatch(r'(?s:[^a])\z')
+ '[^a]'
+ >>> _strip_fnmatch(r'(?s:[^a])\Z')
+ '[^a]'
+ """
+ return re.fullmatch(r'\(\?s:(.*)\)\\[zZ]', translated, re.DOTALL).group(1)
diff --git a/Lib/zipimport.py b/Lib/zipimport.py
index 19279d1c2bea368..09a85f6d7f58e86 100644
--- a/Lib/zipimport.py
+++ b/Lib/zipimport.py
@@ -159,11 +159,12 @@ def get_filename(self, fullname):
"""get_filename(fullname) -> filename string.
Return the filename for the specified module or raise ZipImportError
- if it couldn't be imported.
+ if it couldn't be found.
"""
# Deciding the filename requires working out where the code
# would come from if the module was actually loaded
- code, ispackage, modpath = _get_module_code(self, fullname)
+ _, _, modpath = _get_module_code(
+ self, fullname, compile_source=False)
return modpath
@@ -427,7 +428,12 @@ def _read_directory(archive):
if flags & 0x800:
# UTF-8 file names extension
- name = name.decode()
+ try:
+ name = name.decode()
+ except UnicodeDecodeError as exc:
+ raise ZipImportError(
+ f"can't decode file name in Zip file: {archive!r}",
+ path=archive) from exc
else:
# Historical ZIP filename encoding
try:
@@ -584,12 +590,13 @@ def _get_zlib_decompress_func():
_importing_zstd = False
_zstd_decompressor_class = None
+_zstd_get_frame_size = None
# Return the _zstd.ZstdDecompressor function object, or NULL if _zstd couldn't
# be imported. The result is cached when found.
def _get_zstd_decompressor_class():
- global _zstd_decompressor_class
- if _zstd_decompressor_class:
+ global _zstd_decompressor_class, _zstd_get_frame_size
+ if _zstd_decompressor_class and _zstd_get_frame_size:
return _zstd_decompressor_class
global _importing_zstd
@@ -601,7 +608,10 @@ def _get_zstd_decompressor_class():
_importing_zstd = True
try:
- from _zstd import ZstdDecompressor as _zstd_decompressor_class
+ from _zstd import (
+ ZstdDecompressor as _zstd_decompressor_class,
+ get_frame_size as _zstd_get_frame_size,
+ )
except Exception:
_bootstrap._verbose_message("zipimport: zstd UNAVAILABLE")
raise ZipImportError("can't decompress data; zstd not available")
@@ -615,16 +625,24 @@ def _get_zstd_decompressor_class():
def _zstd_decompress(data):
# A simple version of compression.zstd.decompress() as we cannot import
# that here as the stdlib itself could be being zipimported.
+ decomp_class = _get_zstd_decompressor_class()
+ data = memoryview(data)
+ if not data:
+ raise ZipImportError("zipimport: zstd compressed data ended before "
+ "the end-of-stream marker")
results = []
- while True:
- decomp = _get_zstd_decompressor_class()()
- results.append(decomp.decompress(data))
+ while data:
+ try:
+ frame_size = _zstd_get_frame_size(data)
+ except Exception:
+ raise ZipImportError("zipimport: zstd compressed data ended before "
+ "the end-of-stream marker") from None
+ decomp = decomp_class()
+ results.append(decomp.decompress(data[:frame_size]))
if not decomp.eof:
raise ZipImportError("zipimport: zstd compressed data ended before "
"the end-of-stream marker")
- data = decomp.unused_data
- if not data:
- break
+ data = data[frame_size:]
return b"".join(results)
@@ -793,9 +811,9 @@ def _get_pyc_source(self, path):
return _get_data(self.archive, toc_entry)
-# Get the code object associated with the module specified by
-# 'fullname'.
-def _get_module_code(self, fullname):
+# Get the code object associated with the module specified by 'fullname'.
+# If compile_source is false, return None for source code without reading or compiling it.
+def _get_module_code(self, fullname, *, compile_source=True):
path = _get_module_path(self, fullname)
import_error = None
for suffix, isbytecode, ispackage in _zip_searchorder:
@@ -807,6 +825,8 @@ def _get_module_code(self, fullname):
pass
else:
modpath = toc_entry[0]
+ if not isbytecode and not compile_source:
+ return None, ispackage, modpath
data = _get_data(self.archive, toc_entry)
code = None
if isbytecode:
@@ -820,7 +840,6 @@ def _get_module_code(self, fullname):
# bad magic number or non-matching mtime
# in byte code, try next
continue
- modpath = toc_entry[0]
return code, ispackage, modpath
else:
if import_error:
diff --git a/Lib/zoneinfo/_common.py b/Lib/zoneinfo/_common.py
index caa3a5b583bab32..071ca714be30ab4 100644
--- a/Lib/zoneinfo/_common.py
+++ b/Lib/zoneinfo/_common.py
@@ -78,7 +78,7 @@ def load_data(fobj):
# Read the ttinfo struct, (utoff, isdst, abbrind)
if typecnt:
utcoff, isdst, abbrind = zip(
- *(struct.unpack(">lbb", fobj.read(6)) for i in range(typecnt))
+ *(struct.unpack(">lbB", fobj.read(6)) for i in range(typecnt))
)
else:
utcoff = ()
@@ -89,6 +89,14 @@ def load_data(fobj):
# not by position in the array but by position in the unsplit
# abbreviation string. I suppose this makes more sense in C, which uses
# null to terminate the strings, but it's inconvenient here...
+ #
+ # Each abbreviation index is a single unsigned byte, so only about the
+ # first 256 characters of the block can be referenced. A much longer
+ # block holds nothing usable, and reading it would copy most of the
+ # block for every local time type.
+ if not 0 <= charcnt <= 512:
+ raise ValueError(f"Invalid TZif file: invalid charcnt: {charcnt}")
+
abbr_vals = {}
abbr_chars = fobj.read(charcnt)
diff --git a/Lib/zoneinfo/_tzpath.py b/Lib/zoneinfo/_tzpath.py
index 3661c837daa0a41..7b6396444fd9110 100644
--- a/Lib/zoneinfo/_tzpath.py
+++ b/Lib/zoneinfo/_tzpath.py
@@ -111,6 +111,17 @@ def _validate_tzfile_path(path, _base=_TEST_PATH):
f"ZoneInfo keys must refer to subdirectories of TZPATH, got: {path}"
)
+ # load_tzdata() joins the last "/"-separated component of the key to the
+ # tzdata package directory on its own. On Windows a component with a
+ # drive or root, such as "C:\\file" in "America/C:\\file", would replace
+ # that directory instead of being looked up inside it.
+ for component in path.split("/"):
+ drive, root, _ = os.path.splitroot(component)
+ if drive or root:
+ raise ValueError(
+ f"ZoneInfo keys must not contain drives or roots, got: {path}"
+ )
+
del _TEST_PATH
diff --git a/Lib/zoneinfo/_zoneinfo.py b/Lib/zoneinfo/_zoneinfo.py
index 48154775568b6dc..7cdb4c22fa8932a 100644
--- a/Lib/zoneinfo/_zoneinfo.py
+++ b/Lib/zoneinfo/_zoneinfo.py
@@ -144,7 +144,7 @@ def fromutc(self, dt):
if num_trans > 1 and timestamp >= self._trans_utc[1]:
tti_prev, tti = self._ttinfos[idx - 2 : idx]
elif timestamp > self._trans_utc[-1]:
- tti_prev = self._ttinfos[-1]
+ tti_prev = self._tti_before
tti = self._tz_after
else:
tti_prev = self._tti_before
@@ -535,7 +535,7 @@ def year_to_epoch(self, year):
days_before_year = _post_epoch_days_before_year(year)
d = self.d
- if self.julian and d >= 59 and calendar.isleap(year):
+ if self.julian and d >= 60 and calendar.isleap(year):
d += 1
epoch = (days_before_year + d) * 86400
diff --git a/Mac/BuildScript/README.rst b/Mac/BuildScript/README.rst
index 54341a81c26743f..1d4fab4ef97fa28 100644
--- a/Mac/BuildScript/README.rst
+++ b/Mac/BuildScript/README.rst
@@ -1,7 +1,7 @@
Building a Python Mac OS X distribution
=======================================
-The ``build-install.py`` script creates Python distributions, including
+The ``build-installer.py`` script creates Python distributions, including
certain third-party libraries as necessary. It builds a complete
framework-based Python out-of-tree, installs it in a funny place with
$DESTROOT, massages that installation to remove .pyc files and such, creates
@@ -12,7 +12,7 @@ package. This format is deprecated and is no longer supported by modern
macOS systems; it is usable on macOS 10.6 and earlier systems.
To be usable on newer versions of macOS, the bits in the bundle package
must be assembled in a macOS flat installer package, using current
-versions of the pkgbuild and productbuild utilities. To pass macoS
+versions of the pkgbuild and productbuild utilities. To pass macOS
Gatekeeper download quarantine, the final package must be signed
with a valid Apple Developer ID certificate using productsign.
Starting with macOS 10.15 Catalina, Gatekeeper now also requires
@@ -28,7 +28,7 @@ A goal of PSF-provided (python.org) Python binaries for macOS is to
support a wide-range of operating system releases with one set of
binaries. Currently, the oldest release supported by python.org
binaries is macOS 10.9; it should still be possible to build Python and
-Python installers on older versions of macOS but we not regularly
+Python installers on older versions of macOS but we do not regularly
test on those systems nor provide binaries for them.
Prior to Python 3.9.1, no Python releases supported building on a
@@ -74,7 +74,7 @@ download them.
- builds the following third-party libraries
* OpenSSL 3.5.x
- * Tcl/Tk 8.6.x
+ * Tcl/Tk 9.0.x
* NCurses
* SQLite
* XZ
diff --git a/Mac/BuildScript/build-installer.py b/Mac/BuildScript/build-installer.py
index 16ad3fd111f65d6..c45430243343cc7 100755
--- a/Mac/BuildScript/build-installer.py
+++ b/Mac/BuildScript/build-installer.py
@@ -246,9 +246,9 @@ def library_recipes():
result.extend([
dict(
- name="OpenSSL 3.5.7",
- url="https://github.com/openssl/openssl/releases/download/openssl-3.5.7/openssl-3.5.7.tar.gz",
- checksum="a8c0d28a529ca480f9f36cf5792e2cd21984552a3c8e4aa11a24aa31aeac98e8",
+ name="OpenSSL 3.5.9",
+ url="https://github.com/openssl/openssl/releases/download/openssl-3.5.9/openssl-3.5.9.tar.gz",
+ checksum="603f5602e2eef00d77fbd429d34dcd5822bb301757a1bc9cdb24c670f1eb859a",
buildrecipe=build_universal_openssl,
configure=None,
install=None,
@@ -359,9 +359,9 @@ def library_recipes():
),
),
dict(
- name="SQLite 3.53.3",
- url="https://www.sqlite.org/2026/sqlite-autoconf-3530300.tar.gz",
- checksum="c917d7db16648ec95f714974ace5e5dcf46b7dc70e26600a0a102a3141125db0",
+ name="SQLite 3.53.4",
+ url="https://www.sqlite.org/2026/sqlite-autoconf-3530400.tar.gz",
+ checksum="0e9483900e92cd5de8fd48d16bf9200145a61f7fd5be542a5ac81d8a9516eb9c",
extra_cflags=('-Os '
'-DSQLITE_ENABLE_FTS5 '
'-DSQLITE_ENABLE_FTS4 '
@@ -1402,7 +1402,10 @@ def patchFile(inPath, outPath):
data = data.replace('$FULL_VERSION', getFullVersion())
data = data.replace('$VERSION', getVersion())
data = data.replace('$MACOSX_DEPLOYMENT_TARGET', ''.join((DEPTARGET, ' or later')))
- data = data.replace('$ARCHITECTURES', ", ".join(universal_opts_map[UNIVERSALARCHS]))
+ archs = universal_opts_map[UNIVERSALARCHS]
+ data = data.replace('$ARCHITECTURES', ", ".join(archs))
+ data = data.replace('$ARCHITECTURE_NOUN',
+ "architecture" if len(archs) == 1 else "architectures")
data = data.replace('$INSTALL_SIZE', installSize())
data = data.replace('$THIRD_PARTY_LIBS', "\\\n".join(THIRD_PARTY_LIBS))
diff --git a/Mac/BuildScript/resources/ReadMe.rtf b/Mac/BuildScript/resources/ReadMe.rtf
index d19b542b7e6c5a8..47f607d2f3c6ea5 100644
--- a/Mac/BuildScript/resources/ReadMe.rtf
+++ b/Mac/BuildScript/resources/ReadMe.rtf
@@ -6,7 +6,7 @@
\margl1440\margr1440\vieww15140\viewh15740\viewkind0
\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural\partightenfactor0
-\f0\fs24 \cf0 This package will install Python $FULL_VERSION for macOS $MACOSX_DEPLOYMENT_TARGET for the following architecture(s): $ARCHITECTURES.\
+\f0\fs24 \cf0 This package will install Python $FULL_VERSION for macOS $MACOSX_DEPLOYMENT_TARGET for the following $ARCHITECTURE_NOUN: $ARCHITECTURES.\
\
\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural\partightenfactor0
diff --git a/Mac/BuildScript/resources/install_certificates.command b/Mac/BuildScript/resources/install_certificates.command
index 700eb462b68c187..aa44961da7f4680 100755
--- a/Mac/BuildScript/resources/install_certificates.command
+++ b/Mac/BuildScript/resources/install_certificates.command
@@ -1,4 +1,8 @@
#!/bin/sh
+# Installing into the global environment is the point; ensure that the user
+# hasn't configured pip to always require a virtual environment.
+unset PIP_REQUIRE_VENV
+unset PIP_REQUIRE_VIRTUALENV
/Library/Frameworks/Python.framework/Versions/@PYVER@/bin/python@PYVER@ << "EOF"
diff --git a/Mac/README.rst b/Mac/README.rst
index 8a6e52725615aae..487f1a9c78065af 100644
--- a/Mac/README.rst
+++ b/Mac/README.rst
@@ -97,8 +97,8 @@ machines. In macOS 10.5 support was extended to 64-bit Intel and 64-bit PPC
architectures. It is possible to build Python with various combinations
of architectures depending on the build tools and macOS version in use.
Note that PPC support was removed in macOS 10.7 and 32-bit Intel support
-was removed in macOS 10.15. So currently as of macOS 10.15, macOS only
-supports one execution architecture, 64-bit Intel (``x86_64``).
+was removed in macOS 10.15. macOS 11 added support for Apple Silicon
+(``arm64``).
2. How do I build a universal binary
------------------------------------
@@ -173,8 +173,8 @@ following combinations of SDKs and universal-archs flavors are available:
* 11.0 and later SDKs support ``universal2``
The makefile for a framework build will also install ``python3.x-32``
-binaries when the universal architecture includes at least one 32-bit
-architecture (that is, for all flavors but ``64-bit`` and ``intel-64``).
+binaries when the universal architecture includes both 32-bit and 64-bit
+architectures (that is, for the ``all``, ``intel`` and ``3-way`` flavors).
It will also install ``python3.x-intel64`` binaries in the ``universal2``
case to allow easy execution with the Rosetta 2 Intel emulator on Apple
Silicon Macs.
@@ -225,7 +225,7 @@ While it is technically possible to create a .app without using frameworks you
will have to do the work yourself if you really want this.
A second reason for using frameworks is that they put Python-related items in
-only two places: "/Library/Framework/Python.framework" and
+only two places: "/Library/Frameworks/Python.framework" and
"/Applications/Python " where ```` can be e.g. "3.8",
"2.7", etc. This simplifies matters for users installing
Python from a binary distribution if they want to get rid of it again. Moreover,
@@ -275,7 +275,7 @@ in the sequence
3. make install
-This sequence will put the framework in ``/Library/Framework/Python.framework``,
+This sequence will put the framework in ``/Library/Frameworks/Python.framework``,
the applications in ``/Applications/Python `` and the unix tools in
``/usr/local/bin``.
@@ -283,7 +283,7 @@ Installing in another place, for instance ``$HOME/Library/Frameworks`` if you
have no admin privileges on your machine, is possible. This can be accomplished
by configuring with ``--enable-framework=$HOME/Library/Frameworks``.
The other two directories will then also be installed in your home directory,
-at ``$HOME/Applications/Python-`` and ``$HOME/bin``.
+at ``$HOME/Applications/Python `` and ``$HOME/bin``.
If you want to install some part, but not all, read the main Makefile. The
frameworkinstall is composed of a couple of sub-targets that install the
@@ -326,11 +326,8 @@ documentation set for this release for inclusion in the framework. The
installer package will create links to the documentation for use by IDLE,
pydoc, shell users, and Finder user.
-The script will build a universal binary so you'll therefore have to run this
-script on macOS 10.4 or later and with Xcode 2.1 or later installed.
-However, the Python build process itself has several build dependencies not
-available out of the box with macOS 10.4 so you may have to install
-additional software beyond what is provided with Xcode 2.
+The script will build a universal binary. See ``Mac/BuildScript/README.rst``
+for the recommended build environment.
It should be possible to use SDKs and/or older
versions of Xcode to build installers that are compatible with older systems
on a newer system but this may not be completely foolproof so the resulting
diff --git a/Makefile.pre.in b/Makefile.pre.in
index b42a8491733c636..c265f9b3e1e44c7 100644
--- a/Makefile.pre.in
+++ b/Makefile.pre.in
@@ -25,6 +25,13 @@ MODSHARED_NAMES= _MODSHARED_NAMES_
MODDISABLED_NAMES= _MODDISABLED_NAMES_
MODOBJS= _MODOBJS_
MODLIBS= _MODLIBS_
+# Objects and libraries of the bootstrap modules (Modules/Setup.bootstrap)
+# only. These are the only static modules linked into the build helper
+# programs (Programs/_freeze_module, _bootstrap_python), so that other
+# builtin modules (Modules/Setup.local, MODULE_BUILDTYPE=static) may depend
+# on products of those helpers (frozen modules, getpath).
+BOOTSTRAP_MODOBJS= _BOOTSTRAP_MODOBJS_
+BOOTSTRAP_MODLIBS= _BOOTSTRAP_MODLIBS_
# === Variables set by configure
VERSION= @VERSION@
@@ -50,6 +57,7 @@ GITBRANCH= @GITBRANCH@
PGO_PROF_GEN_FLAG=@PGO_PROF_GEN_FLAG@
PGO_PROF_USE_FLAG=@PGO_PROF_USE_FLAG@
LLVM_PROF_MERGER=@LLVM_PROF_MERGER@
+LLVM_PROF_SHOW=@LLVM_PROF_SHOW@
LLVM_PROF_FILE=@LLVM_PROF_FILE@
LLVM_PROF_ERR=@LLVM_PROF_ERR@
DTRACE= @DTRACE@
@@ -127,7 +135,7 @@ PY_CORE_CFLAGS= $(PY_STDMODULE_CFLAGS) -DPy_BUILD_CORE
# LDFLAGS used to build executables and shared targets.
PY_CORE_LDFLAGS=$(PY_LDFLAGS) $(PY_LDFLAGS_NODIST)
CONFIGURE_EXE_LDFLAGS=@EXE_LDFLAGS@
-PY_CORE_EXE_LDFLAGS:= $(if $(CONFIGURE_EXE_LDFLAGS), $(CONFIGURE_EXE_LDFLAGS) $(PY_LDFLAGS_NODIST), $(PY_CORE_LDFLAGS))
+PY_CORE_EXE_LDFLAGS= $(if $(CONFIGURE_EXE_LDFLAGS), $(CONFIGURE_EXE_LDFLAGS) $(PY_LDFLAGS_NODIST), $(PY_CORE_LDFLAGS))
# Strict or non-strict aliasing flags used to compile dtoa.c, see above
CFLAGS_ALIASING=@CFLAGS_ALIASING@
# Compilation flags only for ceval.c.
@@ -217,6 +225,12 @@ IPHONEOS_DEPLOYMENT_TARGET=@IPHONEOS_DEPLOYMENT_TARGET@
BUILD_DETAILS=@BUILD_DETAILS@
+# visionOS Deployment target is *actually* used during the build, by the
+# compiler shims; export.
+XROS_DEPLOYMENT_TARGET=@XROS_DEPLOYMENT_TARGET@
+@EXPORT_XROS_DEPLOYMENT_TARGET@export XROS_DEPLOYMENT_TARGET
+
+
# Option to install to strip binaries
STRIPFLAG=-s
@@ -228,6 +242,7 @@ LIPO_INTEL64_FLAGS=@LIPO_INTEL64_FLAGS@
# Environment to run shared python without installed libraries
RUNSHARED= @RUNSHARED@
+RUNSHARED_FOR_BUILD= @RUNSHARED_FOR_BUILD@
# ensurepip options
ENSUREPIP= @ENSUREPIP@
@@ -285,6 +300,7 @@ DIST= $(DISTFILES) $(DISTDIRS)
LIBRARY= @LIBRARY@
LDLIBRARY= @LDLIBRARY@
BLDLIBRARY= @BLDLIBRARY@
+MODULE_LDFLAGS_SHARED=$(if $(LIBPYTHON),$(BLDLIBRARY))
PY3LIBRARY= @PY3LIBRARY@
DLLLIBRARY= @DLLLIBRARY@
LDLIBRARYDIR= @LDLIBRARYDIR@
@@ -316,6 +332,7 @@ HOSTRUNNER= @HOSTRUNNER@
PYTHON_FOR_REGEN?=@PYTHON_FOR_REGEN@
UPDATE_FILE=$(PYTHON_FOR_REGEN) $(srcdir)/Tools/build/update_file.py
PYTHON_FOR_BUILD=@PYTHON_FOR_BUILD@
+MODULE_CHECK_COMMAND=@MODULE_CHECK_COMMAND@
# Single-platform builds depend on $(BUILDPYTHON). Cross builds use an
# external "build Python" and have an empty PYTHON_FOR_BUILD_DEPS.
PYTHON_FOR_BUILD_DEPS=@PYTHON_FOR_BUILD_DEPS@
@@ -351,11 +368,14 @@ COVERAGE_REPORT_OPTIONS=--rc lcov_branch_coverage=1 --branch-coverage --title "C
##########################################################################
# Modules
-MODULE_OBJS= \
- Modules/config.o \
+MODULE_OBJS_COMMON= \
Modules/main.o \
Modules/gcmodule.o
+MODULE_OBJS= \
+ Modules/config.o \
+ $(MODULE_OBJS_COMMON)
+
IO_H= Modules/_io/_iomodule.h
IO_OBJS= \
@@ -374,6 +394,7 @@ IO_OBJS= \
MIMALLOC_HEADERS= \
$(srcdir)/Include/internal/pycore_mimalloc.h \
$(srcdir)/Include/internal/mimalloc/mimalloc.h \
+ $(srcdir)/Include/internal/mimalloc/mimalloc-stats.h \
$(srcdir)/Include/internal/mimalloc/mimalloc/atomic.h \
$(srcdir)/Include/internal/mimalloc/mimalloc/internal.h \
$(srcdir)/Include/internal/mimalloc/mimalloc/prim.h \
@@ -389,19 +410,20 @@ PEGEN_OBJS= \
Parser/pegen_errors.o \
Parser/action_helpers.o \
Parser/parser.o \
+ Parser/parser_invalid.o \
Parser/string_parser.o \
Parser/peg_api.o
TOKENIZER_OBJS= \
- Parser/lexer/buffer.o \
Parser/lexer/lexer.o \
+ Parser/lexer/layout.o \
Parser/lexer/number.o \
Parser/lexer/state.o \
Parser/lexer/string.o \
- Parser/tokenizer/file_tokenizer.o \
- Parser/tokenizer/readline_tokenizer.o \
- Parser/tokenizer/string_tokenizer.o \
- Parser/tokenizer/utf8_tokenizer.o \
+ Parser/tokenizer/decoder.o \
+ Parser/tokenizer/api.o \
+ Parser/tokenizer/reader.o \
+ Parser/tokenizer/source.o \
Parser/tokenizer/helpers.o
PEGEN_HEADERS= \
@@ -410,10 +432,12 @@ PEGEN_HEADERS= \
$(srcdir)/Parser/string_parser.h
TOKENIZER_HEADERS= \
- Parser/lexer/buffer.h \
- Parser/lexer/lexer.h \
Parser/lexer/lexer_internal.h \
Parser/lexer/state.h \
+ Parser/tokenizer/reader.h \
+ Parser/tokenizer/reader_internal.h \
+ Parser/tokenizer/source.h \
+ Parser/tokenizer/types.h \
Parser/tokenizer/tokenizer.h \
Parser/tokenizer/helpers.h
@@ -431,6 +455,7 @@ PARSER_HEADERS= \
PYTHON_OBJS= \
Python/_contextvars.o \
+ Python/_strptime.o \
Python/_warnings.o \
Python/Python-ast.o \
Python/Python-tokenize.o \
@@ -511,6 +536,7 @@ PYTHON_OBJS= \
Python/thread.o \
Python/traceback.o \
Python/tracemalloc.o \
+ Python/typecache.o \
Python/uniqueid.o \
Python/getopt.o \
Python/pystrcmp.o \
@@ -600,6 +626,19 @@ LIBRARY_OBJS= \
Modules/getpath.o \
Python/frozen.o
+# objects that get linked into the build helper programs
+# (Programs/_freeze_module, _bootstrap_python): the core, plus the bootstrap
+# modules only (see BOOTSTRAP_MODOBJS). Does not include frozen modules nor
+# getpath, which the helpers are used to build.
+BOOTSTRAP_LIBRARY_OBJS= \
+ Modules/getbuildinfo_bootstrap.o \
+ $(PARSER_OBJS) \
+ $(OBJECT_OBJS) \
+ $(PYTHON_OBJS) \
+ Modules/config_bootstrap.o \
+ $(MODULE_OBJS_COMMON) \
+ $(BOOTSTRAP_MODOBJS)
+
LINK_PYTHON_OBJS=@LINK_PYTHON_OBJS@
##########################################################################
@@ -614,6 +653,7 @@ DTRACE_DEPS = \
# pyexpat's expat library
LIBEXPAT_OBJS= \
+ Modules/expat/xcs.o \
Modules/expat/xmlparse.o \
Modules/expat/xmlrole.o \
Modules/expat/xmltok.o
@@ -621,10 +661,12 @@ LIBEXPAT_OBJS= \
LIBEXPAT_HEADERS= \
Modules/expat/ascii.h \
Modules/expat/asciitab.h \
+ Modules/expat/entities.h \
Modules/expat/expat.h \
Modules/expat/expat_config.h \
Modules/expat/expat_external.h \
Modules/expat/fallthrough.h \
+ Modules/expat/hash_table.h \
Modules/expat/iasciitab.h \
Modules/expat/internal.h \
Modules/expat/latin1tab.h \
@@ -633,7 +675,7 @@ LIBEXPAT_HEADERS= \
Modules/expat/pyexpatns.h \
Modules/expat/siphash.h \
Modules/expat/utf8tab.h \
- Modules/expat/xcsinc.c \
+ Modules/expat/xcs.h \
Modules/expat/xmlrole.h \
Modules/expat/xmltok.h \
Modules/expat/xmltok_impl.h \
@@ -843,6 +885,7 @@ profile-run-stamp:
@ # FIXME: can't run for a cross build
$(LLVM_PROF_FILE) $(RUNSHARED) ./$(BUILDPYTHON) $(PROFILE_TASK)
$(LLVM_PROF_MERGER)
+ $(LLVM_PROF_SHOW)
# Remove profile generation binary since we are done with it.
$(MAKE) clean-retain-profile
# This is an expensive target to build and it does not have proper
@@ -964,12 +1007,15 @@ clinic: check-clean-src
clinic-tests: check-clean-src $(srcdir)/Lib/test/clinic.test.c
$(PYTHON_FOR_REGEN) $(srcdir)/Tools/clinic/clinic.py -f $(srcdir)/Lib/test/clinic.test.c
+# Objects linked into the interpreter only, not into libpython.
+PLATFORM_MAIN_OBJS= @PLATFORM_MAIN_OBJS@
+
# Build the interpreter
-$(BUILDPYTHON): Programs/python.o $(LINK_PYTHON_DEPS)
- $(LINKCC) $(PY_CORE_EXE_LDFLAGS) $(LINKFORSHARED) -o $@ Programs/python.o $(LINK_PYTHON_OBJS) $(LIBS) $(MODLIBS) $(SYSLIBS)
+$(BUILDPYTHON): Programs/python.o $(PLATFORM_MAIN_OBJS) $(LINK_PYTHON_DEPS)
+ $(LINKCC) $(PY_CORE_EXE_LDFLAGS) $(LINKFORSHARED) -o $@ Programs/python.o $(PLATFORM_MAIN_OBJS) $(LINK_PYTHON_OBJS) $(LIBS) $(MODLIBS) $(SYSLIBS)
platform: $(PYTHON_FOR_BUILD_DEPS) pybuilddir.txt
- $(RUNSHARED) $(PYTHON_FOR_BUILD) -c 'import sys ; from sysconfig import get_platform ; print("%s-%d.%d" % (get_platform(), *sys.version_info[:2]))' >platform
+ $(RUNSHARED_FOR_BUILD) $(PYTHON_FOR_BUILD) -c 'import sys ; from sysconfig import get_platform ; print("%s-%d.%d" % (get_platform(), *sys.version_info[:2]))' >platform
# Create build directory and generate the sysconfig build-time data there.
# pybuilddir.txt contains the name of the build dir and is used for
@@ -980,7 +1026,7 @@ platform: $(PYTHON_FOR_BUILD_DEPS) pybuilddir.txt
# or removed in case of failure.
pybuilddir.txt: $(PYTHON_FOR_BUILD_DEPS)
@echo "none" > ./pybuilddir.txt
- $(RUNSHARED) $(PYTHON_FOR_BUILD) -S -X pathconfig_warnings=0 -m sysconfig --generate-posix-vars ;\
+ $(RUNSHARED_FOR_BUILD) $(PYTHON_FOR_BUILD) -S -X pathconfig_warnings=0 -m sysconfig --generate-posix-vars ;\
if test $$? -ne 0 ; then \
echo "generate-posix-vars failed" ; \
rm -f ./pybuilddir.txt ; \
@@ -988,7 +1034,7 @@ pybuilddir.txt: $(PYTHON_FOR_BUILD_DEPS)
fi
$(BUILD_DETAILS): pybuilddir.txt
- $(RUNSHARED) $(PYTHON_FOR_BUILD) $(srcdir)/Tools/build/generate-build-details.py `cat pybuilddir.txt`/$(BUILD_DETAILS)
+ $(RUNSHARED_FOR_BUILD) $(PYTHON_FOR_BUILD) $(srcdir)/Tools/build/generate-build-details.py `cat pybuilddir.txt`/$(BUILD_DETAILS)
# Build static library
$(LIBRARY): $(LIBRARY_OBJS)
@@ -1010,7 +1056,7 @@ libpython3.so: libpython$(LDVERSION).so
$(BLDSHARED) $(NO_AS_NEEDED) -o $@ -Wl,-h$@ $^
libpython$(LDVERSION).dylib: $(LIBRARY_OBJS)
- $(CC) -dynamiclib $(PY_CORE_LDFLAGS) -undefined dynamic_lookup -Wl,-install_name,$(prefix)/lib/libpython$(LDVERSION).dylib -Wl,-compatibility_version,$(VERSION) -Wl,-current_version,$(VERSION) -o $@ $(LIBRARY_OBJS) $(DTRACE_OBJS) $(SHLIBS) $(LIBC) $(LIBM); \
+ $(CC) -dynamiclib $(PY_CORE_LDFLAGS) -undefined dynamic_lookup -Wl,-install_name,$(prefix)/lib/libpython$(LDVERSION).dylib -Wl,-compatibility_version,$(VERSION) -Wl,-current_version,$(VERSION) -o $@ $(LIBRARY_OBJS) $(DTRACE_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM); \
libpython$(VERSION).sl: $(LIBRARY_OBJS)
@@ -1044,7 +1090,7 @@ $(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK): \
-install_name $(PYTHONFRAMEWORKINSTALLNAMEPREFIX)/$(PYTHONFRAMEWORK) \
-compatibility_version $(VERSION) \
-current_version $(VERSION) \
- -framework CoreFoundation $(LIBS);
+ -framework CoreFoundation $(MODLIBS) $(LIBS);
$(INSTALL) -d -m $(DIRMODE) \
$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/Resources/English.lproj
$(INSTALL_DATA) $(RESSRCDIR)/Info.plist \
@@ -1065,7 +1111,7 @@ $(PYTHONFRAMEWORKDIR)/$(PYTHONFRAMEWORK): \
-install_name $(PYTHONFRAMEWORKINSTALLNAMEPREFIX)/$(PYTHONFRAMEWORK) \
-compatibility_version $(VERSION) \
-current_version $(VERSION) \
- -framework CoreFoundation $(LIBS);
+ -framework CoreFoundation $(MODLIBS) $(LIBS);
$(INSTALL_DATA) $(RESSRCDIR)/Info.plist $(PYTHONFRAMEWORKDIR)/Info.plist
# This rule builds the Cygwin Python DLL and import library if configured
@@ -1113,6 +1159,20 @@ web_example/python.mjs web_example/python.wasm: $(BUILDPYTHON)
cp python.mjs web_example/python.mjs
cp python.wasm web_example/python.wasm
+WEB_EMBED_TEST_DIR=$(EMSCRIPTEN_DIR)/web_embed_test
+
+# Linked like an embedder would: against libpython.a, without $(LINKFORSHARED)
+# and so without -sMAIN_MODULE or the interpreter's -sEXPORTED_FUNCTIONS.
+web_embed_test/main.js: $(WEB_EMBED_TEST_DIR)/main.c $(LIBRARY) $(ZIP_STDLIB)
+ @mkdir -p web_embed_test
+ $(LINKCC) $(PY_STDMODULE_CFLAGS) $(PY_CORE_EXE_LDFLAGS) -O2 -g0 -o $@ \
+ $(WEB_EMBED_TEST_DIR)/main.c $(LIBRARY) $(LIBS) $(MODLIBS) $(SYSLIBS) \
+ -sALLOW_MEMORY_GROWTH -sSTACK_SIZE=5MB \
+ --preload-file $(ZIP_STDLIB)@/lib/stdlib.zip
+
+.PHONY: web_embed_test
+web_embed_test: web_embed_test/main.js
+
.PHONY: web_example
web_example: web_example/python.mjs web_example/python.worker.mjs web_example/index.html web_example/server.py web_example/$(ZIP_STDLIB)
@@ -1339,6 +1399,7 @@ PYTHON_HEADERS= \
$(srcdir)/Include/internal/pycore_getopt.h \
$(srcdir)/Include/internal/pycore_gil.h \
$(srcdir)/Include/internal/pycore_global_objects.h \
+ $(srcdir)/Include/internal/pycore_global_objects_fini.h \
$(srcdir)/Include/internal/pycore_global_objects_fini_generated.h \
$(srcdir)/Include/internal/pycore_global_strings.h \
$(srcdir)/Include/internal/pycore_hamt.h \
@@ -1355,6 +1416,7 @@ PYTHON_HEADERS= \
$(srcdir)/Include/internal/pycore_interpframe_structs.h \
$(srcdir)/Include/internal/pycore_interpolation.h \
$(srcdir)/Include/internal/pycore_intrinsics.h \
+ $(srcdir)/Include/internal/pycore_iterobject.h \
$(srcdir)/Include/internal/pycore_jit.h \
$(srcdir)/Include/internal/pycore_lazyimportobject.h \
$(srcdir)/Include/internal/pycore_list.h \
@@ -1419,6 +1481,7 @@ PYTHON_HEADERS= \
$(srcdir)/Include/internal/pycore_tracemalloc.h \
$(srcdir)/Include/internal/pycore_tstate.h \
$(srcdir)/Include/internal/pycore_tuple.h \
+ $(srcdir)/Include/internal/pycore_typecache.h \
$(srcdir)/Include/internal/pycore_typedefs.h \
$(srcdir)/Include/internal/pycore_typeobject.h \
$(srcdir)/Include/internal/pycore_typevarobject.h \
@@ -1431,6 +1494,7 @@ PYTHON_HEADERS= \
$(srcdir)/Include/internal/pycore_uop.h \
$(srcdir)/Include/internal/pycore_uop_ids.h \
$(srcdir)/Include/internal/pycore_uop_metadata.h \
+ $(srcdir)/Include/internal/pycore_wasm_trampoline.h \
$(srcdir)/Include/internal/pycore_warnings.h \
$(srcdir)/Include/internal/pycore_weakref.h \
$(DTRACE_HEADERS) \
@@ -1442,6 +1506,9 @@ PYTHON_HEADERS= \
# Build static libexpat.a
LIBEXPAT_CFLAGS=@LIBEXPAT_CFLAGS@ $(PY_STDMODULE_CFLAGS) $(CCSHARED)
+Modules/expat/xcs.o: $(srcdir)/Modules/expat/xcs.c $(LIBEXPAT_HEADERS) $(PYTHON_HEADERS)
+ $(CC) -c $(LIBEXPAT_CFLAGS) -o $@ $(srcdir)/Modules/expat/xcs.c
+
Modules/expat/xmlparse.o: $(srcdir)/Modules/expat/xmlparse.c $(LIBEXPAT_HEADERS) $(PYTHON_HEADERS)
$(CC) -c $(LIBEXPAT_CFLAGS) -o $@ $(srcdir)/Modules/expat/xmlparse.c
@@ -1539,11 +1606,11 @@ sharedmods: $(SHAREDMODS) pybuilddir.txt
.PHONY: checksharedmods
checksharedmods: sharedmods $(PYTHON_FOR_BUILD_DEPS) $(BUILDPYTHON)
@if [ -n "@MISSING_STDLIB_CONFIG@" ]; then \
- $(RUNSHARED) $(PYTHON_FOR_BUILD) $(srcdir)/Tools/build/check_extension_modules.py --generate-missing-stdlib-info --with-missing-stdlib-config="@MISSING_STDLIB_CONFIG@"; \
+ $(MODULE_CHECK_COMMAND) --generate-missing-stdlib-info --with-missing-stdlib-config="@MISSING_STDLIB_CONFIG@"; \
else \
- $(RUNSHARED) $(PYTHON_FOR_BUILD) $(srcdir)/Tools/build/check_extension_modules.py --generate-missing-stdlib-info; \
+ $(MODULE_CHECK_COMMAND) --generate-missing-stdlib-info; \
fi
- @$(RUNSHARED) $(PYTHON_FOR_BUILD) $(srcdir)/Tools/build/check_extension_modules.py
+ @$(MODULE_CHECK_COMMAND)
.PHONY: rundsymutil
rundsymutil: sharedmods $(PYTHON_FOR_BUILD_DEPS) $(BUILDPYTHON)
@@ -1572,7 +1639,7 @@ Modules/Setup.bootstrap: $(srcdir)/Modules/Setup.bootstrap.in config.status
Modules/Setup.stdlib: $(srcdir)/Modules/Setup.stdlib.in config.status
./config.status $@
-Makefile Modules/config.c: Makefile.pre \
+Makefile Modules/config.c Modules/config_bootstrap.c: Makefile.pre \
$(srcdir)/Modules/config.c.in \
$(MAKESETUP) \
$(srcdir)/Modules/Setup \
@@ -1583,9 +1650,9 @@ Makefile Modules/config.c: Makefile.pre \
-s Modules \
Modules/Setup.local \
Modules/Setup.stdlib \
- Modules/Setup.bootstrap \
+ -b Modules/Setup.bootstrap \
$(srcdir)/Modules/Setup
- @mv config.c Modules
+ @mv config.c config_bootstrap.c Modules
@echo "The Makefile was updated, you may need to re-run make."
.PHONY: regen-test-frozenmain
@@ -1606,8 +1673,8 @@ regen-re: $(BUILDPYTHON)
# using Tools/build/generate_re_casefix.py
$(RUNSHARED) ./$(BUILDPYTHON) $(srcdir)/Tools/build/generate_re_casefix.py $(srcdir)/Lib/re/_casefix.py
-Programs/_testembed: Programs/_testembed.o $(LINK_PYTHON_DEPS)
- $(LINKCC) $(PY_CORE_EXE_LDFLAGS) $(LINKFORSHARED) -o $@ Programs/_testembed.o $(LINK_PYTHON_OBJS) $(LIBS) $(MODLIBS) $(SYSLIBS)
+Programs/_testembed: Programs/_testembed.o $(PLATFORM_MAIN_OBJS) $(LINK_PYTHON_DEPS)
+ $(LINKCC) $(PY_CORE_EXE_LDFLAGS) $(LINKFORSHARED) -o $@ Programs/_testembed.o $(PLATFORM_MAIN_OBJS) $(LINK_PYTHON_OBJS) $(LIBS) $(MODLIBS) $(SYSLIBS)
############################################################################
# "Bootstrap Python" used to run Programs/_freeze_module.py
@@ -1615,13 +1682,14 @@ Programs/_testembed: Programs/_testembed.o $(LINK_PYTHON_DEPS)
BOOTSTRAP_HEADERS = \
Python/frozen_modules/importlib._bootstrap.h \
Python/frozen_modules/importlib._bootstrap_external.h \
- Python/frozen_modules/zipimport.h
+ Python/frozen_modules/zipimport.h \
+ Python/frozen_modules/builtins.h
Programs/_bootstrap_python.o: Programs/_bootstrap_python.c $(BOOTSTRAP_HEADERS) $(PYTHON_HEADERS)
-_bootstrap_python: $(LIBRARY_OBJS_OMIT_FROZEN) Programs/_bootstrap_python.o Modules/getpath.o Modules/Setup.local
- $(LINKCC) $(PY_LDFLAGS_NOLTO) -o $@ $(LIBRARY_OBJS_OMIT_FROZEN) \
- Programs/_bootstrap_python.o Modules/getpath.o $(LIBS) $(MODLIBS) $(SYSLIBS)
+_bootstrap_python: $(BOOTSTRAP_LIBRARY_OBJS) Programs/_bootstrap_python.o Modules/getpath.o Modules/Setup.local
+ $(LINKCC) $(PY_LDFLAGS_NOLTO) -o $@ $(BOOTSTRAP_LIBRARY_OBJS) \
+ Programs/_bootstrap_python.o Modules/getpath.o $(LIBS) $(BOOTSTRAP_MODLIBS) $(SYSLIBS)
# Dummy pybuilddir.txt is needed for _bootstrap_python to be runnable
@echo "none" > ./pybuilddir.txt
@@ -1639,6 +1707,9 @@ _bootstrap_python: $(LIBRARY_OBJS_OMIT_FROZEN) Programs/_bootstrap_python.o Modu
#
# Standard build process:
# 1) compile minimal core objects for Py_Compile*() and PyMarshal_Write*().
+# Only the bootstrap modules (Modules/Setup.bootstrap) are part of these
+# objects (see BOOTSTRAP_LIBRARY_OBJS), so other builtin modules may
+# depend on the output of the following steps.
# 2) build Programs/_freeze_module binary.
# 3) create frozen module headers for importlib and getpath.
# 4) build _bootstrap_python binary.
@@ -1656,13 +1727,9 @@ FROZEN_FILES_IN = \
Lib/importlib/_bootstrap.py \
Lib/importlib/_bootstrap_external.py \
Lib/zipimport.py \
+ Lib/_pybuiltins.py \
Lib/abc.py \
Lib/codecs.py \
- Lib/encodings/__init__.py \
- Lib/encodings/aliases.py \
- Lib/encodings/utf_8.py \
- Lib/encodings/_win_cp_codecs.py \
- Lib/encodings/_iconv_codecs.py \
Lib/io.py \
Lib/_collections_abc.py \
Lib/_sitebuiltins.py \
@@ -1687,13 +1754,9 @@ FROZEN_FILES_OUT = \
Python/frozen_modules/importlib._bootstrap.h \
Python/frozen_modules/importlib._bootstrap_external.h \
Python/frozen_modules/zipimport.h \
+ Python/frozen_modules/builtins.h \
Python/frozen_modules/abc.h \
Python/frozen_modules/codecs.h \
- Python/frozen_modules/encodings.h \
- Python/frozen_modules/encodings.aliases.h \
- Python/frozen_modules/encodings.utf_8.h \
- Python/frozen_modules/encodings._win_cp_codecs.h \
- Python/frozen_modules/encodings._iconv_codecs.h \
Python/frozen_modules/io.h \
Python/frozen_modules/_collections_abc.h \
Python/frozen_modules/_sitebuiltins.h \
@@ -1719,8 +1782,8 @@ Programs/_freeze_module.o: Programs/_freeze_module.c Makefile
Modules/getpath_noop.o: $(srcdir)/Modules/getpath_noop.c Makefile
-Programs/_freeze_module: Programs/_freeze_module.o Modules/getpath_noop.o $(LIBRARY_OBJS_OMIT_FROZEN)
- $(LINKCC) $(PY_CORE_LDFLAGS) -o $@ Programs/_freeze_module.o Modules/getpath_noop.o $(LIBRARY_OBJS_OMIT_FROZEN) $(LIBS) $(MODLIBS) $(SYSLIBS)
+Programs/_freeze_module: Programs/_freeze_module.o Modules/getpath_noop.o $(BOOTSTRAP_LIBRARY_OBJS)
+ $(LINKCC) $(PY_CORE_LDFLAGS) -o $@ Programs/_freeze_module.o Modules/getpath_noop.o $(BOOTSTRAP_LIBRARY_OBJS) $(LIBS) $(BOOTSTRAP_MODLIBS) $(SYSLIBS)
# We manually freeze getpath.py rather than through freeze_modules
Python/frozen_modules/getpath.h: Modules/getpath.py $(FREEZE_MODULE_BOOTSTRAP_DEPS)
@@ -1737,27 +1800,15 @@ Python/frozen_modules/importlib._bootstrap_external.h: Lib/importlib/_bootstrap_
Python/frozen_modules/zipimport.h: Lib/zipimport.py $(FREEZE_MODULE_BOOTSTRAP_DEPS)
$(FREEZE_MODULE_BOOTSTRAP) zipimport $(srcdir)/Lib/zipimport.py Python/frozen_modules/zipimport.h
+Python/frozen_modules/builtins.h: Lib/_pybuiltins.py $(FREEZE_MODULE_BOOTSTRAP_DEPS)
+ $(FREEZE_MODULE_BOOTSTRAP) builtins $(srcdir)/Lib/_pybuiltins.py Python/frozen_modules/builtins.h
+
Python/frozen_modules/abc.h: Lib/abc.py $(FREEZE_MODULE_DEPS)
$(FREEZE_MODULE) abc $(srcdir)/Lib/abc.py Python/frozen_modules/abc.h
Python/frozen_modules/codecs.h: Lib/codecs.py $(FREEZE_MODULE_DEPS)
$(FREEZE_MODULE) codecs $(srcdir)/Lib/codecs.py Python/frozen_modules/codecs.h
-Python/frozen_modules/encodings.h: Lib/encodings/__init__.py $(FREEZE_MODULE_DEPS)
- $(FREEZE_MODULE) encodings $(srcdir)/Lib/encodings/__init__.py Python/frozen_modules/encodings.h
-
-Python/frozen_modules/encodings.aliases.h: Lib/encodings/aliases.py $(FREEZE_MODULE_DEPS)
- $(FREEZE_MODULE) encodings.aliases $(srcdir)/Lib/encodings/aliases.py Python/frozen_modules/encodings.aliases.h
-
-Python/frozen_modules/encodings.utf_8.h: Lib/encodings/utf_8.py $(FREEZE_MODULE_DEPS)
- $(FREEZE_MODULE) encodings.utf_8 $(srcdir)/Lib/encodings/utf_8.py Python/frozen_modules/encodings.utf_8.h
-
-Python/frozen_modules/encodings._win_cp_codecs.h: Lib/encodings/_win_cp_codecs.py $(FREEZE_MODULE_DEPS)
- $(FREEZE_MODULE) encodings._win_cp_codecs $(srcdir)/Lib/encodings/_win_cp_codecs.py Python/frozen_modules/encodings._win_cp_codecs.h
-
-Python/frozen_modules/encodings._iconv_codecs.h: Lib/encodings/_iconv_codecs.py $(FREEZE_MODULE_DEPS)
- $(FREEZE_MODULE) encodings._iconv_codecs $(srcdir)/Lib/encodings/_iconv_codecs.py Python/frozen_modules/encodings._iconv_codecs.h
-
Python/frozen_modules/io.h: Lib/io.py $(FREEZE_MODULE_DEPS)
$(FREEZE_MODULE) io $(srcdir)/Lib/io.py Python/frozen_modules/io.h
@@ -1866,6 +1917,7 @@ regen-unicodedata:
# Regenerate all generated files
# "clinic" is regenerated implicitly via "regen-global-objects".
+# Keep the list of targets to run manually in sync with Doc/using/configure.rst.
.PHONY: regen-all
regen-all: regen-cases regen-slots \
regen-token regen-ast regen-keyword regen-sre regen-frozen \
@@ -1885,11 +1937,24 @@ Modules/getbuildinfo.o: $(PARSER_OBJS) \
$(MODOBJS) \
$(DTRACE_OBJS) \
$(srcdir)/Modules/getbuildinfo.c
- $(CC) -c $(PY_CORE_CFLAGS) \
+ $(CC) -c $(PY_CORE_CFLAGS) $(GETBUILDINFO_CFLAGS) \
+ -o $@ $(srcdir)/Modules/getbuildinfo.c
+
+# Separate object for the build helper programs: it must not depend on
+# $(MODOBJS), which may in turn depend on the helpers' output.
+Modules/getbuildinfo_bootstrap.o: $(PARSER_OBJS) \
+ $(OBJECT_OBJS) \
+ $(PYTHON_OBJS) \
+ $(MODULE_OBJS_COMMON) \
+ $(BOOTSTRAP_MODOBJS) \
+ $(srcdir)/Modules/getbuildinfo.c
+ $(CC) -c $(PY_CORE_CFLAGS) $(GETBUILDINFO_CFLAGS) \
+ -o $@ $(srcdir)/Modules/getbuildinfo.c
+
+GETBUILDINFO_CFLAGS= \
-DGITVERSION="\"`LC_ALL=C $(GITVERSION)`\"" \
-DGITTAG="\"`LC_ALL=C $(GITTAG)`\"" \
- -DGITBRANCH="\"`LC_ALL=C $(GITBRANCH)`\"" \
- -o $@ $(srcdir)/Modules/getbuildinfo.c
+ -DGITBRANCH="\"`LC_ALL=C $(GITBRANCH)`\""
Modules/getpath.o: $(srcdir)/Modules/getpath.c Python/frozen_modules/getpath.h Makefile $(PYTHON_HEADERS)
$(CC) -c $(PY_CORE_CFLAGS) -DPYTHONPATH='"$(PYTHONPATH)"' \
@@ -1966,6 +2031,7 @@ regen-pegen:
$(srcdir)/Grammar/Tokens \
-o $(srcdir)/Parser/parser.c.new
$(UPDATE_FILE) --create $(srcdir)/Parser/parser.c $(srcdir)/Parser/parser.c.new
+ $(UPDATE_FILE) --create $(srcdir)/Parser/parser_invalid.c $(srcdir)/Parser/parser_invalid.c.new
.PHONY: regen-ast
regen-ast:
@@ -2090,9 +2156,12 @@ Objects/obmalloc.o: $(srcdir)/Objects/mimalloc/alloc.c \
$(srcdir)/Objects/mimalloc/alloc-aligned.c \
$(srcdir)/Objects/mimalloc/alloc-posix.c \
$(srcdir)/Objects/mimalloc/arena.c \
+ $(srcdir)/Objects/mimalloc/arena-abandon.c \
$(srcdir)/Objects/mimalloc/bitmap.c \
+ $(srcdir)/Objects/mimalloc/free.c \
$(srcdir)/Objects/mimalloc/heap.c \
$(srcdir)/Objects/mimalloc/init.c \
+ $(srcdir)/Objects/mimalloc/libc.c \
$(srcdir)/Objects/mimalloc/options.c \
$(srcdir)/Objects/mimalloc/os.c \
$(srcdir)/Objects/mimalloc/page.c \
@@ -2101,6 +2170,7 @@ Objects/obmalloc.o: $(srcdir)/Objects/mimalloc/alloc.c \
$(srcdir)/Objects/mimalloc/segment-map.c \
$(srcdir)/Objects/mimalloc/stats.c \
$(srcdir)/Objects/mimalloc/prim/prim.c \
+ $(srcdir)/Objects/mimalloc/prim/emscripten/prim.c \
$(srcdir)/Objects/mimalloc/prim/osx/prim.c \
$(srcdir)/Objects/mimalloc/prim/unix/prim.c \
$(srcdir)/Objects/mimalloc/prim/wasi/prim.c
@@ -2252,7 +2322,7 @@ regen-slots: Python/slots.toml
$(PYTHON_FOR_REGEN) $(srcdir)/Tools/build/generate_slots.py \
--generate-all
-$(LIBRARY_OBJS) $(MODOBJS) Programs/python.o: $(PYTHON_HEADERS)
+$(LIBRARY_OBJS) $(MODOBJS) Modules/config_bootstrap.o Programs/python.o $(PLATFORM_MAIN_OBJS): $(PYTHON_HEADERS)
######################################################################
@@ -2293,32 +2363,31 @@ testuniversal: all
$(RUNSHARED) /usr/libexec/oah/translate \
./$(BUILDPYTHON) -E -m test -j 0 -u all $(TESTOPTS)
-# Run the test suite on the iOS simulator. Must be run on a macOS machine with
-# a full Xcode install that has an iPhone SE (3rd edition) simulator available.
+# Run the test suite on an Apple Mobile (i.e., iOS/tvOS/watchOS/visionOS)
+# device simulator. Must be run on a macOS machine with a full Xcode install
+# that has an SE-class simulator available for the chosen platform.
# This must be run *after* a `make install` has completed the build. The
-# `--with-framework-name` argument *cannot* be used when configuring the build.
-XCFOLDER:=iOSTestbed.$(MULTIARCH).$(shell date +%s).$$PPID
+# testbed is configured for the framework name used to configure the build;
+# that name is expected to be `Python`, optionally followed by uppercased ABI
+# flags (e.g., `PythonT`).
+XCFOLDER:=AppleTestbed.$(MULTIARCH).$(shell date +%s).$$PPID
.PHONY: testios
testios:
- @if test "$(MACHDEP)" != "ios"; then \
- echo "Cannot run the iOS testbed for a non-iOS build."; \
+ @if test "$(MACHDEP)" != "ios" -a "$(MACHDEP)" != "tvos" -a "$(MACHDEP)" != "visionos" -a "$(MACHDEP)" != "watchos" ; then \
+ echo "Cannot run the Apple mobile testbed for a $(MACHDEP) build."; \
exit 1;\
fi
- @if test "$(findstring -iphonesimulator,$(MULTIARCH))" != "-iphonesimulator"; then \
- echo "Cannot run the iOS testbed for non-simulator builds."; \
- exit 1;\
- fi
- @if test $(PYTHONFRAMEWORK) != "Python"; then \
- echo "Cannot run the iOS testbed with a non-default framework name."; \
+ @if test "$(findstring simulator,$(MULTIARCH))" != "simulator"; then \
+ echo "Cannot run the Apple mobile testbed for non-simulator builds."; \
exit 1;\
fi
@if ! test -d $(PYTHONFRAMEWORKPREFIX); then \
- echo "Cannot find a finalized iOS Python.framework. Have you run 'make install' to finalize the framework build?"; \
+ echo "Cannot find a finalized Python.framework. Have you run 'make install' to finalize the framework build?"; \
exit 1;\
fi
# Clone the testbed project into the XCFOLDER
- $(PYTHON_FOR_BUILD) $(srcdir)/Platforms/Apple/testbed clone --framework $(PYTHONFRAMEWORKPREFIX) "$(XCFOLDER)"
+ $(PYTHON_FOR_BUILD) $(srcdir)/Platforms/Apple/testbed clone --platform $(MACHDEP) --framework $(PYTHONFRAMEWORKPREFIX) "$(XCFOLDER)"
# Run the testbed project
$(PYTHON_FOR_BUILD) "$(XCFOLDER)" run --verbose -- test -uall --single-process --rerun -W --pythoninfo
@@ -2370,7 +2439,7 @@ install: @FRAMEWORKINSTALLFIRST@ @INSTALLTARGETS@ @FRAMEWORKINSTALLLAST@
upgrade) ensurepip="--upgrade" ;; \
install|*) ensurepip="" ;; \
esac; \
- $(RUNSHARED) $(PYTHON_FOR_BUILD) -m ensurepip \
+ $(RUNSHARED_FOR_BUILD) $(PYTHON_FOR_BUILD) -m ensurepip \
$$ensurepip --root=$(DESTDIR)/ ; \
fi
@@ -2381,7 +2450,7 @@ altinstall: commoninstall
upgrade) ensurepip="--altinstall --upgrade" ;; \
install|*) ensurepip="--altinstall" ;; \
esac; \
- $(RUNSHARED) $(PYTHON_FOR_BUILD) -m ensurepip \
+ $(RUNSHARED_FOR_BUILD) $(PYTHON_FOR_BUILD) -m ensurepip \
$$ensurepip --root=$(DESTDIR)/ ; \
fi
@@ -2417,7 +2486,7 @@ sharedinstall: all
# Install the interpreter with $(VERSION) affixed
# This goes into $(exec_prefix)
.PHONY: altbininstall
-altbininstall: $(BUILDPYTHON) @FRAMEWORKPYTHONW@
+altbininstall: all @FRAMEWORKPYTHONW@
@for i in $(BINDIR) $(LIBDIR); \
do \
if test ! -d $(DESTDIR)$$i; then \
@@ -2622,7 +2691,6 @@ TESTSUBDIRS= idlelib/idle_test \
test/test_capi \
test/test_cext \
test/test_concurrent_futures \
- test/test_cppext \
test/test_ctypes \
test/test_dataclasses \
test/test_doctest \
@@ -2687,6 +2755,7 @@ TESTSUBDIRS= idlelib/idle_test \
test/test_lazy_import/data/pkg \
test/test_lazy_import/data/badsyntax \
test/test_lazy_import/data/circular_import_pkg \
+ test/test_lazy_import/data/lazypkg \
test/test_lazy_import/data/metasyntactic \
test/test_lazy_import/data/metasyntactic/foo \
test/test_lazy_import/data/metasyntactic/foo/ack \
@@ -2847,12 +2916,12 @@ libinstall: all $(srcdir)/Modules/xxmodule.c
patch --force --reject-file "$(abs_builddir)/app-store-compliance.rej" --strip 2 --directory "$(DESTDIR)$(LIBDEST)" --input "$(abs_srcdir)/$(APP_STORE_COMPLIANCE_PATCH)" || true ; \
fi
@ # Build PYC files for the 3 optimization levels (0, 1, 2)
- -PYTHONPATH=$(DESTDIR)$(LIBDEST) $(RUNSHARED) \
+ -PYTHONPATH=$(DESTDIR)$(LIBDEST) $(RUNSHARED_FOR_BUILD) \
$(PYTHON_FOR_BUILD) -Wi $(DESTDIR)$(LIBDEST)/compileall.py \
-o 0 -o 1 -o 2 $(COMPILEALL_OPTS) -d $(LIBDEST) -f \
-x 'bad_coding|badsyntax|site-packages' \
$(DESTDIR)$(LIBDEST)
- -PYTHONPATH=$(DESTDIR)$(LIBDEST) $(RUNSHARED) \
+ -PYTHONPATH=$(DESTDIR)$(LIBDEST) $(RUNSHARED_FOR_BUILD) \
$(PYTHON_FOR_BUILD) -Wi $(DESTDIR)$(LIBDEST)/compileall.py \
-o 0 -o 1 -o 2 $(COMPILEALL_OPTS) -d $(LIBDEST)/site-packages -f \
-x badsyntax $(DESTDIR)$(LIBDEST)/site-packages
@@ -2936,8 +3005,11 @@ inclinstall:
$(INSTALL_DATA) $$i $(DESTDIR)$(INCLUDEPY)/internal; \
done
@if test "$(INSTALL_MIMALLOC)" = "yes"; then \
- echo $(INSTALL_DATA) $(srcdir)/Include/internal/mimalloc/mimalloc.h $(DESTDIR)$(INCLUDEPY)/internal/mimalloc/mimalloc.h; \
- $(INSTALL_DATA) $(srcdir)/Include/internal/mimalloc/mimalloc.h $(DESTDIR)$(INCLUDEPY)/internal/mimalloc/mimalloc.h; \
+ for i in $(srcdir)/Include/internal/mimalloc/*.h; \
+ do \
+ echo $(INSTALL_DATA) $$i $(INCLUDEPY)/internal/mimalloc; \
+ $(INSTALL_DATA) $$i $(DESTDIR)$(INCLUDEPY)/internal/mimalloc; \
+ done; \
for i in $(srcdir)/Include/internal/mimalloc/mimalloc/*.h; \
do \
echo $(INSTALL_DATA) $$i $(INCLUDEPY)/internal/mimalloc/mimalloc; \
@@ -2977,6 +3049,9 @@ libainstall: all scripts
fi; \
fi; \
$(INSTALL_DATA) Programs/python.o $(DESTDIR)$(LIBPL)/python.o; \
+ for i in $(PLATFORM_MAIN_OBJS); do \
+ $(INSTALL_DATA) $$i $(DESTDIR)$(LIBPL); \
+ done; \
fi
$(INSTALL_DATA) Modules/config.c $(DESTDIR)$(LIBPL)/config.c
$(INSTALL_DATA) $(srcdir)/Modules/config.c.in $(DESTDIR)$(LIBPL)/config.c.in
@@ -3066,7 +3141,7 @@ frameworkinstallunversionedstructure: $(LDLIBRARY)
rm -rf $(DESTDIR)$(PYTHONFRAMEWORKPREFIX)/include; \
fi
$(INSTALL) -d -m $(DIRMODE) $(DESTDIR)$(PYTHONFRAMEWORKINSTALLDIR)
- sed 's/%VERSION%/'"`$(RUNSHARED) $(PYTHON_FOR_BUILD) -c 'import platform; print(platform.python_version())'`"'/g' < $(RESSRCDIR)/Info.plist > $(DESTDIR)$(PYTHONFRAMEWORKINSTALLDIR)/Info.plist
+ sed 's/%VERSION%/'"`$(RUNSHARED_FOR_BUILD) $(PYTHON_FOR_BUILD) -c 'import platform; print(platform.python_version())'`"'/g' < $(RESSRCDIR)/Info.plist > $(DESTDIR)$(PYTHONFRAMEWORKINSTALLDIR)/Info.plist
$(INSTALL_SHARED) $(LDLIBRARY) $(DESTDIR)$(PYTHONFRAMEWORKPREFIX)/$(LDLIBRARY)
$(INSTALL) -d -m $(DIRMODE) $(DESTDIR)$(LIBDIR)
$(LN) -fs "../$(LDLIBRARY)" "$(DESTDIR)$(prefix)/lib/libpython$(LDVERSION).dylib"
@@ -3164,13 +3239,6 @@ Python/asm_trampoline_universal2.o: $(srcdir)/Python/asm_trampoline_aarch64.S $(
rm -f Python/asm_trampoline_arm64-apple-darwin.o \
Python/asm_trampoline_x86_64-apple-darwin.o
-Python/emscripten_trampoline_inner.wasm: $(srcdir)/Python/emscripten_trampoline_inner.c
- # emcc has a path that ends with emsdk/upstream/emscripten/emcc, we're looking for emsdk/upstream/bin/clang.
- $$(em-config LLVM_ROOT)/clang -o $@ $< -mgc -O2 -Wl,--no-entry -Wl,--import-table -Wl,--import-memory -target wasm32-unknown-unknown -nostdlib
-
-Python/emscripten_trampoline_wasm.c: Python/emscripten_trampoline_inner.wasm
- $(PYTHON_FOR_REGEN) $(srcdir)/Platforms/emscripten/prepare_external_wasm.py $< $@ getWasmTrampolineModule
-
JIT_SHIM_BUILD_OBJS= @JIT_SHIM_BUILD_O@
JIT_UNWIND_INFO_H= $(if $(JIT_OBJS),jit_unwind_info.h $(patsubst jit_stencils-%.h,jit_unwind_info-%.h,@JIT_STENCILS_H@))
JIT_BUILD_TARGETS= jit_stencils.h @JIT_STENCILS_H@ $(JIT_UNWIND_INFO_H) $(JIT_SHIM_BUILD_OBJS)
@@ -3298,7 +3366,7 @@ clean-retain-profile: pycremoval
find build -name '*.py[co]' -exec rm -f {} ';' || true
-rm -f pybuilddir.txt
-rm -f _bootstrap_python
- -rm -rf web_example python.mjs python.wasm python*.symbols python*.map
+ -rm -rf web_example web_embed_test python.mjs python.wasm python*.symbols python*.map
-rm -f Programs/_testembed Programs/_freeze_module
-rm -rf Python/deepfreeze
-rm -f Python/frozen_modules/*.h
@@ -3340,7 +3408,7 @@ clean: clean-profile clean-jit-stencils
clobber: clean
-rm -f $(BUILDPYTHON) $(LIBRARY) $(LDLIBRARY) $(DLLLIBRARY) \
tags TAGS \
- config.cache config.log pyconfig.h Modules/config.c
+ config.cache config.log pyconfig.h Modules/config.c Modules/config_bootstrap.c
-rm -rf build platform
-rm -rf $(PYTHONFRAMEWORKDIR)
-rm -rf Platforms/Apple/iOS/Frameworks
@@ -3457,9 +3525,9 @@ MODULE__CTYPES_DEPS=$(srcdir)/Modules/_ctypes/ctypes.h
MODULE__CTYPES_TEST_DEPS=$(srcdir)/Modules/_ctypes/_ctypes_test_generated.c.h
MODULE__CTYPES_MALLOC_CLOSURE=@MODULE__CTYPES_MALLOC_CLOSURE@
MODULE__ELEMENTTREE_DEPS=$(srcdir)/Modules/pyexpat.c @LIBEXPAT_INTERNAL@
-MODULE__HASHLIB_DEPS=$(srcdir)/Modules/hashlib.h
+MODULE__HASHLIB_DEPS=$(srcdir)/Modules/hashlib.h $(srcdir)/Modules/_openssl_mem.h
MODULE__IO_DEPS=$(srcdir)/Modules/_io/_iomodule.h
-MODULE__REMOTE_DEBUGGING_DEPS=$(srcdir)/Modules/_remote_debugging/_remote_debugging.h $(srcdir)/Modules/_remote_debugging/gc_stats.h
+MODULE__REMOTE_DEBUGGING_DEPS=$(srcdir)/Modules/_remote_debugging/_remote_debugging.h $(srcdir)/Modules/_remote_debugging/binary_io.h $(srcdir)/Modules/_remote_debugging/gc_stats.h
# HACL*-based cryptographic primitives
MODULE__MD5_DEPS=$(srcdir)/Modules/hashlib.h $(LIBHACL_MD5_HEADERS) $(LIBHACL_MD5_LIB_@LIBHACL_LDEPS_LIBTYPE@)
@@ -3476,10 +3544,10 @@ MODULE__HMAC_DEPS=$(srcdir)/Modules/hashlib.h $(LIBHACL_HMAC_HEADERS) $(LIBHACL_
MODULE__HMAC_LDEPS=$(LIBHACL_HMAC_LIB_@LIBHACL_LDEPS_LIBTYPE@)
MODULE__SOCKET_DEPS=$(srcdir)/Modules/socketmodule.h $(srcdir)/Modules/addrinfo.h $(srcdir)/Modules/getaddrinfo.c $(srcdir)/Modules/getnameinfo.c
-MODULE__SSL_DEPS=$(srcdir)/Modules/_ssl.h $(srcdir)/Modules/_ssl/cert.c $(srcdir)/Modules/_ssl/debughelpers.c $(srcdir)/Modules/_ssl/misc.c $(srcdir)/Modules/_ssl_data_111.h $(srcdir)/Modules/_ssl_data_300.h $(srcdir)/Modules/socketmodule.h
+MODULE__SSL_DEPS=$(srcdir)/Modules/_ssl.h $(srcdir)/Modules/_openssl_mem.h $(srcdir)/Modules/_ssl/cert.c $(srcdir)/Modules/_ssl/debughelpers.c $(srcdir)/Modules/_ssl/misc.c $(srcdir)/Modules/_ssl/distrusted_spki.h $(srcdir)/Modules/_ssl_data_111.h $(srcdir)/Modules/_ssl_data_300.h $(srcdir)/Modules/socketmodule.h
MODULE__TESTCAPI_DEPS=$(srcdir)/Modules/_testcapi/parts.h $(srcdir)/Modules/_testcapi/util.h
MODULE__TESTLIMITEDCAPI_DEPS=$(srcdir)/Modules/_testlimitedcapi/testcapi_long.h $(srcdir)/Modules/_testlimitedcapi/parts.h $(srcdir)/Modules/_testlimitedcapi/util.h
-MODULE__TESTINTERNALCAPI_DEPS=$(srcdir)/Modules/_testinternalcapi/parts.h $(srcdir)/Python/ceval.h $(srcdir)/Modules/_testinternalcapi/test_targets.h $(srcdir)/Modules/_testinternalcapi/test_cases.c.h
+MODULE__TESTINTERNALCAPI_DEPS=$(srcdir)/Modules/_testinternalcapi/parts.h $(srcdir)/Parser/tokenizer/source.h $(srcdir)/Parser/tokenizer/types.h $(srcdir)/Python/ceval.h $(srcdir)/Modules/_testinternalcapi/test_targets.h $(srcdir)/Modules/_testinternalcapi/test_cases.c.h
MODULE__SQLITE3_DEPS=$(srcdir)/Modules/_sqlite/connection.h $(srcdir)/Modules/_sqlite/cursor.h $(srcdir)/Modules/_sqlite/microprotocols.h $(srcdir)/Modules/_sqlite/module.h $(srcdir)/Modules/_sqlite/prepare_protocol.h $(srcdir)/Modules/_sqlite/row.h $(srcdir)/Modules/_sqlite/util.h
MODULE__ZSTD_DEPS=$(srcdir)/Modules/_zstd/_zstdmodule.h $(srcdir)/Modules/_zstd/buffer.h $(srcdir)/Modules/_zstd/zstddict.h
diff --git a/Misc/ACKS b/Misc/ACKS
index fec00c1b272f4ea..c3ecfc1e315a595 100644
--- a/Misc/ACKS
+++ b/Misc/ACKS
@@ -117,6 +117,7 @@ Cesar Eduardo Barros
Des Barry
Emanuel Barry
Ulf Bartelt
+Tim Bartlett
Campbell Barton
Don Bashford
Pior Bastida
@@ -426,6 +427,7 @@ Hauke Dämpfling
Evan Dandrea
Eric Daniel
Scott David Daniels
+Aaron Davidson
Derzsi Dániel
Lawrence D'Anna
Steven D'Aprano
@@ -748,6 +750,7 @@ Peter Harris
Jonathan Hartley
Travis B. Hartwell
Henrik Harutyunyan
+Ashley Harvey
Shane Harvey
Larry Hastings
Tim Hatch
@@ -882,6 +885,7 @@ Dean Inwood
Bob Ippolito
Roger Irwin
Atsuo Ishimoto
+Timofei Ivankov
Alexey Izbyshev
Kasia Jachim
Adam Jackson
@@ -1104,6 +1108,7 @@ Michael Layzell
Michael Lazar
Peter Lazorchak
Brian Leair
+Iain Learmonth
Mathieu Leduc-Hamel
Amandine Lee
Antony Lee
@@ -1141,6 +1146,7 @@ Ivan Levkivskyi
Ben Lewis
William Lewis
Akira Li
+Han Li
Jiahao Li
Robert Li
Xuanji Li
@@ -1265,6 +1271,7 @@ Rihaan Meher
Bill van Melle
Lucas Prado Melo
Ezio Melotti
+Ashwin Menon
Doug Mennella
Dimitri Merejkowsky
Brian Merrell
@@ -2043,6 +2050,7 @@ Sjoerd de Vries
Jonas Wagner
Daniel Wagner-Hall
Niki W. Waibel
+WakaTaira
Wojtek Walczak
Charles Waldman
Richard Walker
diff --git a/Misc/NEWS.d/3.14.0a6.rst b/Misc/NEWS.d/3.14.0a6.rst
index 5fb5306eeaedf56..ae3338d8337ed98 100644
--- a/Misc/NEWS.d/3.14.0a6.rst
+++ b/Misc/NEWS.d/3.14.0a6.rst
@@ -1398,11 +1398,13 @@ Python 3.18:
replace ``_PyUnicodeWriter_WriteSubstring(&writer, str, start, end)`` with
:c:func:`PyUnicodeWriter_WriteSubstring(writer, str, start, end) `.
* :c:func:`!_PyUnicodeWriter_WriteASCIIString`:
- replace ``_PyUnicodeWriter_WriteASCIIString(&writer, str)`` with
- :c:func:`PyUnicodeWriter_WriteUTF8(writer, str) `.
+ replace ``_PyUnicodeWriter_WriteASCIIString(&writer, str, size)`` with
+ :c:func:`PyUnicodeWriter_WriteUTF8(writer, str, size) `.
* :c:func:`!_PyUnicodeWriter_WriteLatin1String`:
- replace ``_PyUnicodeWriter_WriteLatin1String(&writer, str)`` with
- :c:func:`PyUnicodeWriter_WriteUTF8(writer, str) `.
+ replace ``_PyUnicodeWriter_WriteLatin1String(&writer, str, size)`` by
+ decoding the string with :c:func:`PyUnicode_DecodeLatin1`, writing the
+ result with :c:func:`PyUnicodeWriter_WriteStr`, and releasing the result
+ with :c:func:`Py_DECREF`.
* :c:func:`!_PyUnicodeWriter_Prepare`: (no replacement).
* :c:func:`!_PyUnicodeWriter_PrepareKind`: (no replacement).
diff --git a/Misc/NEWS.d/3.15.0a1.rst b/Misc/NEWS.d/3.15.0a1.rst
index c7e3a872fe72858..d71401e03472602 100644
--- a/Misc/NEWS.d/3.15.0a1.rst
+++ b/Misc/NEWS.d/3.15.0a1.rst
@@ -2768,8 +2768,8 @@ Fix the "Invalid error handling" exception in
.. nonce: Gpr2GB
.. section: Library
-+Accept leading zeros in precision and width fields for
-+:class:`~decimal.Decimal` formatting, for example ``format(Decimal(1.25),
+Accept leading zeros in precision and width fields for
+:class:`~decimal.Decimal` formatting, for example ``format(Decimal(1.25),
'.016f')``.
..
@@ -5914,8 +5914,8 @@ Exception text when trying to delete attributes of types was clarified.
.. nonce: ALByCb
.. section: C API
-Function watchers can now receive a PyFunction_PYFUNC_EVENT_MODIFY_QUALNAME
-event when a watched functions qualname is changed.
+Function watchers can now receive a PyFunction_EVENT_MODIFY_QUALNAME
+event when a watched function's qualname is changed.
..
diff --git a/Misc/NEWS.d/3.15.0b1.rst b/Misc/NEWS.d/3.15.0b1.rst
index e0fcab0eef870fc..b53733f7b5df3bb 100644
--- a/Misc/NEWS.d/3.15.0b1.rst
+++ b/Misc/NEWS.d/3.15.0b1.rst
@@ -1081,10 +1081,10 @@ Deprecate :meth:`http.cookies.Morsel.js_output` and
.. nonce: iHWO0v
.. section: Library
-Add a *canonical* keyword-only parameter to the base16, base32, base64,
-base85, ascii85, and Z85 decoders in :mod:`base64` and :mod:`binascii`. When
-true, encodings with non-zero padding bits (base16/32/64) or non-canonical
-encodings (base85/ascii85) are rejected. Single-character final groups in
+Add a *canonical* keyword-only parameter to the base32, base64, base85,
+ascii85, and Z85 decoders in :mod:`base64` and :mod:`binascii`. When true,
+encodings with non-zero padding bits (base32/64) or non-canonical encodings
+(base85/ascii85) are rejected. Single-character final groups in
:func:`binascii.a2b_ascii85` and :func:`binascii.a2b_base85` are now always
rejected as encoding violations, regardless of *canonical*; previously they
were silently ignored and produced no output bytes.
diff --git a/Misc/NEWS.d/3.16.0a1.rst b/Misc/NEWS.d/3.16.0a1.rst
new file mode 100644
index 000000000000000..158d83e6bd72b1f
--- /dev/null
+++ b/Misc/NEWS.d/3.16.0a1.rst
@@ -0,0 +1,11791 @@
+.. date: 2026-09-29-16-32-46
+.. gh-issue: 158446
+.. nonce: dToaPr
+.. release date: 2026-10-13
+.. section: Security
+
+Fix a crash or incorrect output that could occur when formatting a
+:class:`float` or :class:`complex` with a precision close to the platform's
+``INT_MAX``. :c:func:`PyOS_double_to_string` now raises :exc:`ValueError`
+for any precision of that magnitude, regardless of presentation type or
+value, as the format string parsers already did for precisions above
+``INT_MAX``.
+
+..
+
+.. date: 2026-09-23-11-34-30
+.. gh-issue: 156793
+.. nonce: zC_AjF
+.. section: Security
+
+:mod:`asyncio`: :meth:`loop.start_tls() ` and
+:meth:`loop.create_connection() ` now
+validate the *server_hostname* argument if an :class:`ssl.SSLContext` is
+passed with *check_hostname* set to ``True``.
+
+..
+
+.. date: 2026-09-16-14-05-19
+.. gh-issue: 156793
+.. nonce: Qa1T5Z
+.. section: Security
+
+:meth:`ssl.SSLContext.wrap_bio` now validates its *server_side*,
+*server_hostname* and *session* arguments similar to
+:meth:`ssl.SSLContext.wrap_socket`.
+
+In particular, a context with :attr:`~ssl.SSLContext.check_hostname` enabled
+and no *server_hostname* passed to :meth:`!wrap_bio` now raises
+:exc:`ValueError` instead of completing a handshake that verified the
+certificate chain without verifying the peer's identity, with no indication
+that the check had been skipped.
+
+..
+
+.. date: 2026-09-10-13-38-11
+.. gh-issue: 157265
+.. nonce: -vYuMp
+.. section: Security
+
+In :mod:`tarfile`, when extracting a link falls back to extracting a member
+of the archive, skip the member when the filter function returns None when
+called with the extracted member's name replaced with the link's.
+
+..
+
+.. date: 2026-08-31-16-47-33
+.. gh-issue: 157953
+.. nonce: KxCF5N
+.. section: Security
+
+Update bundled `libexpat `_ to version 2.8.5.
+
+..
+
+.. date: 2026-08-18-13-54-05
+.. gh-issue: 156002
+.. nonce: CcWXPP
+.. section: Security
+
+Bound the amount of data :mod:`zipfile` decompresses per read for members
+compressed with bzip2, LZMA, or Zstandard, matching the existing limit for
+deflate. A small archive member could previously expand into an unbounded
+allocation even when read in small chunks.
+
+..
+
+.. date: 2026-08-14-11-55-00
+.. gh-issue: 157579
+.. nonce: Kq3Vt2
+.. section: Security
+
+Fix a race condition in the cleanup of :class:`tempfile.TemporaryDirectory`.
+When working around file system permission errors, files are now removed
+relative to open directory file descriptors instead of resolving their path
+again, so that replacing a directory of the tree with a symbolic link can no
+longer make the cleanup delete files outside of the temporary directory.
+This addresses :cve:`2026-12345`.
+
+..
+
+.. date: 2026-08-13-13-08-11
+.. gh-issue: 155999
+.. nonce: Xt4rWq
+.. section: Security
+
+Fix the :mod:`tarfile` ``tar`` and ``data`` extraction filters creating
+directories outside the destination for members whose name leaves the
+destination and returns to it, such as ``../evil/../dest/sub/file``. The
+containment check used the resolved path, but intermediate directories were
+created from the name as given.
+
+..
+
+.. date: 2026-08-10-12-00-00
+.. gh-issue: 156293
+.. nonce: sNIcbk
+.. section: Security
+
+Fix a crash in :mod:`ssl` when an :attr:`~ssl.SSLContext.sni_callback`
+switches a connection to another :class:`~ssl.SSLContext` and the context
+that carries the callback is no longer referenced by the application.
+Servers that keep their ``sni_callback`` context alive (the usual case when
+it wraps the listening socket or is stored on the server object) were not
+affected. This addresses :cve:`2026-19445`.
+
+..
+
+.. date: 2026-08-06-11-43-20
+.. gh-issue: 155292
+.. nonce: j4pHBO
+.. section: Security
+
+Change the :mod:`stringprep` module and :mod:`encodings.idna` codec to not
+consider Unicode codepoint attributes beyond those defined in :rfc:`3454`.
+
+..
+
+.. date: 2026-07-31-16-20-17
+.. gh-issue: 155694
+.. nonce: SsxlKG
+.. section: Security
+
+Fix :cve:`2026-15806` by scoping :class:`~urllib.request.HTTPPasswordMgr`
+credentials to the URL scheme, preventing credentials stored for an HTTPS
+URL from being used for a matching HTTP URL, while URIs without a scheme
+continue to match any scheme.
+
+..
+
+.. date: 2026-07-04-17-00-00
+.. gh-issue: 153030
+.. nonce: RovkP6
+.. section: Security
+
+Fixed quadratic complexity in incremental parsing of long unterminated
+constructs (such as tags or comments) in :class:`html.parser.HTMLParser`,
+which could be exploited for a denial of service.
+
+..
+
+.. date: 2026-06-30-13-24-13
+.. gh-issue: 152674
+.. nonce: -2QVoL
+.. section: Security
+
+The :class:`xml.etree.ElementTree.Element` methods
+:meth:`~xml.etree.ElementTree.Element.findall`,
+:meth:`~xml.etree.ElementTree.Element.iterfind` and
+:meth:`~xml.etree.ElementTree.Element.find` avoid quadratic behavior when
+using XPath index predicates (``[1]``, ``[last()]``, ``[last()-N]``) on XML
+documents with many same-tag siblings.
+
+..
+
+.. date: 2026-06-25-20-44-20
+.. gh-issue: 152216
+.. nonce: VxiK5y
+.. section: Security
+
+Update bundled `libexpat `_ to version 2.8.2.
+
+..
+
+.. date: 2026-06-23-14-19-30
+.. gh-issue: 151987
+.. nonce: 8mNIMf
+.. section: Security
+
+The :meth:`tarfile.TarFile.extract` method now applies the given filter when
+it extracts a link target from the archive as a fallback.
+
+..
+
+.. date: 2026-06-23-13-28-16
+.. gh-issue: 151981
+.. nonce: xBHEcU
+.. section: Security
+
+In :mod:`tarfile`, seeking a stream now stops when end of the stream is
+reached.
+
+..
+
+.. date: 2026-06-16-14-58-02
+.. gh-issue: 151544
+.. nonce: _bexVy
+.. section: Security
+
+:file:`Modules/Setup.local` is no longer used as a landmark to discover
+whether Python is running in a source tree, as it could potentially affect
+actual installs. The :file:`pybuilddir.txt` file is now the sole indicator
+of running in a source tree.
+
+..
+
+.. date: 2026-06-10-13-08-19
+.. gh-issue: 151558
+.. nonce: mL74i2
+.. section: Security
+
+Fixed an vulnerability in the :mod:`tarfile` ``data`` and ``tar`` extraction
+filters where crafted archives could create a symlink pointing outside the
+destination directory. This was a bypass of :cve:`2025-4330`.
+
+..
+
+.. date: 2026-05-30-09-36-20
+.. gh-issue: 150599
+.. nonce: nlHqU-
+.. section: Security
+
+Fix a possible stack buffer overflow in :mod:`bz2` when a
+:class:`bz2.BZ2Decompressor` is reused after a decompression error. The
+decompressor now becomes unusable after libbz2 reports an error.
+
+..
+
+.. date: 2026-05-30-00-00-00
+.. gh-issue: 150743
+.. nonce: httpdos
+.. section: Security
+
+:mod:`http.client` now limits the number of chunked-response trailer lines
+it will read to :attr:`~http.client.HTTPConnection.max_response_headers`
+(100 by default), and the number of interim (1xx) responses it will skip to
+100. A malicious or broken server could previously stream trailer lines or
+``100 Continue`` responses forever, hanging the client even when a socket
+timeout was in use. Reported by ``@YLChen-007`` via GHSA-w4q2-g22w-6fr4.
+
+..
+
+.. date: 2026-05-18-17-46-00
+.. gh-issue: 149835
+.. nonce: EebFlk
+.. section: Security
+
+:func:`shutil.move` now resolves symlinks via :func:`os.path.realpath` when
+checking whether the destination is inside the source directory, preventing
+a symlink-based bypass of that guard.
+
+..
+
+.. date: 2026-05-11-21-15-07
+.. gh-issue: 149698
+.. nonce: OudOcW
+.. section: Security
+
+Update bundled `libexpat `_ to version 2.8.1
+for the fix for :cve:`2026-45186`.
+
+..
+
+.. date: 2026-05-10-18-05-32
+.. gh-issue: 87451
+.. nonce: XkKB6M
+.. section: Security
+
+The :mod:`ftplib` module's undocumented ``ftpcp`` function no longer trusts
+the IPv4 address value returned from the source server in response to the
+``PASV`` command by default, completing the fix for CVE-2021-4189. As with
+:class:`ftplib.FTP`, the former behavior can be re-enabled by setting the
+``trust_server_pasv_ipv4_address`` attribute on the source
+:class:`ftplib.FTP` instance to ``True``. Thanks to Qi Deng at Aurascape AI
+for the report.
+
+..
+
+.. date: 2026-05-08-02-18-54
+.. gh-issue: 149474
+.. nonce: ujQ-mu
+.. section: Security
+
+Fix the binary writer in :mod:`profiling.sampling` not firing the audit
+(:pep:`578`) when creating the output file. The writer and the reader now
+accept any path-like object. Patch by Maurycy Pawłowski-Wieroński.
+
+..
+
+.. date: 2026-05-03-21-00-00
+.. gh-issue: 149486
+.. nonce: tarflt
+.. section: Security
+
+:func:`tarfile.data_filter` now validates link targets using the same
+normalised value that is written to disk, strips trailing separators from
+the member name when resolving a symlink's directory, and rejects link
+members that would replace the destination directory itself. This closes
+several path-traversal bypasses of the ``data`` extraction filter.
+
+..
+
+.. date: 2026-04-27-16-36-11
+.. gh-issue: 149079
+.. nonce: vKl-LM
+.. section: Security
+
+Fix a potential denial of service in :func:`unicodedata.normalize`. The
+canonical ordering step of Unicode normalization used a quadratic-time
+insertion sort for reordering combining characters, which could be exploited
+with crafted input containing many combining characters in non-canonical
+order. Replaced with a linear-time counting sort for long runs.
+
+..
+
+.. date: 2026-04-26-19-30-45
+.. gh-issue: 149018
+.. nonce: a9SqWb
+.. section: Security
+
+Improved protection against XML hash-flooding attacks in
+:mod:`xml.parsers.expat` and :mod:`xml.etree.ElementTree` when Python is
+compiled with libExpat 2.8.0 or later.
+
+..
+
+.. date: 2026-01-16-11-58-19
+.. gh-issue: 143927
+.. nonce: aviFeG
+.. section: Security
+
+Normalize all line endings (CR, CRLF, and LF) to LF+TAB when writing
+multi-line configparser values.
+
+..
+
+.. date: 2026-10-12-23-32-50
+.. gh-issue: 159285
+.. nonce: nlLuwQ
+.. section: Core and Builtins
+
+Fix a crash in a debug build when copying an empty :class:`dict` fails with
+:exc:`MemoryError`. Patch by Christian Aurich Zanettini Martins.
+
+..
+
+.. date: 2026-10-11-01-41-31
+.. gh-issue: 129724
+.. nonce: Kq3vTz
+.. section: Core and Builtins
+
+Fix the output of :mod:`marshal` for compiled code, and so the content of
+``.pyc`` files, varying with what was imported or compiled earlier in the
+process. Strings in :class:`slice` constants made only of ASCII letters,
+digits and underscores are now interned in the default build, like those of
+other constants.
+
+..
+
+.. date: 2026-10-10-23-50-00
+.. gh-issue: 159137
+.. nonce: gcWalk
+.. section: Core and Builtins
+
+Speed up the garbage collector by untracking tuples and counting the
+surviving objects while it looks for unreachable objects, which saves two
+walks of the collected generation in every collection.
+
+..
+
+.. date: 2026-10-10-00-00-00
+.. gh-issue: 159137
+.. nonce: gcReuse
+.. section: Core and Builtins
+
+Avoid a second reachability analysis in the garbage collector when no
+weakref callback, finalizer, or collectable-object debug output ran.
+Finished generators, coroutines, and async generators can skip this analysis
+even when finalized. Free-threaded builds also avoid a second stop-the-world
+pause in this case.
+
+..
+
+.. date: 2026-10-06-14-12-49
+.. gh-issue: 158918
+.. nonce: TDVkZx
+.. section: Core and Builtins
+
+Reduce C stack usage of ``_PyModule_IsPossiblyShadowing``, which could
+potentially cause stack overflows during module attribute access while
+deeply recursing in agressively optimized builds.
+
+..
+
+.. date: 2026-10-06-05-12-21
+.. gh-issue: 158803
+.. nonce: iYTpRQ
+.. section: Core and Builtins
+
+Fix a crash in :meth:`bytes.join` and :meth:`bytearray.join` in the
+:term:`free-threaded build` when another thread concurrently mutates the
+list being joined. Patch by Christian Aurich Zanettini Martins.
+
+..
+
+.. date: 2026-10-05-03-25-30
+.. gh-issue: 158824
+.. nonce: h-hJj7
+.. section: Core and Builtins
+
+Fix module-level :meth:`~module.__getattr__` being called before a module's
+own lazy imports were resolved, which allowed it to shadow them.
+
+..
+
+.. date: 2026-10-05-01-59-22
+.. gh-issue: 158820
+.. nonce: 3KLyOT
+.. section: Core and Builtins
+
+Fix a crash when a :ref:`lazy import ` is declared or resolved
+by a finalizer running during interpreter shutdown.
+
+..
+
+.. date: 2026-10-04-11-59-33
+.. gh-issue: 158592
+.. nonce: _BpoeY
+.. section: Core and Builtins
+
+Skip the array reallocation when shrinking a small :class:`list`. Patch by
+Donghee Na.
+
+..
+
+.. date: 2026-10-04-01-40-31
+.. gh-issue: 158790
+.. nonce: F3kQ7z
+.. section: Core and Builtins
+
+Speed up :meth:`list.insert` and item deletion via :keyword:`del` in
+free-threaded builds by using :manpage:`memmove(3)`.
+
+..
+
+.. date: 2026-10-03-19-11-03
+.. gh-issue: 130706
+.. nonce: 01-O6U
+.. section: Core and Builtins
+
+Add a fast path to ``_Py_Dealloc()`` for non-GC objects. Patch by Donghee
+Na.
+
+..
+
+.. date: 2026-10-03-16-14-26
+.. gh-issue: 158583
+.. nonce: 7EUMvS
+.. section: Core and Builtins
+
+:meth:`bytes.fromhex` and :meth:`bytearray.fromhex`: Fix uninitialized
+memory read. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-10-02-16-19-35
+.. gh-issue: 158592
+.. nonce: V6W21J
+.. section: Core and Builtins
+
+``del list[index]`` now triggers shrinking the list's internal array.
+
+..
+
+.. date: 2026-10-01-20-00-00
+.. gh-issue: 158140
+.. nonce: small
+.. section: Core and Builtins
+
+Resolve lazily imported sibling submodules independently, so accessing one
+does not import another merely because its declaration came last.
+
+..
+
+.. date: 2026-09-30-10-12-41
+.. gh-issue: 158316
+.. nonce: Yv3kQe
+.. section: Core and Builtins
+
+On Free Threading, speed up :meth:`bytearray.decode` by decoding the
+underlying storage directly instead of going through the buffer protocol.
+
+..
+
+.. date: 2026-09-30-01-30-58
+.. gh-issue: 158486
+.. nonce: cqmMwv
+.. section: Core and Builtins
+
+Fix the PowerSort mask calculation in :meth:`list.sort` for very large
+lists.
+
+..
+
+.. date: 2026-09-29-07-28-20
+.. gh-issue: 158380
+.. nonce: F0J0PO
+.. section: Core and Builtins
+
+Fix incorrect type guards for ``dict`` reads and writes in the experimental
+JIT.
+
+..
+
+.. date: 2026-09-28-18-58-27
+.. gh-issue: 158364
+.. nonce: jBqmTs
+.. section: Core and Builtins
+
+Fix crash when :func:`sys._current_frames` or
+:func:`sys._current_exceptions` is called while another interpreter is
+running.
+
+..
+
+.. date: 2026-09-28-11-52-49
+.. gh-issue: 158219
+.. nonce: tNjBVV
+.. section: Core and Builtins
+
+Fix :class:`bytearray` constructor: do not use a bytes object if its hash
+value is already computed. Patch by Cody Maloney and Victor Stinner.
+
+..
+
+.. date: 2026-09-26-23-44-44
+.. gh-issue: 158241
+.. nonce: NZ9OSU
+.. section: Core and Builtins
+
+Fix a crash and possible code object corruption following a
+:exc:`MemoryError` while compiling Python code.
+
+..
+
+.. date: 2026-09-26-15-39-32
+.. gh-issue: 158254
+.. nonce: qT7vRk
+.. section: Core and Builtins
+
+Reverse iterators over a :class:`dict` and its views now raise
+:exc:`RuntimeError` if the dictionary's keys change during iteration, like
+forward iterators, instead of yielding entries for the new keys.
+
+..
+
+.. date: 2026-09-25-22-34-50
+.. gh-issue: 158165
+.. nonce: GVPxKy
+.. section: Core and Builtins
+
+Fix compilation of ``_Py_get_machine_stack_pointer()`` with MinGW on
+Windows. Patch by Donghee Na.
+
+..
+
+.. date: 2026-09-24-18-44-40
+.. gh-issue: 158072
+.. nonce: mHveWw
+.. section: Core and Builtins
+
+Fix a JIT crash when a class is instantiated with their default arguments
+
+..
+
+.. date: 2026-09-24-18-20-00
+.. gh-issue: 153569
+.. nonce: diagnostics
+.. section: Core and Builtins
+
+Correct missing-brace error messages for multiline f-strings and t-strings.
+Improve tokenization of UTF-8 input split across many readline calls.
+Preserve source order when reading files with stateful encodings. Preserve
+input errors when scanning string literals.
+
+..
+
+.. date: 2026-09-24-17-30-48
+.. gh-issue: 157914
+.. nonce: 5fVJob
+.. section: Core and Builtins
+
+Revert :gh:`146064`. The linked PyMutex change was causing a significant
+performance regression in some cases.
+
+..
+
+.. date: 2026-09-22-12-00-00
+.. gh-issue: 157838
+.. nonce: brcMrg
+.. section: Core and Builtins
+
+Merge biased reference counts on behalf of threads that are detached instead
+of waiting for them to attach again, in the free-threaded build.
+
+..
+
+.. date: 2026-09-20-12-11-01
+.. gh-issue: 157840
+.. nonce: EAo1Kp
+.. section: Core and Builtins
+
+Speed up calls to :func:`hasattr` and three-argument :func:`getattr` for
+unassigned attributes in an object's :attr:`~object.__slots__` by roughly
+6x.
+
+..
+
+.. date: 2026-09-20-08-59-48
+.. gh-issue: 157833
+.. nonce: 3b0bac
+.. section: Core and Builtins
+
+Fix call specialization for C functions and methods with ``METH_CLASS``,
+``METH_STATIC``, or ``METH_COEXIST`` flags, improving their call
+performance.
+
+..
+
+.. date: 2026-09-19-12-00-00
+.. gh-issue: 157778
+.. nonce: fstring-brace
+.. section: Core and Builtins
+
+Include the line number of the opening brace in the :exc:`SyntaxError` for
+an unclosed f-string or t-string replacement field when a matching quote on
+a later line is interpreted as the start of an unterminated string.
+
+..
+
+.. date: 2026-09-18-20-24-43
+.. gh-issue: 157468
+.. nonce: zVIAva
+.. section: Core and Builtins
+
+Fix the JIT optimizer folding a builtin name to a constant taken from the
+interpreter's builtins dictionary even when the running function uses a
+different ``__builtins__`` mapping, such as one created with
+``vars(builtins).copy()``. The optimizer now only folds when the function's
+builtins is the interpreter's, and the folded constant is guarded at runtime
+so that another function sharing the same code object but a different
+builtins mapping does not use it.
+
+..
+
+.. date: 2026-09-18-15-20-00
+.. gh-issue: 157757
+.. nonce: Kq3Lm7
+.. section: Core and Builtins
+
+Fix a lazy ``import a.b as c`` reading ``b`` off ``a`` instead of importing
+the module ``a.b``. It now binds the submodule, and raises
+:exc:`ModuleNotFoundError` when no module backs the name.
+
+..
+
+.. date: 2026-09-16-15-02-11
+.. gh-issue: 155695
+.. nonce: Kf3xQa
+.. section: Core and Builtins
+
+Resolved names are now removed from :data:`sys.lazy_modules` more
+consistently: a lazy import of an already loaded module is no longer
+recorded, and reifying ``lazy from pkg import attr`` now discards the
+``pkg.attr`` entry.
+
+..
+
+.. date: 2026-09-15-17-04-54
+.. gh-issue: 155742
+.. nonce: 2DUW_9
+.. section: Core and Builtins
+
+In debug mode at Python exit, check if immutable singleton objects have been
+modified by mistake to detect bugs in C extensions. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-09-14-23-16-26
+.. gh-issue: 156939
+.. nonce: oZqlSt
+.. section: Core and Builtins
+
+When Python is built in debug mode, :class:`bytes` and :class:`bytearray`
+destructors now check if the trailing null byte has been overridden to
+detect buffer overflow. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-09-13-21-00-00
+.. gh-issue: 153568
+.. nonce: prefix-cache
+.. section: Core and Builtins
+
+Speed up parsing by reusing memoized rule prefixes across consecutive
+grammar alternatives, avoiding repeated rule calls and cache lookups.
+
+..
+
+.. date: 2026-09-13-17-00-00
+.. gh-issue: 153568
+.. nonce: target-grammar
+.. section: Core and Builtins
+
+Speed up parsing by sharing expression rules with assignment and deletion
+targets, and simplify comparison and keyword argument rules.
+
+..
+
+.. date: 2026-09-13-12-46-10
+.. gh-issue: 157378
+.. nonce: Rg7Tq2
+.. section: Core and Builtins
+
+Fix ``SyntaxError.offset`` and ``SyntaxError.end_offset`` for the "Non-UTF-8
+code starting with ..." error when a non-ASCII character precedes the
+invalid byte on the same line. Patch by Shamil Abdulaev.
+
+..
+
+.. date: 2026-09-13-10-43-24
+.. gh-issue: 156762
+.. nonce: Kbf2mo
+.. section: Core and Builtins
+
+Fix undefined behaviour in :class:`operator.methodcaller`: its
+:c:member:`~PyTypeObject.tp_clear` slot function returned ``void`` instead
+of ``int``, so the garbage collector called it through an incompatible
+function type. Patched by Shamil Abdulaev.
+
+..
+
+.. date: 2026-09-12-22-29-51
+.. gh-issue: 157377
+.. nonce: O6WYlM
+.. section: Core and Builtins
+
+Fix :func:`gc.get_count` on the free-threaded build resetting the
+thread-local allocation counter that schedules automatic garbage collection.
+A thread that called it while allocating could prevent cyclic garbage from
+ever being collected.
+
+..
+
+.. date: 2026-09-12-16-40-00
+.. gh-issue: 157361
+.. nonce: anextpy
+.. section: Core and Builtins
+
+Implement :func:`anext` in Python instead of C, in a frozen ``_pybuiltins``
+module. The awaitable returned by ``anext(it, default)`` is now a plain
+coroutine, so introspection tools such as :func:`asyncio.print_call_graph`
+can see through it into :meth:`~object.__anext__`.
+
+..
+
+.. date: 2026-09-12-12-00-00
+.. gh-issue: 153568
+.. nonce: parser
+.. section: Core and Builtins
+
+Reduce temporary allocations while parsing Python source.
+
+..
+
+.. date: 2026-09-10-08-21-07
+.. gh-issue: 157247
+.. nonce: Zv4bz2
+.. section: Core and Builtins
+
+Fix :func:`sys.activate_stack_trampoline` allowing activation from a
+subinterpreter while the JIT is enabled in the main interpreter.
+
+..
+
+.. date: 2026-09-10-02-50-14
+.. gh-issue: 157242
+.. nonce: LsqOUJ
+.. section: Core and Builtins
+
+If :meth:`bytearray.resize` or :meth:`bytearray.take_bytes` fails, leave the
+:class:`bytearray` unchanged, instead of clearing it. Patch by Victor
+Stinner.
+
+..
+
+.. date: 2026-09-05-17-32-11
+.. gh-issue: 156995
+.. nonce: Tk3bYt
+.. section: Core and Builtins
+
+Fix :class:`bytearray` sharing its buffer with the single-byte
+:class:`bytes` object of the same value, so that writing to the bytearray
+modified that :class:`bytes` object. This happened with
+:meth:`bytearray.take_bytes` when exactly one byte remained, and on the
+free-threaded build when a bytearray was shrunk to one byte from another
+thread.
+
+..
+
+.. date: 2026-09-04-22-00-00
+.. gh-issue: 156910
+.. nonce: aBcD3f
+.. section: Core and Builtins
+
+Fix a deadlock in the :term:`free threaded ` build when
+setting ``__abstractmethods__`` on a type while another thread holds the
+type lock.
+
+..
+
+.. date: 2026-09-04-16-12-30
+.. gh-issue: 156942
+.. nonce: Qk7Rw2
+.. section: Core and Builtins
+
+:mod:`marshal` no longer replaces the exception raised while marshalling the
+value with a generic ``ValueError("unmarshallable object")``. Error
+messages now name the type of the unsupported object and, for the types
+supported only by newer data formats, the required version.
+
+..
+
+.. date: 2026-09-04-14-06-00
+.. gh-issue: 156091
+.. nonce: nested-comp
+.. section: Core and Builtins
+
+Fix a crash when compiling deeply nested inlined list, set, or dict
+comprehensions. A :exc:`SyntaxError` is now raised when the nesting exceeds
+the compiler's static block limit.
+
+..
+
+.. date: 2026-09-04-05-25-35
+.. gh-issue: 156865
+.. nonce: 7c5SBs
+.. section: Core and Builtins
+
+Raise :exc:`ValueError`'s for overflows, while trying to change
+:class:`memoryview` elements with ``'f'`` and ``'Zf'`` format codes. Patch
+by Sergey B Kirpichev.
+
+..
+
+.. date: 2026-09-03-15-20-00
+.. gh-issue: 156894
+.. nonce: Rt9Bx4
+.. section: Core and Builtins
+
+Fix the position of syntax errors which cover a range if the line contains
+non-ASCII characters before the error.
+
+..
+
+.. date: 2026-09-03-12-40-00
+.. gh-issue: 156886
+.. nonce: Kx7mQt
+.. section: Core and Builtins
+
+Fix :exc:`ZeroDivisionError` spuriously raised for a complex power with a
+non-zero base when the phase of the result is infinite, e.g.
+``1e300**1e308j`` or ``complex('inf')**1j``.
+
+..
+
+.. date: 2026-09-01-07-15-20
+.. gh-issue: 155525
+.. nonce: A7kP2m
+.. section: Core and Builtins
+
+Fix quadratic-time tokenization of modules containing many f-strings or
+t-strings.
+
+..
+
+.. date: 2026-08-31-10-45-11
+.. gh-issue: 156689
+.. nonce: Jq3xNv
+.. section: Core and Builtins
+
+Fix an out-of-bounds read in :func:`compile` and :func:`ast.parse` when an
+AST object is passed with ``mode='func_type'``.
+
+..
+
+.. date: 2026-08-27-13-26-50
+.. gh-issue: 156459
+.. nonce: Z8Zqik
+.. section: Core and Builtins
+
+Fix cleanup on error in ``compiler_set_qualname``. Previously it was called
+in ``_PyCompile_EnterScope``, after the scope had been entered, and this was
+not reversed in case of an error.
+
+..
+
+.. date: 2026-08-26-10-00-00
+.. gh-issue: 155725
+.. nonce: tRcMal
+.. section: Core and Builtins
+
+:mod:`tracemalloc` no longer acquires the :term:`GIL` nor creates a
+temporary thread state to trace memory allocations: traceback frames now
+store plain UTF-8 strings instead of Python str objects, and tracebacks are
+captured using the Python thread state already associated with the calling
+thread, even if it is not attached. Threads without a Python thread state
+record the traceback as ````.
+
+..
+
+.. date: 2026-08-26-01-08-38
+.. gh-issue: 156371
+.. nonce: USpwKG
+.. section: Core and Builtins
+
+Fix missing ``PyRefTracer_DESTROY`` events for trashcan deferred objects.
+Patch by Donghee Na.
+
+..
+
+.. date: 2026-08-24-12-00-00
+.. gh-issue: 156310
+.. nonce: pSqIter
+.. section: Core and Builtins
+
+Fix memory safety issues in the :func:`iter` fallback for objects that
+implement :meth:`~object.__getitem__` without :meth:`~object.__iter__`
+(``PySeqIter_Type``). Sharing an iterator between threads in the
+free-threaded build could use the underlying sequence after it was freed,
+and re-entrant exhaustion in the default build could decrement the
+sequence's reference count twice. Concurrent iteration may still see
+duplicate or missing items, but it no longer corrupts the interpreter state.
+
+..
+
+.. date: 2026-08-23-21-30-00
+.. gh-issue: 64862
+.. nonce: Kx7Qm2
+.. section: Core and Builtins
+
+The :func:`iter` function now accepts the *stop_exception* parameter. The
+created iterator stops when the callable raises the specified exception. The
+second parameter is now named *stop_value* and can be passed by keyword.
+:func:`aiter` now accepts the same *stop_value* and *stop_exception*
+parameters, calling an asynchronous callable and awaiting the result.
+
+..
+
+.. date: 2026-08-23-12-00-00
+.. gh-issue: 156114
+.. nonce: Kq7fXz
+.. section: Core and Builtins
+
+Fix a crash in the perf trampoline when a code object has a name or filename
+that cannot be encoded to UTF-8. Patched by Shamil Abdulaev.
+
+..
+
+.. date: 2026-08-21-18-49-12
+.. gh-issue: 156204
+.. nonce: ZusA7e
+.. section: Core and Builtins
+
+Fix a crash in :c:func:`PyErr_GivenExceptionMatches` when evaluating deeply
+nested exception tuples. The recursion is now bounded, and exceeding the
+limit is reported as an unraisable exception.
+
+..
+
+.. date: 2026-08-21-14-38-06
+.. gh-issue: 148750
+.. nonce: xBijjR
+.. section: Core and Builtins
+
+:mod:`encodings` is no longer frozen, due to issues importing submodules
+when using a zipped standard library.
+
+..
+
+.. date: 2026-08-20-22-13-20
+.. gh-issue: 156126
+.. nonce: pXm4Qr
+.. section: Core and Builtins
+
+Fix a crash when importing a module whose name contains characters that
+cannot be encoded to UTF-8 (such as lone surrogates) while :option:`-X
+importtime <-X>` is enabled.
+
+..
+
+.. date: 2026-08-19-06-43-54
+.. gh-issue: 144446
+.. nonce: k3QzXa
+.. section: Core and Builtins
+
+Fix thread safety of the :attr:`!generator.gi_frame`,
+:attr:`!coroutine.cr_frame` and :attr:`!agen.ag_frame` attributes in the
+free-threading build.
+
+..
+
+.. date: 2026-08-18-18-13-47
+.. gh-issue: 156021
+.. nonce: 3mK5c5
+.. section: Core and Builtins
+
+Empty :mod:`AST ` node representations no longer include ``...`` when
+the recursion depth limit is exceeded, making them easier to distinguish
+from non-empty ones. Patch by Bartosz Sławecki.
+
+..
+
+.. date: 2026-08-18-14-19-51
+.. gh-issue: 155254
+.. nonce: 75TMlb
+.. section: Core and Builtins
+
+Avoid warning about missing standard library when using
+:ref:`sys-path-init-_pth-files`.
+
+..
+
+.. date: 2026-08-17-15-13-14
+.. gh-issue: 155978
+.. nonce: 4ztALD
+.. section: Core and Builtins
+
+Fix a memory leak in the free-threaded build when setting or deleting a
+special method (such as ``__repr__``) on a class that has many subclasses.
+
+..
+
+.. date: 2026-08-16-19-33-01
+.. gh-issue: 148653
+.. nonce: Kt3vQx
+.. section: Core and Builtins
+
+Forbid :mod:`marshalling ` recursive tuples, and fix a crash when
+unmarshalling a self-referencing tuple.
+
+..
+
+.. date: 2026-08-15-20-31-20
+.. gh-issue: 155823
+.. nonce: OhNmzi
+.. section: Core and Builtins
+
+Fix a JIT bug where the side exit taken when a virtual iterator is exhausted
+left a stale value on the stack, so the tier one interpreter resumed with
+corrupted state and ``yield from`` raised :exc:`AttributeError` instead of
+finishing normally.
+
+..
+
+.. date: 2026-08-14-19-00-00
+.. gh-issue: 155141
+.. nonce: call-kw
+.. section: Core and Builtins
+
+Compile pure-keyword calls with 16 to 29 keyword arguments using the faster
+``CALL_KW`` instruction. This includes common cases such as dataclass
+constructors with many fields.
+
+..
+
+.. date: 2026-08-13-13-50-00
+.. gh-issue: 155752
+.. nonce: Rp7K2x
+.. section: Core and Builtins
+
+Fix a crash when a :class:`types.GenericAlias` argument gains a
+``__typing_subst__`` hook after the alias parameters have been cached.
+
+..
+
+.. date: 2026-08-11-13-50-35
+.. gh-issue: 155504
+.. nonce: PsTqZm
+.. section: Core and Builtins
+
+Fix a crash when thread state creation fails before the thread state is
+fully initialized.
+
+..
+
+.. date: 2026-08-11-06-04-26
+.. gh-issue: 155526
+.. nonce: W7ZHXu
+.. section: Core and Builtins
+
+Fix spurious :exc:`OverflowError` for ``abs(nanj)`` in case :c:data:`errno`
+was previously set to :c:macro:`!ERANGE` by some library call. Patch by
+Sergey B Kirpichev.
+
+..
+
+.. date: 2026-08-11-01-45-24
+.. gh-issue: 129752
+.. nonce: Zo3OUx
+.. section: Core and Builtins
+
+Don't update adaptive counters in the free-threaded build when thread-local
+bytecode is disabled (``-X tlbc=0``). Patch by Donghee Na.
+
+..
+
+.. date: 2026-08-10-11-20-00
+.. gh-issue: 155515
+.. nonce: Lp3qWc
+.. section: Core and Builtins
+
+Track the internal HAMT iterators, which back iteration over a
+:class:`contextvars.Context`, with the garbage collector. A reference cycle
+running through such an iterator was never collected, leaking the whole
+context it iterated over.
+
+..
+
+.. date: 2026-08-07-18-32-15
+.. gh-issue: 155400
+.. nonce: Kq3Vpt
+.. section: Core and Builtins
+
+Fix a deadlock in the free-threaded build between two threads assigning to a
+special method of the same class. While applying the type slot updates with
+the world stopped, only the type lock was prevented from being released; the
+type dict mutex could still be released and re-acquired, in the wrong order,
+if the thread blocked on the stop-the-world mutex.
+
+..
+
+.. date: 2026-08-07-14-45-02
+.. gh-issue: 155315
+.. nonce: Mk9Fd2
+.. section: Core and Builtins
+
+Fix :mod:`marshal` so that a ``frozendict`` referenced more than once in the
+serialized data round-trips correctly, instead of failing to load with
+:exc:`ValueError`. Patch by tonghuaroot.
+
+..
+
+.. date: 2026-08-07-13-40-12
+.. gh-issue: 155363
+.. nonce: Qk3Vt9
+.. section: Core and Builtins
+
+Fix a leak in the :term:`free-threaded build` when creating a thread state
+fails after an internal QSBR slot has been reserved for it. The slot could
+never be reclaimed, so the QSBR array grew without bound across repeated
+failures.
+
+..
+
+.. date: 2026-08-07-10-14-56
+.. gh-issue: 154701
+.. nonce: zulh2S
+.. section: Core and Builtins
+
+Fix an infinite loop in JIT when a ``FOR_ITER`` side exit links an executor
+back to itself.
+
+..
+
+.. date: 2026-08-02-17-55-29
+.. gh-issue: 154937
+.. nonce: m9IBba
+.. section: Core and Builtins
+
+Fix a data race on thread handle identifiers when ``_thread._shutdown()``
+runs concurrently with the startup of non-daemon threads in the
+:term:`free-threaded build`.
+
+..
+
+.. date: 2026-08-01-18-04-11
+.. gh-issue: 120321
+.. nonce: k3XvQb
+.. section: Core and Builtins
+
+Fix thread safety of :term:`asynchronous generators ` when iterated, closed or thrown into concurrently from multiple
+threads on the :term:`free threading` build. Also make an ``athrow()``
+awaitable single-use: reusing it after completion now raises
+:exc:`RuntimeError` instead of resuming the generator again.
+
+..
+
+.. date: 2026-08-01-15-07-10
+.. gh-issue: 154902
+.. nonce: DIi6sf
+.. section: Core and Builtins
+
+Fix a crash when ``__conditional_annotations__`` is rebound to a non-set
+object.
+
+..
+
+.. date: 2026-07-29-08-43-14
+.. gh-issue: 151464
+.. nonce: o_mtmz
+.. section: Core and Builtins
+
+Exclude invalid token ``<>`` from :mod:`tokenize` output. :exc:`SyntaxError`
+for ``<>`` now suggests ``!=``.
+
+..
+
+.. date: 2026-07-28-10-00-00
+.. gh-issue: 133931
+.. nonce: fnQzxD
+.. section: Core and Builtins
+
+Fix data races when setting attributes of function objects on the
+:term:`free threaded ` build.
+
+..
+
+.. date: 2026-07-27-17-20-49
+.. gh-issue: 154719
+.. nonce: eI88Gs
+.. section: Core and Builtins
+
+Trailing whitespace in a t-string interpolation expression is now preserved
+in :attr:`string.templatelib.Interpolation.expression`, up to the closing
+``}`` or the conversion (``!``), format (``:``), or debug (``=``) delimiter.
+Explicit line continuations following a debug ``=`` remain part of the debug
+text and are excluded from
+:attr:`~string.templatelib.Interpolation.expression`.
+
+..
+
+.. date: 2026-07-27-16-29-10
+.. gh-issue: 154775
+.. nonce: _ISRIk
+.. section: Core and Builtins
+
+When matching a complex literal in :keyword:`case` statements, an extraneous
+``+`` sign (for example, ``1++1j`` or ``1-+1j``) is no longer allowed.
+
+..
+
+.. date: 2026-07-26-09-07-41
+.. gh-issue: 154709
+.. nonce: M2uZ76
+.. section: Core and Builtins
+
+Fix an out-of-bounds access in reverse dictionary iterators when the
+underlying dictionary is cleared and modified after the iterator is created.
+
+..
+
+.. date: 2026-07-25-17-35-14
+.. gh-issue: 154695
+.. nonce: aQWLLv
+.. section: Core and Builtins
+
+Fix :class:`asyncio.Task` raising :exc:`AttributeError` when created with
+``eager_start=True`` and no explicit *loop* argument.
+
+..
+
+.. date: 2026-07-25-12-44-13
+.. gh-issue: 154044
+.. nonce: GBa2wP
+.. section: Core and Builtins
+
+Fix a data race on a descriptor's ``__qualname__`` cache in the
+:term:`free-threaded build`.
+
+..
+
+.. date: 2026-07-25-12-43-42
+.. gh-issue: 154196
+.. nonce: 0rAdob
+.. section: Core and Builtins
+
+Improve :exc:`AttributeError` messages from unresolved lazy imports. Patch
+by Bartosz Sławecki.
+
+..
+
+.. date: 2026-07-24-13-15-31
+.. gh-issue: 153809
+.. nonce: JFA6GT
+.. section: Core and Builtins
+
+Fix interpreter crash while deallocating objects of :class:`asyncio.Task` on
+free-threaded builds. Contributed by Sergey Miryanov.
+
+..
+
+.. date: 2026-07-22-14-30-00
+.. gh-issue: 154429
+.. nonce: Qk9mZ2
+.. section: Core and Builtins
+
+Slightly speed up deallocation of objects that are not tracked by the
+garbage collector, such as :class:`int`, :class:`float` and :class:`str`.
+
+..
+
+.. date: 2026-07-21-14-38-49
+.. gh-issue: 145868
+.. nonce: 7iGRvU
+.. section: Core and Builtins
+
+Suggest the closest valid feature name in the :exc:`SyntaxError` message
+when an unknown name is imported from :mod:`__future__`.
+
+..
+
+.. date: 2026-07-20-20-16-08
+.. gh-issue: 154275
+.. nonce: l961cA
+.. section: Core and Builtins
+
+Fix a crash when getting deeply nested ``__parameters__`` from a
+:class:`types.GenericAlias` objects.
+
+..
+
+.. date: 2026-07-19-19-14-39
+.. gh-issue: 154043
+.. nonce: Kych7F
+.. section: Core and Builtins
+
+Fix a data race when iterating a shared :class:`types.GenericAlias` iterator
+from multiple threads under the :term:`free-threaded build`.
+
+..
+
+.. date: 2026-07-19-16-18-25
+.. gh-issue: 154014
+.. nonce: CJsjVL
+.. section: Core and Builtins
+
+Fix a JIT assertion during interpreter shutdown by initializing ``vm_data``
+fields for cold executors that bypass ``_Py_ExecutorInit()``.
+
+..
+
+.. date: 2026-07-19-12-33-27
+.. gh-issue: 153932
+.. nonce: lKw2bo
+.. section: Core and Builtins
+
+Fix thread safety issue in the ``__reduce__`` method of
+:py:class:`enumerate`.
+
+..
+
+.. date: 2026-07-17-22-03-39
+.. gh-issue: 153881
+.. nonce: oDa06s
+.. section: Core and Builtins
+
+Fix potential data race when calling :meth:`~object.__getstate__` under the
+:term:`free-threaded build`.
+
+..
+
+.. date: 2026-07-16-02-50-01
+.. gh-issue: 153785
+.. nonce: fJqPKC
+.. section: Core and Builtins
+
+:exc:`AttributeError`: The default error message is now generated from
+``name`` and ``obj`` attributes when both are set and the exception was
+constructed with no positional arguments, or with a single positional
+argument equal to ``name``. Patch by Bartosz Sławecki.
+
+..
+
+.. date: 2026-07-14-20-19-48
+.. gh-issue: 152075
+.. nonce: V9Rwhp
+.. section: Core and Builtins
+
+Reduced lock contention during LOAD_GLOBAL bytecode specialization under
+free threading.
+
+..
+
+.. date: 2026-07-13-13-05-00
+.. gh-issue: 78959
+.. nonce: Xy4a2B
+.. section: Core and Builtins
+
+Add the *order* parameter to :meth:`memoryview.cast`. With ``order='F'`` it
+creates a zero-copy Fortran-contiguous (column-major) view of a flat buffer,
+mirroring the *order* argument of :meth:`memoryview.tobytes`.
+
+..
+
+.. date: 2026-07-11-16-53-21
+.. gh-issue: 153568
+.. nonce: newlines
+.. section: Core and Builtins
+
+Speed up the tokenizer by copying source text verbatim when it contains no
+carriage returns.
+
+..
+
+.. date: 2026-07-11-15-45-00
+.. gh-issue: 153578
+.. nonce: Qm4Zt9
+.. section: Core and Builtins
+
+Fix an out-of-bounds write in :meth:`bytearray.extend` when the bytearray is
+resized while the argument's :meth:`~object.__buffer__` is being acquired,
+for example by another thread. Patch by tonghuaroot.
+
+..
+
+.. date: 2026-07-11-15-30-00
+.. gh-issue: 153570
+.. nonce: Kb7Xd2
+.. section: Core and Builtins
+
+Fix a use-after-free in :meth:`bytearray.take_bytes` when the argument's
+:meth:`~object.__index__` method resizes the bytearray. Patch by
+tonghuaroot.
+
+..
+
+.. date: 2026-07-11-15-07-49
+.. gh-issue: 153568
+.. nonce: identcache
+.. section: Core and Builtins
+
+Speed up the parser by caching repeated identifiers during a parse.
+
+..
+
+.. date: 2026-07-11-15-01-45
+.. gh-issue: 153568
+.. nonce: toktext
+.. section: Core and Builtins
+
+Speed up the parser by not materializing the text of tokens whose text is
+never read.
+
+..
+
+.. date: 2026-07-11-14-59-17
+.. gh-issue: 153568
+.. nonce: leftrec
+.. section: Core and Builtins
+
+Speed up parsing of left-recursive rules by updating their memoization
+entries in place.
+
+..
+
+.. date: 2026-07-11-14-58-24
+.. gh-issue: 153568
+.. nonce: stackchk
+.. section: Core and Builtins
+
+Speed up the parser by turning its per-rule C-stack check into a single
+inline comparison.
+
+..
+
+.. date: 2026-07-11-14-57-19
+.. gh-issue: 153568
+.. nonce: memoflt
+.. section: Core and Builtins
+
+Speed up the parser by letting memoization lookups that cannot match return
+immediately.
+
+..
+
+.. date: 2026-07-11-01-17-57
+.. gh-issue: 153419
+.. nonce: U8HJOJ
+.. section: Core and Builtins
+
+Fix multiple :class:`bytearray` crashes and reference leaks caused by
+skipping :meth:`~object.__init__` and broken state setup code.
+
+..
+
+.. date: 2026-07-09-13-28-27
+.. gh-issue: 153354
+.. nonce: It4Jj_
+.. section: Core and Builtins
+
+Fix a crash in compiler-generated ``__annotate__`` functions when the
+annotation format comparison returned a non-boolean result.
+
+..
+
+.. date: 2026-07-08-13-23-11
+.. gh-issue: 153298
+.. nonce: wvcXxN
+.. section: Core and Builtins
+
+Fixes a data race in :class:`types.GenericAlias` ``__parameters__``
+initialization on free-threading builds.
+
+..
+
+.. date: 2026-07-07-04-16-48
+.. gh-issue: 153205
+.. nonce: 5fE8QZ
+.. section: Core and Builtins
+
+Fix a potential :exc:`SystemError` during vector calls when memory
+allocation fails. A :exc:`MemoryError` is now raised instead.
+
+..
+
+.. date: 2026-07-06-18-00-00
+.. gh-issue: 153171
+.. nonce: errloc1
+.. section: Core and Builtins
+
+Improve syntax error messages for misplaced ``not`` after an operator in
+contexts where a generic "invalid syntax" error was previously reported,
+such as ``1 << 2 + not x`` and ``1 * + not x``.
+
+..
+
+.. date: 2026-07-06-16-30-00
+.. gh-issue: 153236
+.. nonce: lazy-import-errors
+.. section: Core and Builtins
+
+Propagate exceptions raised while importing lazy submodules instead of
+reporting them as missing attributes.
+
+..
+
+.. date: 2026-07-01-12-00-00
+.. gh-issue: 102960
+.. nonce: fR8kJa
+.. section: Core and Builtins
+
+:ref:`Frame objects ` now support :mod:`weak references
+`. Patch by Łukasz Langa.
+
+..
+
+.. date: 2026-06-30-14-50-00
+.. gh-issue: 152708
+.. nonce: aBcDeF
+.. section: Core and Builtins
+
+Fix AST generation asymmetry where unary positive ``+`` was implicitly
+dropped in pattern match expressions, restoring parsing parity with unary
+negative ``-``.
+
+..
+
+.. date: 2026-06-30-14-00-00
+.. gh-issue: 152682
+.. nonce: yId7e5
+.. section: Core and Builtins
+
+Fix NULL pointer dereference in :func:`compile` when a reserved name (e.g.
+``__classdict__``) is used as a type parameter name and memory allocation
+fails while formatting the error message.
+
+..
+
+.. date: 2026-06-29-23-29-14
+.. gh-issue: 152635
+.. nonce: O21J0O
+.. section: Core and Builtins
+
+Fix a crash caused when running out of memory creating a
+:mod:`!_interpchannels` channel. Now a :exc:`MemoryError` is correctly
+raised.
+
+..
+
+.. date: 2026-06-28-14-39-05
+.. gh-issue: 152405
+.. nonce: -_3YRo
+.. section: Core and Builtins
+
+Do not expose the internal mapping of :class:`types.MappingProxyType` when
+performing rich-compare operations with non-stdlib types. Previously, it was
+possible to mutate the internal mapping of a proxy there. Now we pass not
+the original :class:`dict` instance, but its copy, when dealing with custom
+types.
+
+..
+
+.. date: 2026-06-28-14-31-03
+.. gh-issue: 152492
+.. nonce: _09Zee
+.. section: Core and Builtins
+
+:type:`collections.OrderedDict` ``update`` method can now accept
+:type:`frozendict` as an argument.
+
+..
+
+.. date: 2026-06-27-10-05-12
+.. gh-issue: 152375
+.. nonce: L-ZBk6
+.. section: Core and Builtins
+
+Fix undefined behaviour when a :mod:`sys.monitoring` callback raised an
+exception while the program was following a branch or loop.
+
+..
+
+.. date: 2026-06-26-22-38-21
+.. gh-issue: 152192
+.. nonce: lX2jIM
+.. section: Core and Builtins
+
+Fix a truncated ``oparg`` being passed to JIT trace initialization for a
+``JUMP_BACKWARD`` with an ``EXTENDED_ARG``.
+
+..
+
+.. date: 2026-06-26-22-03-16
+.. gh-issue: 152235
+.. nonce: ZKWiWk
+.. section: Core and Builtins
+
+Defer GC tracking of :meth:`set.intersection`, :meth:`set.difference`,
+:meth:`set.symmetric_difference`, :meth:`set.union` and ``set.__sub__``.
+Patch by Donghee Na.
+
+..
+
+.. date: 2026-06-26-20-37-22
+.. gh-issue: 152315
+.. nonce: iVS7u5
+.. section: Core and Builtins
+
+:exc:`TypeError` messages for some instance methods called with too many
+positional arguments now suggest checking whether the method definition is
+missing the ``self`` parameter.
+
+..
+
+.. date: 2026-06-26-05-49-13
+.. gh-issue: 152235
+.. nonce: YU20T9
+.. section: Core and Builtins
+
+Defer GC tracking of a :class:`set` or :class:`frozenset` to the end of its
+construction from iterable. Patch by Donghee Na.
+
+..
+
+.. date: 2026-06-25-21-34-15
+.. gh-issue: 152228
+.. nonce: a6K14K
+.. section: Core and Builtins
+
+Fix an assertion failure when python is built in a debug mode that happened
+in :meth:`str.replace` under a limited memory situation.
+
+..
+
+.. date: 2026-06-24-14-05-00
+.. gh-issue: 152107
+.. nonce: K3jX9p
+.. section: Core and Builtins
+
+Fix a crash when creating a :class:`dict` item iterator (for example
+``iter(d.items())`` or ``reversed(d.items())``) under a memory-allocation
+failure. Patch by Jiucheng Zang.
+
+..
+
+.. date: 2026-06-24-13-36-31
+.. gh-issue: 151722
+.. nonce: lWKfE1
+.. section: Core and Builtins
+
+:meth:`!frozendict.fromkeys` now only tracks the :class:`frozendict` in the
+garbage collector once the dictionary is fully initialized. Patch by Donghee
+Na and Victor Stinner.
+
+..
+
+.. date: 2026-06-23-23-48-54
+.. gh-issue: 151763
+.. nonce: Eu8pYQ
+.. section: Core and Builtins
+
+Fixes possible crash on :class:`types.CodeType` deallocation.
+
+..
+
+.. date: 2026-06-23-19-50-22
+.. gh-issue: 152020
+.. nonce: DTKXjR
+.. section: Core and Builtins
+
+On the free-threaded build, :func:`asyncio.all_tasks` no longer loses
+eager-started tasks when called from a thread other than the one running the
+event loop.
+
+..
+
+.. date: 2026-06-23-12-03-55
+.. gh-issue: 151763
+.. nonce: K7QfWG
+.. section: Core and Builtins
+
+Fix a potential crash in :func:`compile`, :func:`exec`, :func:`eval` and
+:func:`ast.parse` when an allocation fails: the parser or compiler could
+return without setting an exception.
+
+..
+
+.. date: 2026-06-22-14-48-22
+.. gh-issue: 151912
+.. nonce: YcxfnU
+.. section: Core and Builtins
+
+Fixed a crash in ``type()`` when selecting a metaclass whose ``tp_new`` slot
+is ``NULL``. Such metaclasses are now rejected with ``TypeError`` instead of
+causing a NULL pointer dereference.
+
+..
+
+.. date: 2026-06-22-11-05-56
+.. gh-issue: 151895
+.. nonce: QQsjUQ
+.. section: Core and Builtins
+
+Fixed a crash in :func:`marshal.loads` when an allocation failed while
+loading a reference-tracked dictionary; it now raises :exc:`MemoryError`.
+
+..
+
+.. date: 2026-06-22-06-26-34
+.. gh-issue: 151905
+.. nonce: FOLMYg
+.. section: Core and Builtins
+
+Fix OOM error handling in :c:func:`PyFrame_GetBack` to propagate exceptions
+instead of masking them as None.
+
+..
+
+.. date: 2026-06-22-02-42-38
+.. gh-issue: 151907
+.. nonce: 6Tol_J
+.. section: Core and Builtins
+
+Avoid creating :class:`list` objects in comprehensions when the
+comprehension is not used as a value.
+
+..
+
+.. date: 2026-06-21-16-00-00
+.. gh-issue: 151773
+.. nonce: mN4kRt
+.. section: Core and Builtins
+
+Fix a crash in :func:`contextvars.ContextVar.set` when memory allocation
+fails.
+
+..
+
+.. date: 2026-06-21-12-55-18
+.. gh-issue: 151665
+.. nonce: 82fmzx
+.. section: Core and Builtins
+
+:func:`inspect.signature` now works on the lazy evaluators of type aliases
+and type parameters instead of raising :exc:`ValueError`.
+
+..
+
+.. date: 2026-06-20-10-01-26
+.. gh-issue: 151672
+.. nonce: K-w7j0
+.. section: Core and Builtins
+
+Fix an inconsistency where calling ``__lazy_import__`` with a string
+``fromlist`` would return a :class:`types.LazyImportType` that resolves to
+the named member, rather than the module being imported.
+
+..
+
+.. date: 2026-06-20-00-30-47
+.. gh-issue: 151722
+.. nonce: RPMPIY
+.. section: Core and Builtins
+
+Defer GC tracking of :class:`frozendict` to end of construction. Patch by
+Donghee Na.
+
+..
+
+.. date: 2026-06-19-16-40-01
+.. gh-issue: 151619
+.. nonce: 35yyJW
+.. section: Core and Builtins
+
+Fix an issue where using non-module global or builtin namespaces (such as
+dictionaries passed to :func:`exec`) could cause cached global loads to
+produce unresolved :ref:`lazy imports `.
+
+..
+
+.. date: 2026-06-19-12-00-00
+.. gh-issue: 151646
+.. nonce: Gc5tAt
+.. section: Core and Builtins
+
+Fix a data race in free-threading builds between :func:`gc.get_stats` and a
+concurrent garbage collection cycle. Access to the per-generation
+statistics is now serialized with a mutex so the reader observes a
+consistent snapshot.
+
+..
+
+.. date: 2026-06-18-16-00-10
+.. gh-issue: 151126
+.. nonce: tBqn6I
+.. section: Core and Builtins
+
+Fix a crash when sharing :class:`memoryview` objects between interpreters
+fails due to running out of memory. It now raises a proper
+:exc:`MemoryError`.
+
+..
+
+.. date: 2026-06-18-00-00-00
+.. gh-issue: 151644
+.. nonce: 5cFffN
+.. section: Core and Builtins
+
+Fix a data race in :func:`sys.setdlopenflags` and :func:`sys.getdlopenflags`
+when called concurrently in the free-threaded build. The underlying
+``_PyImport_GetDLOpenFlags`` and ``_PyImport_SetDLOpenFlags`` functions now
+use atomic load/store operations.
+
+..
+
+.. date: 2026-06-17-16-46-07
+.. gh-issue: 151126
+.. nonce: vhTL0T
+.. section: Core and Builtins
+
+Avoid possible crash in ``_winapi.c`` where a device has no memory left. Now
+it properly raises a :exc:`MemoryError`. Patch by Ivy Xu.
+
+..
+
+.. date: 2026-06-17-16-26-45
+.. gh-issue: 151126
+.. nonce: Yc_6wC
+.. section: Core and Builtins
+
+Avoid possible crash in ``getpath.c`` where a device has no memory left. Now
+it properly raises a :exc:`MemoryError`. Patch by Ivy Xu.
+
+..
+
+.. date: 2026-06-16-19-20-00
+.. gh-issue: 151518
+.. nonce: e6v0Js
+.. section: Core and Builtins
+
+Fix a free-threaded stop-the-world fairness issue that could starve a thread
+reattaching after being suspended while detached.
+
+..
+
+.. date: 2026-06-16-17-23-37
+.. gh-issue: 151546
+.. nonce: LhiaZz
+.. section: Core and Builtins
+
+Fix the stack limit check if Python is linked to musl (ex: Alpine Linux).
+Use the stack size set by the linker to compute the stack limits. Patch by
+Victor Stinner.
+
+..
+
+.. date: 2026-06-16-00-45-42
+.. gh-issue: 151510
+.. nonce: HJ-kGn
+.. section: Core and Builtins
+
+Fix a crash in :func:`!__lazy_import__` when called without an explicit
+``globals`` argument and without a current Python frame.
+
+..
+
+.. date: 2026-06-14-05-05-15
+.. gh-issue: 151461
+.. nonce: 5q0s88
+.. section: Core and Builtins
+
+Fix direct execution of files with invalid source encodings to report the
+underlying codec lookup or decoding error instead of the generic
+``SyntaxError: encoding problem`` message. Patch by Bartosz Sławecki.
+
+..
+
+.. date: 2026-06-12-17-15-53
+.. gh-issue: 151377
+.. nonce: bQSQUk
+.. section: Core and Builtins
+
+Fix races in free-threaded builds when updating type slots for newly created
+classes and when removing entries from a base type's subclasses dictionary.
+
+..
+
+.. date: 2026-06-12-15-30-25
+.. gh-issue: 151218
+.. nonce: 5M_nv8
+.. section: Core and Builtins
+
+:c:func:`PyConfig_Set` and :func:`sys.set_int_max_str_digits` now replace
+:data:`sys.flags` (create a new object), instead of modifying
+:data:`sys.flags` in-place. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-06-11-16-03-23
+.. gh-issue: 151297
+.. nonce: NGPkUM
+.. section: Core and Builtins
+
+Fix an invalid pointer dereference that could occur when calling
+:c:func:`PyObject_Realloc` with a NULL pointer in :term:`free-threaded
+builds ` or with :envvar:`PYTHONMALLOC` set to
+``mimalloc``.
+
+..
+
+.. date: 2026-06-10-15-42-46
+.. gh-issue: 151253
+.. nonce: 7MMQ8P
+.. section: Core and Builtins
+
+If ``import encodings`` (first import) fails at Python startup, dump the
+Python path configuration to help users debugging their configuration. Patch
+by Victor Stinner.
+
+..
+
+.. date: 2026-06-10-15-19-58
+.. gh-issue: 151238
+.. nonce: C9Wu4x
+.. section: Core and Builtins
+
+Fix a crash when compiling a concatenated f-string or t-string if an error
+occurs when processing one of it's parts.
+
+..
+
+.. date: 2026-06-09-12-24-35
+.. gh-issue: 151112
+.. nonce: 4RKCkD
+.. section: Core and Builtins
+
+Fix a crash in the compiler that could occur when running out of memory.
+
+..
+
+.. date: 2026-06-09-10-28-30
+.. gh-issue: 151126
+.. nonce: DKa6Sl
+.. section: Core and Builtins
+
+Fix a crash, when there's no memory left on a device, which happened in:
+code compilation, :mod:`!_interpchannels` module,
+:func:`!_winapi.CreateProcess` function.
+
+Now these places raise proper :exc:`MemoryError` errors.
+
+..
+
+.. date: 2026-06-08-13-14-42
+.. gh-issue: 150902
+.. nonce: -CWZ66
+.. section: Core and Builtins
+
+Apply an existing optimization of PyCriticalSection (single mutex) to
+PyCriticalSection2: avoid acquiring the same locks that the current CS has
+already acquired.
+
+..
+
+.. date: 2026-06-08-05-31-22
+.. gh-issue: 151065
+.. nonce: _o_31F
+.. section: Core and Builtins
+
+Fix memory leak when using the :ref:`mimalloc memory allocator `.
+
+..
+
+.. date: 2026-06-06-20-15-08
+.. gh-issue: 151029
+.. nonce: A33CKK
+.. section: Core and Builtins
+
+On Linux, fix :func:`sys.remote_exec` unable to find remote writable memory
+when ``libpython`` replaced on disk.
+
+..
+
+.. date: 2026-06-06-08-20-00
+.. gh-issue: 150942
+.. nonce: Jk9pQr
+.. section: Core and Builtins
+
+Speed up frame local variable item collection by appending result pairs to
+the output list without an extra reference-count round-trip (using the
+internal reference-stealing list append helper). Patch by Omkar Kabde.
+
+..
+
+.. date: 2026-06-05-22-52-41
+.. gh-issue: 150988
+.. nonce: fDKfMJ
+.. section: Core and Builtins
+
+Fix a reference leak in :exc:`OSError` when attributes are set before
+``super().__init__()``.
+
+..
+
+.. date: 2026-06-05-09-25-08
+.. gh-issue: 145685
+.. nonce: afO33b
+.. section: Core and Builtins
+
+The internal method cache used for types is now a per-type cache instead of
+a global per-interpreter one, improving performance and reducing cache
+misses. Patch by Kumar Aditya.
+
+..
+
+.. date: 2026-06-04-15-02-35
+.. gh-issue: 146495
+.. nonce: wWRRvx
+.. section: Core and Builtins
+
+Improve :exc:`SyntaxError` message for ``&&`` and ``||`` operators,
+suggesting ``and``/``&`` and ``or``/``|`` respectively.
+
+..
+
+.. date: 2026-06-04-12-53-10
+.. gh-issue: 148874
+.. nonce: r121cG
+.. section: Core and Builtins
+
+Ignore interrupts immediately after calling the ``__enter__`` method of a
+context menager in a ``with`` statement. This ensures that the ``__exit__``
+method is always called in a ``with`` statement.
+
+..
+
+.. date: 2026-06-03-21-14-28
+.. gh-issue: 150459
+.. nonce: qpsCEl
+.. section: Core and Builtins
+
+Fix :exc:`SyntaxError` error message for ``from x lazy import y``. Raise
+:exc:`SyntaxWarning` on ``from . lazy import x`` (with whitespace between
+the dots and a module named ``lazy``).
+
+..
+
+.. date: 2026-06-03-16-27-00
+.. gh-issue: 150858
+.. nonce: j2dSkD
+.. section: Core and Builtins
+
+Fix a data race while changing ``__qualname__`` of a type concurrently on
+free-threaded builds.
+
+..
+
+.. date: 2026-06-02-16-21-02
+.. gh-issue: 150737
+.. nonce: LoYUFY
+.. section: Core and Builtins
+
+Optimize bytecode for empty unpack cases such as ``{*()}``.
+
+..
+
+.. date: 2026-06-01-19-24-12
+.. gh-issue: 150723
+.. nonce: WlcL_-
+.. section: Core and Builtins
+
+Fix perf jitdump timestamps on macOS. Events were stamped using
+``CLOCK_MONOTONIC``, but macOS profilers timestamp their samples with
+``mach_absolute_time()``. The mismatch prevented the JIT code mappings from
+lining up with the samples, so no Python frame could be resolved.
+
+..
+
+.. date: 2026-06-01-19-21-01
+.. gh-issue: 150723
+.. nonce: Hb3JDG
+.. section: Core and Builtins
+
+Fix malformed perf jitdump thread ids on macOS. The ``thread_id`` field of
+the ``JR_CODE_LOAD`` record was written as a 64-bit value instead of the
+32-bit value required by the jitdump format, which shifted every following
+field and prevented profilers from resolving Python frames.
+
+..
+
+.. date: 2026-06-01-19-00-00
+.. gh-issue: 150700
+.. nonce: W8CzVR
+.. section: Core and Builtins
+
+Fix a :exc:`SystemError` when compiling a class-scope comprehension
+containing a ``lambda`` that references ``__class__``, ``__classdict__``, or
+``__conditional_annotations__``. Patch by Bartosz Sławecki.
+
+..
+
+.. date: 2026-05-30-20-19-35
+.. gh-issue: 150633
+.. nonce: XkNul0
+.. section: Core and Builtins
+
+Fix the frozen importer accepting module names with embedded null bytes,
+which caused it to bypass the :data:`sys.modules` cache and create duplicate
+module objects.
+
+..
+
+.. date: 2026-05-29-17-51-11
+.. gh-issue: 144774
+.. nonce: jPcixe
+.. section: Core and Builtins
+
+Fix data race in :class:`BaseException` when an exception is copied while
+being mutated.
+
+..
+
+.. date: 2026-05-26-00-06-30
+.. gh-issue: 150411
+.. nonce: u-d-_5
+.. section: Core and Builtins
+
+Fix a data race in the free-threaded build when :func:`gc.get_count` reads
+the young generation allocation count while another thread updates it.
+
+..
+
+.. date: 2026-05-25-16-00-22
+.. gh-issue: 150374
+.. nonce: Emu6d8
+.. section: Core and Builtins
+
+Fix double release of the import lock on lazy import reification errors.
+
+..
+
+.. date: 2026-05-24-22-46-49
+.. gh-issue: 148613
+.. nonce: PLpmyd
+.. section: Core and Builtins
+
+Fix a data race in the free-threaded build between :func:`gc.set_threshold`
+and garbage collection scheduling during object allocation.
+
+..
+
+.. date: 2026-05-24-14-45-00
+.. gh-issue: 149156
+.. nonce: NP73rB
+.. section: Core and Builtins
+
+Fix an intermittent crash after :func:`os.fork` when perf trampoline
+profiling is enabled and the child returns through trampoline frames
+inherited from the parent process.
+
+..
+
+.. date: 2026-05-23-22-08-01
+.. gh-issue: 149449
+.. nonce: 2lhQFF
+.. section: Core and Builtins
+
+Fix a use-after-free crash when the :mod:`unicodedata` module was removed
+from :data:`sys.modules` and garbage-collected between calls that decode
+``\N{...}`` escapes or use the ``namereplace`` codec error handler.
+
+..
+
+.. date: 2026-05-22-21-52-38
+.. gh-issue: 150207
+.. nonce: l2BUtI
+.. section: Core and Builtins
+
+Fix a crash when a memory allocation fails during tokenizer initialization.
+A proper :exc:`MemoryError` is now raised instead.
+
+..
+
+.. date: 2026-05-22-17-10-29
+.. gh-issue: 149816
+.. nonce: u1-iqT
+.. section: Core and Builtins
+
+Fix a Use-After-Free race condition in ``subtype_getweakref()`` during
+concurrent weakref creation and destruction in the free-threading build.
+
+..
+
+.. date: 2026-05-22-17-09-28
+.. gh-issue: 150107
+.. nonce: GD72-D
+.. section: Core and Builtins
+
+:mod:`asyncio`: ``sendfile()`` and ``sock_sendfile()`` event loop methods
+now call ``file.seek(offset)`` if *file* has a ``seek()`` method, even if
+*offset* is ``0`` (default value).
+
+..
+
+.. date: 2026-05-21-21-04-43
+.. gh-issue: 150208
+.. nonce: VOkxRG
+.. section: Core and Builtins
+
+Avoid double-quoting string values from ``pyconfig.h`` in ``sysconfigdata``
+variables.
+
+..
+
+.. date: 2026-05-20-13-06-17
+.. gh-issue: 150146
+.. nonce: i5m_SL
+.. section: Core and Builtins
+
+Fix a crash on a complex type variable substitution.
+
+``from typing import TypeVar; memoryview[TypeVar("")][*typing.Mapping[...,
+...]]`` used to fail due to missing ``NULL`` check on ``_unpack_args`` C
+function call.
+
+..
+
+.. date: 2026-05-18-18-36-28
+.. gh-issue: 148587
+.. nonce: -RD3z5
+.. section: Core and Builtins
+
+:py:attr:`sys.lazy_modules` is now a set instead of a dict as initially
+spelled out in PEP 810.
+
+..
+
+.. date: 2026-05-18-17-16-51
+.. gh-issue: 150027
+.. nonce: sJgLvd
+.. section: Core and Builtins
+
+Improve performance of :class:`frozenset` objects by avoiding copies during
+construction.
+
+..
+
+.. date: 2026-05-18-16-54-54
+.. gh-issue: 150042
+.. nonce: LSr5W8
+.. section: Core and Builtins
+
+Fix refleak in queue.SimpleQueue.put if memory allocation fails.
+
+..
+
+.. date: 2026-05-18-13-47-17
+.. gh-issue: 149590
+.. nonce: IPBeQx
+.. section: Core and Builtins
+
+Fix crash when faulthandler is imported more than once.
+
+..
+
+.. date: 2026-05-18-12-32-33
+.. gh-issue: 149816
+.. nonce: v18Ypf
+.. section: Core and Builtins
+
+Fix race conditions in ``invoke_gc_callback`` iterating ``gc.callbacks`` in
+free-threading mode.
+
+..
+
+.. date: 2026-05-17-12-00-00
+.. gh-issue: 138325
+.. nonce: h2XSfe
+.. section: Core and Builtins
+
+Speed up converting a list to a tuple in the ``tuple(genexpr)`` fast path
+and in starred tuple displays (e.g. ``(*a, *b)``) by stealing the list's
+items into the tuple instead of copying them.
+
+..
+
+.. date: 2026-05-16-11-03-54
+.. gh-issue: 149816
+.. nonce: X_gqMT
+.. section: Core and Builtins
+
+Fix a race condition in ``_PyBytes_FromList`` in free-threading mode.
+
+..
+
+.. date: 2026-05-15-20-13-41
+.. gh-issue: 157407
+.. nonce: 4Lso8S
+.. section: Core and Builtins
+
+Argument Clinic now parses arguments of positional-only methods with a
+*defining class* directly, without a :c:type:`!_PyArg_Parser`.
+
+..
+
+.. date: 2026-05-15-11-31-57
+.. gh-issue: 149816
+.. nonce: ugN2rx
+.. section: Core and Builtins
+
+Fix a race condition in :class:`memoryview` with free-threading.
+
+..
+
+.. date: 2026-05-14-19-41-03
+.. gh-issue: 149807
+.. nonce: IwGaCo
+.. section: Core and Builtins
+
+Fix ``hash(frozendict)``: compute the hash of each ``(key, value)`` pair
+correctly. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-05-13-21-26-26
+.. gh-issue: 149805
+.. nonce: IG6cza
+.. section: Core and Builtins
+
+Fix a :exc:`SystemError` when compiling a compiling ``__classdict__`` class
+annotation. Found by OSS-Fuzz in :oss-fuzz:`512907042`.
+
+..
+
+.. date: 2026-05-13-06-54-41
+.. gh-issue: 149738
+.. nonce: 4BLFoH
+.. section: Core and Builtins
+
+:mod:`sqlite3`: Disallow removing ``row_factory`` and ``text_factory``
+attributes of a connection or cursor to prevent a crash on a query.
+
+..
+
+.. date: 2026-05-12-16-47-23
+.. gh-issue: 139808
+.. nonce: iIs7_E
+.. section: Core and Builtins
+
+Add branch protections for AArch64 (BTI/PAC) in assembly code used by
+:option:`-X perf_jit <-X>` (Linux perf profiler integration).
+
+..
+
+.. date: 2026-05-12-12-49-30
+.. gh-issue: 127727
+.. nonce: hNmj9G
+.. section: Core and Builtins
+
+Warn when running a virtual environment created for a different minor Python
+version than the current interpreter, and suggest using ``python -m venv
+--upgrade``.
+
+..
+
+.. date: 2026-05-11-18-20-41
+.. gh-issue: 148871
+.. nonce: AeCbq7
+.. section: Core and Builtins
+
+The empty tuple ``()`` is now loaded via :opcode:`LOAD_COMMON_CONSTANT`
+instead of :opcode:`LOAD_CONST`, removing it from per-code-object
+:attr:`~codeobject.co_consts` tuples.
+
+..
+
+.. date: 2026-05-11-15-58-23
+.. gh-issue: 149689
+.. nonce: 9Ht49z
+.. section: Core and Builtins
+
+Fix missing error propagation in parser action helpers when memory
+allocation fails. Patch by Thomas Kowalski.
+
+..
+
+.. date: 2026-05-11-14-48-56
+.. gh-issue: 149676
+.. nonce: 6aTrw1
+.. section: Core and Builtins
+
+Fix ``frozendict | frozendict`` hash.
+
+..
+
+.. date: 2026-05-10-16-43-50
+.. gh-issue: 148829
+.. nonce: gscS14
+.. section: Core and Builtins
+
+:class:`sentinel` objects now support a ``repr=`` argument and their
+:attr:`~sentinel.__module__` attribute is writable.
+
+..
+
+.. date: 2026-05-10-07-42-36
+.. gh-issue: 149642
+.. nonce: 6ZksML
+.. section: Core and Builtins
+
+Allow imports inside ``exec()`` calls within functions under
+``PYTHON_LAZY_IMPORTS=all``.
+
+..
+
+.. date: 2026-05-09-15-22-32
+.. gh-issue: 144957
+.. nonce: u1F2aQ
+.. section: Core and Builtins
+
+Fix lazy ``from`` imports of module attributes provided by module-level
+``__getattr__``.
+
+..
+
+.. date: 2026-05-07-03-18-59
+.. gh-issue: 149459
+.. nonce: 5fhAqP
+.. section: Core and Builtins
+
+Fix a crash in the JIT optimizer when a specialized ``LOAD_SPECIAL`` guard
+deoptimized after inserting the synthetic ``NULL`` stack entry.
+
+..
+
+.. date: 2026-05-05-12-00-00
+.. gh-issue: 149321
+.. nonce: remove-lazy-imports-none
+.. section: Core and Builtins
+
+Do not support ``none`` as a lazy imports mode.
+
+..
+
+.. date: 2026-04-29-15-10-59
+.. gh-issue: 149162
+.. nonce: BPPyrq
+.. section: Core and Builtins
+
+Fix a potential deadlock in :c:func:`PyUnicode_InternFromString` and other
+interning functions in the :term:`free-threaded build` when called from C++
+static local initializers.
+
+..
+
+.. date: 2026-04-26-15-08-53
+.. gh-issue: 148817
+.. nonce: cuN07H
+.. section: Core and Builtins
+
+Fold large constant list and set literals used as the iterable of a
+:keyword:`for` loop or ``in``/``not in`` test into a constant :class:`tuple`
+or :class:`frozenset`, restoring an optimization previously done by the AST
+optimizer that was lost when constant folding moved to the CFG.
+
+..
+
+.. date: 2026-04-21-15-07-03
+.. gh-issue: 148825
+.. nonce: AbJzmZ
+.. section: Core and Builtins
+
+Fix build error if specialization is disabled.
+
+..
+
+.. date: 2026-04-15-15-48-04
+.. gh-issue: 148450
+.. nonce: 2MEVqH
+.. section: Core and Builtins
+
+Fix ``abc.register()`` so it invalidates type version tags for registered
+classes.
+
+..
+
+.. date: 2026-04-13-00-00-00
+.. gh-issue: 148442
+.. nonce: aBcDeF
+.. section: Core and Builtins
+
+Fix a race condition in ``list.__lt__``, ``list.__le__``, ``list.__gt__``,
+and ``list.__ge__``. Previously, under concurrent list mutation, the items
+being compared could be replaced with other objects before the final
+comparison, causing the final comparison result to be incorrect.
+
+..
+
+.. date: 2026-03-31-16-15-15
+.. gh-issue: 75723
+.. nonce: BZ4Rsn
+.. section: Core and Builtins
+
+Avoid re-executing ``.pth`` files when :func:`site.addsitedir` is called for
+a known directory.
+
+..
+
+.. date: 2026-03-23-00-45-44
+.. gh-issue: 145857
+.. nonce: dB66WV
+.. section: Core and Builtins
+
+The ``DELETE_GLOBAL`` opcode is now replaced with ``PUSH_NULL;
+STORE_GLOBAL``.
+
+..
+
+.. date: 2026-03-20-16-27-15
+.. gh-issue: 145855
+.. nonce: 3yaHO4
+.. section: Core and Builtins
+
+The ``DELETE_ATTR`` opcode is now replaced with ``PUSH_NULL; STORE_ATTR``.
+
+..
+
+.. date: 2026-03-16-02-23-48
+.. gh-issue: 145854
+.. nonce: rRexF3
+.. section: Core and Builtins
+
+The ``DELETE_NAME`` opcode is now replaced with ``PUSH_NULL; STORE_NAME``.
+
+..
+
+.. date: 2026-02-14-16-19-22
+.. gh-issue: 138912
+.. nonce: TKMC9K
+.. section: Core and Builtins
+
+Add fast path for :keyword:`match` class patterns without any sub-patterns
+to improve performance by ~15%.
+
+..
+
+.. date: 2025-08-15-06-28-45
+.. gh-issue: 91484
+.. nonce: huCgHt
+.. section: Core and Builtins
+
+:meth:`memoryview.cast` now allows casting from N-D to 1-D for F-contiguous.
+
+..
+
+.. date: 2024-12-24-08-44-49
+.. gh-issue: 128213
+.. nonce: Y71jDi
+.. section: Core and Builtins
+
+Speed up :class:`bytes` creation from :class:`list` and :class:`tuple` of
+integers.
+
+Patch by Ben Hsing and Pieter Eendebak
+
+..
+
+.. date: 2024-09-19-15-47-50
+.. gh-issue: 117999
+.. nonce: Iq4jEG
+.. section: Core and Builtins
+
+Fix calculation of powers of complex numbers. Small integer powers now
+produce correct sign of zero components. Negative powers of infinite numbers
+now evaluate to zero instead of NaN. Powers of infinite numbers no longer
+raise OverflowError.
+
+..
+
+.. date: 2020-06-23-13-59-37
+.. gh-issue: 85260
+.. nonce: o_LJ76
+.. section: Core and Builtins
+
+:func:`compile` now raises :exc:`ValueError` instead of crashing on a debug
+build if an identifier field of an AST node (such as the name of a function,
+a class, an imported module or a caught exception) is ``"None"``, ``"True"``
+or ``"False"``.
+
+..
+
+.. bpo: 38131
+.. date: 2019-12-27-19-20-33
+.. nonce: J5fv54
+.. section: Core and Builtins
+
+Produce more meaningful messages when compiling AST objects with wrong field
+values. Patch by Batuhan Taskaya.
+
+..
+
+.. date: 2026-10-11-08-41-00
+.. gh-issue: 159184
+.. nonce: Nn4tOr
+.. section: Library
+
+Fix :func:`marshal.dumps` raising :exc:`TypeError` for a set or frozenset
+containing several complex NaNs, which also made it impossible to write a
+:file:`.pyc` file for source code containing such a constant.
+
+..
+
+.. date: 2026-10-11-08-40-00
+.. gh-issue: 159185
+.. nonce: Sq7cZd
+.. section: Library
+
+Fix a crash in :func:`marshal.dumps` and :func:`marshal.dump` when a set is
+modified while its elements are serialized, for example by the
+:meth:`~object.__buffer__` method of one of its elements.
+:exc:`RuntimeError` is now raised.
+
+..
+
+.. date: 2026-10-11-06-00-00
+.. gh-issue: 129724
+.. nonce: mRsh1x
+.. section: Library
+
+Make the output of :func:`marshal.dumps` and :func:`marshal.dump`, and so
+the content of :file:`.pyc` files, independent of the reference counts of
+the serialized objects. The format is unchanged, but the data is not
+byte-for-byte identical to that written by previous Python versions.
+
+..
+
+.. date: 2026-10-08-16-18-43
+.. gh-issue: 87720
+.. nonce: Elqdl9
+.. section: Library
+
+Fixed error in :mod:`email` new policies where header folding failed to
+detect the need to re-quote text obtained from encoded words in certain
+cases.
+
+..
+
+.. date: 2026-10-07-20-32-20
+.. gh-issue: 158929
+.. nonce: 6dwqfQ
+.. section: Library
+
+Fix crash when calling :func:`syslog.syslog` while a subinterpreter in
+another thread calls :func:`syslog.openlog` or :func:`syslog.closelog`.
+
+..
+
+.. date: 2026-10-07-02-29-45
+.. gh-issue: 158897
+.. nonce: jH3FwQ
+.. section: Library
+
+Optimize :meth:`!io.BufferedReader.readline` when lines are close to the
+buffer size (128 kB by default) or longer than the buffer size. Replace the
+C loop searching for the newline byte in the buffer with a :c:func:`!memchr`
+call which is more efficient. In the good case, it makes ``readline()`` up
+to 4x faster! Patch by Victor Stinner.
+
+..
+
+.. date: 2026-10-06-20-33-52
+.. gh-issue: 158936
+.. nonce: flCm_m
+.. section: Library
+
+:func:`~dataclasses.dataclass` no longer fails when a string annotation
+names a :ref:`lazy import ` that cannot be resolved, matching
+the behavior for non-string annotations.
+
+..
+
+.. date: 2026-10-06-20-03-01
+.. gh-issue: 158893
+.. nonce: B6A53q
+.. section: Library
+
+Make :func:`os.strerror` thread-safe: use the reentrant ``strerror_r()``
+function if available. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-10-05-18-00-01
+.. gh-issue: 158539
+.. nonce: k8Lv2a
+.. section: Library
+
+Fix macOS runtime section lookup for remote debugging when virtual memory
+region sizes differ from Mach-O segment file sizes.
+
+..
+
+.. date: 2026-10-05-18-00-00
+.. gh-issue: 156545
+.. nonce: z1mQp7
+.. section: Library
+
+Fix deep flamegraph exports on platforms with small C stacks by falling back
+to the Python JSON encoder when the C encoder runs out of stack space.
+
+..
+
+.. date: 2026-10-05-13-57-08
+.. gh-issue: 79459
+.. nonce: 2RgBDL
+.. section: Library
+
+:mod:`tempfile` functions that take a ``prefix`` or ``suffix`` argument now
+raise a :exc:`ValueError` if they contain a directory component:
+:func:`tempfile.mkstemp`, :func:`tempfile.mkdtemp`,
+:func:`tempfile.TemporaryFile`, :func:`tempfile.NamedTemporaryFile`.
+
+..
+
+.. date: 2026-10-04-20-00-00
+.. gh-issue: 158552
+.. nonce: windows
+.. section: Library
+
+Wait for Windows threads to finish suspending before reading target memory
+in the sampling profiler's blocking mode. Resume the target if waiting for
+suspension fails.
+
+..
+
+.. date: 2026-10-01-16-45-00
+.. gh-issue: 156321
+.. nonce: Kq3xVt
+.. section: Library
+
+Fix :func:`asyncio.shield` reporting an exception from the inner future
+through the loop exception handler as soon as it completes after the shield
+was cancelled, even when the exception is retrieved afterwards. The
+exception is now reported only if it is never retrieved, as with any other
+future.
+
+..
+
+.. date: 2026-10-01-14-00-00
+.. gh-issue: 158539
+.. nonce: q1w2e3
+.. section: Library
+
+Fix :mod:`profiling.sampling` exception mode discarding samples for code
+running inside an ``except`` block in a generator or coroutine. The remote
+debugger now follows ``tstate->exc_info`` and its ``previous_item`` chain
+instead of only reading the embedded ``exc_state``, matching the exception
+that :func:`sys.exception` reports.
+
+..
+
+.. date: 2026-10-01-13-59-02
+.. gh-issue: 158563
+.. nonce: kR7wQe
+.. section: Library
+
+Fix :func:`turtle.undo` after :func:`turtle.teleport` and after an exception
+in :func:`turtle.circle`, :func:`turtle.dot` or :func:`turtle.write`. Fix
+:func:`turtle.stamp`, :func:`turtle.clearstamp`, :func:`turtle.clear` and
+:func:`turtle.reset` when the undo buffer is disabled.
+
+..
+
+.. date: 2026-09-30-22-10-00
+.. gh-issue: 158540
+.. nonce: kQ9vXm
+.. section: Library
+
+Fix :mod:`profiling.sampling` not adding the directory containing the
+profiled script to :data:`sys.path`, which prevented the script from
+importing modules placed next to it. The script's directory is now added,
+matching the behavior of ``python script.py``.
+
+..
+
+.. date: 2026-09-30-20-09-46
+.. gh-issue: 158522
+.. nonce: L6j7tU
+.. section: Library
+
+Fix :mod:`profiling.sampling` showing a single frame for a task whose
+coroutine recurses. Patch by Timofei Ivankov.
+
+..
+
+.. date: 2026-09-26-22-07-09
+.. gh-issue: 158237
+.. nonce: AbCdEf
+.. section: Library
+
+Fix :func:`ast.unparse` to not insert a space before attribute access on
+bool constants (e.g. ``True.real`` instead of ``True .real``).
+
+..
+
+.. date: 2026-09-25-22-15-54
+.. gh-issue: 158169
+.. nonce: ZlibTail
+.. section: Library
+
+Fix :attr:`zlib.Decompress.unconsumed_tail` duplicating
+:attr:`~zlib.Decompress.unused_data` after end of stream when *max_length*
+was used.
+
+..
+
+.. date: 2026-09-19-20-31-58
+.. gh-issue: 141540
+.. nonce: phc605
+.. section: Library
+
+Quote the unconverted data and the format in the error messages of
+:func:`time.strptime` and :meth:`datetime.datetime.strptime` so that
+whitespace such as a trailing newline is visible.
+
+..
+
+.. date: 2026-09-19-14-10-18
+.. gh-issue: 157788
+.. nonce: v70Lxd
+.. section: Library
+
+Fix ``python -m asyncio ps`` failing on a process that has a task with a
+name longer than 255 characters.
+
+..
+
+.. date: 2026-09-19-12-00-00
+.. gh-issue: 157605
+.. nonce: Qh92xZ
+.. section: Library
+
+Fix :mod:`profiling.sampling` failing when a native thread has an empty
+Python stack.
+
+..
+
+.. date: 2026-09-18-17-33-31
+.. gh-issue: 157763
+.. nonce: Wd0_Uo
+.. section: Library
+
+The undocumented :func:`!ctypes.util.test` function is now :term:`soft
+deprecated` and a no-op at runtime.
+
+..
+
+.. date: 2026-09-18-12-00-00
+.. gh-issue: 157660
+.. nonce: tlbc
+.. section: Library
+
+Fix :mod:`profiling.sampling` reporting errors or incorrect line numbers in
+free-threaded builds when a thread-local bytecode array grows or gains
+entries after being cached.
+
+..
+
+.. date: 2026-09-17-21-05-42
+.. gh-issue: 153888
+.. nonce: Ht7Yqb
+.. section: Library
+
+Fix :func:`unittest.mock.patch` with ``autospec``, ``spec``, or ``spec_set``
+when used with lazy-imported objects.
+
+..
+
+.. date: 2026-09-17-17-30-00
+.. gh-issue: 119646
+.. nonce: kP8nQm
+.. section: Library
+
+On Windows, :exc:`OSError` from :mod:`subprocess` now includes the attempted
+executable or working directory in ``filename``.
+
+..
+
+.. date: 2026-09-17-15-14-08
+.. gh-issue: 157675
+.. nonce: C4-ze9
+.. section: Library
+
+:func:`encodings.idna.nameprep` now takes a *limit* argument that allows
+rejecting extremely large input early. The ``idna`` encoding and the
+:func:`!encodings.idna.ToASCII` and :func:`!encodings.idna.ToUnicode`
+functions use this to avoid passing unbounded input to quadratic-time
+algorithms.
+
+..
+
+.. date: 2026-09-17-14-00-00
+.. gh-issue: 157672
+.. nonce: tksigs
+.. section: Library
+
+Fix :mod:`tkinter` on macOS: creating a :class:`~tkinter.Tk` instance no
+longer replaces the Python handlers of SIGINT, SIGHUP and SIGTERM with Tk's
+handler which exits the process, so Ctrl-C raises :exc:`KeyboardInterrupt`
+again.
+
+..
+
+.. date: 2026-09-17-03-20-24
+.. gh-issue: 157639
+.. nonce: VP3kc4
+.. section: Library
+
+Fix a crash in :mod:`!cProfile` when an external timer re-enters the
+profiler. Profiling events raised while the external timer runs are now
+ignored.
+
+..
+
+.. date: 2026-09-16-14-04-38
+.. gh-issue: 157621
+.. nonce: R6v2S8
+.. section: Library
+
+Fix a crash when a weak-reference callback is attached to a
+:class:`typing.ParamSpecArgs` or :class:`typing.ParamSpecKwargs` instance.
+
+..
+
+.. date: 2026-09-16-09-28-42
+.. gh-issue: 157633
+.. nonce: EvGFI0
+.. section: Library
+
+Update :mod:`unicodedata` database to Unicode 18.0.0.
+
+..
+
+.. date: 2026-09-15-16-37-19
+.. gh-issue: 69919
+.. nonce: izH1zP
+.. section: Library
+
+:meth:`code.InteractiveInterpreter.runsource` and the REPL now report any
+exception raised by compiling the source, such as :exc:`MemoryError` or
+:exc:`RecursionError` for too deeply nested source, instead of propagating
+it or printing a traceback of the REPL internals.
+
+..
+
+.. date: 2026-09-14-18-36-32
+.. gh-issue: 157514
+.. nonce: 02FZED
+.. section: Library
+
+Add constants :const:`tkinter.TCL_VERSION_INFO` and
+:const:`tkinter.TK_VERSION_INFO`, named tuples with the versions of the Tcl
+and Tk libraries that were used for building the module, and
+``_tkinter.TCL_PATCH_LEVEL`` and ``_tkinter.TK_PATCH_LEVEL`` strings.
+
+..
+
+.. date: 2026-09-14-18-36-31
+.. gh-issue: 157513
+.. nonce: EW4QOC
+.. section: Library
+
+:const:`ssl.OPENSSL_VERSION_INFO` is now a named tuple. Add
+:const:`ssl.OPENSSL_API_VERSION_INFO` which provides information about the
+version of the OpenSSL library that was used for building the module.
+
+..
+
+.. date: 2026-09-14-12-05-02
+.. gh-issue: 157487
+.. nonce: ID-qIv
+.. section: Library
+
+Add constants :const:`ctypes.LIBFFI_VERSION`,
+:const:`ctypes.libffi_version`, :const:`ctypes.LIBFFI_VERSION_INFO` and
+:const:`ctypes.libffi_version_info`, which provide information about the
+version of the libffi library in use. They are only available with libffi
+3.5 or later.
+
+..
+
+.. date: 2026-09-14-11-38-23
+.. gh-issue: 157485
+.. nonce: yAK9LN
+.. section: Library
+
+Add constants :const:`readline.READLINE_VERSION_INFO`,
+:const:`readline.readline_version_info` and
+:const:`readline.readline_version`, which provide information about the
+version of the Readline library in use.
+
+..
+
+.. date: 2026-09-14-10-39-05
+.. gh-issue: 157480
+.. nonce: to5EnW
+.. section: Library
+
+Add constants in :mod:`dbm.ndbm` which provide information about the version
+of the underlying library in use: :const:`~dbm.ndbm.GDBM_VERSION_INFO`,
+:const:`~dbm.ndbm.gdbm_version_info` and :const:`~dbm.ndbm.gdbm_version` if
+it is GDBM, or :const:`~dbm.ndbm.BDB_VERSION`,
+:const:`~dbm.ndbm.bdb_version`, :const:`~dbm.ndbm.BDB_VERSION_INFO` and
+:const:`~dbm.ndbm.bdb_version_info` if it is Berkeley DB.
+:const:`dbm.ndbm.library` is now ``'ndbm'`` instead of ``'GNU gdbm'`` for a
+classic NDBM library.
+
+..
+
+.. date: 2026-09-14-10-22-36
+.. gh-issue: 157478
+.. nonce: F4cBKN
+.. section: Library
+
+Add constants :const:`dbm.gnu.GDBM_VERSION_INFO`,
+:const:`dbm.gnu.gdbm_version_info` and :const:`dbm.gnu.gdbm_version`, which
+provide information about the version of the GDBM library in use. The
+private constant ``_gdbm._GDBM_VERSION`` has been removed.
+
+..
+
+.. date: 2026-09-14-09-28-35
+.. gh-issue: 157475
+.. nonce: dvuniU
+.. section: Library
+
+Add constants :const:`decimal.LIBMPDEC_VERSION`,
+:const:`decimal.libmpdec_version`, :const:`decimal.LIBMPDEC_VERSION_INFO`,
+and :const:`decimal.libmpdec_version_info` in the C implementation, which
+provide information about the version of the libmpdec library in use.
+
+..
+
+.. date: 2026-09-14-09-02-19
+.. gh-issue: 157473
+.. nonce: LlzPyM
+.. section: Library
+
+Add constant :const:`xml.parsers.expat.VERSION_INFO` which provides
+information about the version of the Expat library that was used for
+building the module. :const:`xml.parsers.expat.version_info` is now a named
+tuple.
+
+..
+
+.. date: 2026-09-14-07-49-51
+.. gh-issue: 157470
+.. nonce: jgEHYK
+.. section: Library
+
+Add constants :const:`sqlite3.SQLITE_VERSION` and
+:const:`sqlite3.SQLITE_VERSION_INFO` which provide information about the
+version of the SQLite library that was used for building the module.
+:const:`sqlite3.sqlite_version_info` is now a named tuple.
+
+..
+
+.. date: 2026-09-14-00-30-00
+.. gh-issue: 157451
+.. nonce: k7Qm2x
+.. section: Library
+
+Fix :mod:`gettext` plural form selection when the ``Plural-Forms``
+expression combines the unary ``!`` operator with a binary operator, for
+example ``!n + 1`` or ``2 * !n``. The latter raised :exc:`SyntaxError`.
+
+..
+
+.. date: 2026-09-13-21-45-00
+.. gh-issue: 150816
+.. nonce: pQ3kZs
+.. section: Library
+
+Speed up :func:`inspect.signature` for Python functions by skipping
+redundant validation when creating :class:`inspect.Parameter` objects.
+
+..
+
+.. date: 2026-09-13-15-58-28
+.. gh-issue: 157335
+.. nonce: efaMah
+.. section: Library
+
+Fix out-of-bounds write in ``mmap.mmap.__setitem__`` that could occur when
+converting the index or the assigned value (via :meth:`~object.__index__`
+for a single item, or via the buffer protocol for a slice) resized or closed
+the mmap object during the assignment.
+
+..
+
+.. date: 2026-09-13-10-30-00
+.. gh-issue: 157406
+.. nonce: a3kZq7
+.. section: Library
+
+Fix the Python implementation of :class:`xml.etree.ElementTree.XMLParser`:
+the ``doctype()`` method of the target is now called for a document type
+declaration without an external identifier, like ````, as in
+the C implementation.
+
+..
+
+.. date: 2026-09-13-07-14-35
+.. gh-issue: 128509
+.. nonce: 9F2GCE
+.. section: Library
+
+:func:`marshal.load` and :func:`marshal.loads` can now get 1-byte string
+singletons. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-09-12-18-03-15
+.. gh-issue: 157364
+.. nonce: Qd7mKs
+.. section: Library
+
+Fix a use-after-free in :class:`io.TextIOWrapper` when a call to the
+underlying buffer reentrantly detaches it. Patched by Shamil Abdulaev.
+
+..
+
+.. date: 2026-09-12-15-50-23
+.. gh-issue: 157366
+.. nonce: djwD2M
+.. section: Library
+
+Remove the accidental acceptance of :class:`bytes` in the C implementation
+of :mod:`xml.etree.ElementTree`, a leftover of the Python 2 to Python 3
+migration, for paths of :meth:`~xml.etree.ElementTree.Element.find` and
+similar methods, for the tag of :meth:`~xml.etree.ElementTree.Element.iter`,
+and for the names of events of :class:`~xml.etree.ElementTree.XMLPullParser`
+and :func:`~xml.etree.ElementTree.iterparse`. It now raises the same
+exceptions as the Python implementation.
+
+..
+
+.. date: 2026-09-12-03-14-57
+.. gh-issue: 157242
+.. nonce: ycbtjC
+.. section: Library
+
+:class:`io.BytesIO` is no longer closed on ``write()`` and ``truncate()``
+failure (:exc:`MemoryError`). Patch by Victor Stinner.
+
+..
+
+.. date: 2026-09-11-16-50-11
+.. gh-issue: 157325
+.. nonce: hzTild
+.. section: Library
+
+Fix an out-of-bounds read in the ``hz`` incremental decoder when the input
+ends with ``~``.
+
+..
+
+.. date: 2026-09-11-14-14-51
+.. gh-issue: 157301
+.. nonce: QxcE2r
+.. section: Library
+
+Fix :class:`asyncio.Task` hanging the event loop when an eager start fails
+to enter the task's context.
+
+..
+
+.. date: 2026-09-11-12-00-00
+.. gh-issue: 156955
+.. nonce: bLtmAp
+.. section: Library
+
+Speed up :func:`csv.writer` by caching the set of characters that need
+quoting or escaping in the dialect. Writing long fields is now up to 5 times
+faster.
+
+..
+
+.. date: 2026-09-09-13-46-38
+.. gh-issue: 157213
+.. nonce: rYg7pO
+.. section: Library
+
+Fix :func:`asyncio.gather` leaving stale await-graph edges on children that
+outlive it.
+
+..
+
+.. date: 2026-09-08-15-55-00
+.. gh-issue: 157176
+.. nonce: yZ8a1B
+.. section: Library
+
+Make the :class:`time.struct_time` type immutable to prevent reference
+cycles between the type and its instances. Patch by Shamil Abdulaev.
+
+..
+
+.. date: 2026-09-08-13-06-29
+.. gh-issue: 156002
+.. nonce: vmOC8T
+.. section: Library
+
+:mod:`zipfile` again reads members through a third-party decompressor
+installed by monkey-patching the private ``_get_decompressor()`` to return
+an object that only implements old BZ2Decompressor API from Python 3.3.
+Calling decompress() with one argument is deprecated. Note that
+decompressors without ``needs_input`` and two-argument ``decompress()`` are
+vulnerable to :cve:`2026-15310`.
+
+..
+
+.. date: 2026-09-08-09-30-00
+.. gh-issue: 157159
+.. nonce: tabNny
+.. section: Library
+
+The usage message printed by ``python -m tabnanny`` when no arguments are
+given now suggests ``python -m`` instead of the source file.
+
+..
+
+.. date: 2026-09-08-04-10-00
+.. gh-issue: 123018
+.. nonce: hV2kQe
+.. section: Library
+
+Fix :func:`readline.write_history_file` and
+:func:`readline.append_history_file` producing a history file that
+:func:`readline.read_history_file` could not load when a limit was set with
+:func:`readline.set_history_length` and Python was built against
+``libedit``. This works around `NetBSD PR 60322
+`_.
+
+..
+
+.. date: 2026-09-08-00-31-56
+.. gh-issue: 157127
+.. nonce: gduPd0
+.. section: Library
+
+Reword the :mod:`argparse` error message reported for a missing required
+mutually exclusive group to ``one of the following arguments is required:
+--foo, --bar``, so that the argument names are separated by commas.
+
+..
+
+.. date: 2026-09-07-23-40-00
+.. gh-issue: 157146
+.. nonce: lczip1
+.. section: Library
+
+:mod:`linecache` can now read the source of a module that was imported from
+a zip archive on :data:`sys.path` when given only the file name, as
+:mod:`pdb`, :mod:`warnings` and :mod:`doctest` do.
+
+..
+
+.. date: 2026-09-07-12-24-11
+.. gh-issue: 157058
+.. nonce: 2SoQU7
+.. section: Library
+
+:func:`asyncio.wait_for` with a non-positive timeout now records the waiter
+in the call graph.
+
+..
+
+.. date: 2026-09-07-00-21-31
+.. gh-issue: 156933
+.. nonce: OalCjC
+.. section: Library
+
+Fix incorrect integer return values from :mod:`ctypes` callbacks on some
+platforms, such as s390x.
+
+..
+
+.. date: 2026-09-06-15-23-24
+.. gh-issue: 157048
+.. nonce: UtFyiJ
+.. section: Library
+
+Preserve the position and contents of :class:`io.BytesIO` when
+:meth:`!BytesIO.__init__` fails because a buffer is exported.
+
+..
+
+.. date: 2026-09-06-15-12-18
+.. gh-issue: 157025
+.. nonce: ZvFpFT
+.. section: Library
+
+Fix transport cleanup when cancelling :meth:`asyncio.loop.sendfile` while
+waiting for the write buffer to drain in the native implementation.
+
+..
+
+.. date: 2026-09-05-22-39-22
+.. gh-issue: 156961
+.. nonce: ZtYqoA
+.. section: Library
+
+Fix :func:`tkinter.font.nametofont` and the :class:`tkinter.font.Font`
+constructor for a font name or description returned by Tk as a Tcl object,
+for example by :meth:`ttk.Style.lookup() `.
+
+..
+
+.. date: 2026-09-05-18-23-30
+.. gh-issue: 156988
+.. nonce: nEUQE6
+.. section: Library
+
+:func:`asyncio.print_call_graph` no longer truncates the call stack at a
+synchronous generator.
+
+..
+
+.. date: 2026-09-05-15-27-11
+.. gh-issue: 156970
+.. nonce: DxlgbB
+.. section: Library
+
+Set the docstring of :attr:`unittest.mock.Mock.return_value`.
+
+..
+
+.. date: 2026-09-04-16-05-45
+.. gh-issue: 156946
+.. nonce: 0ZYCdh
+.. section: Library
+
+Fix a crash in :mod:`curses.panel` when the finalizer of a panel's user
+pointer runs while the panel is being deallocated. The panel is now taken
+off the panel stack before its user pointer is dropped.
+
+..
+
+.. date: 2026-09-04-14-15-31
+.. gh-issue: 156924
+.. nonce: 3Ux7IJ
+.. section: Library
+
+:meth:`annotationlib.ForwardRef.evaluate` now resolves :ref:`lazy import
+` proxies found in the namespace. With
+:attr:`~annotationlib.Format.FORWARDREF`, a lazy import that fails to
+resolve now results in a :class:`~annotationlib.ForwardRef` instead of the
+:class:`lazy import proxy `, and with
+:attr:`~annotationlib.Format.VALUE` the underlying exception is propagated.
+
+..
+
+.. date: 2026-09-04-11-45-08
+.. gh-issue: 156865
+.. nonce: mrdfKJ
+.. section: Library
+
+Don't raise exceptions on overflows in :class:`ctypes.c_float_complex`.
+Patch by Sergey B Kirpichev.
+
+..
+
+.. date: 2026-09-04-09-18-05
+.. gh-issue: 156920
+.. nonce: lONsKT
+.. section: Library
+
+Fix :mod:`asyncio` on Windows: closing a :class:`~asyncio.DatagramTransport`
+under :class:`~asyncio.ProactorEventLoop` while datagrams were still queued,
+or while an in-flight write failed right as ``close()`` was draining the
+buffer, could strand the queued data and never call ``connection_lost()``,
+hanging the close indefinitely.
+
+..
+
+.. date: 2026-09-03-04-51-46
+.. gh-issue: 156864
+.. nonce: Pbe7Tl
+.. section: Library
+
+:func:`array.array` setter now correctly detects overflows for the ``'e'``,
+``'f'`` and ``'Zf'`` type codes. Patch by Sergey B Kirpichev.
+
+..
+
+.. date: 2026-09-03-04-32-06
+.. gh-issue: 156867
+.. nonce: hq3efC
+.. section: Library
+
+Raise :exc:`OverflowError`'s for native ``'Zf'`` format in
+:func:`struct.pack`, like for ``'f'`` format. Previously overflows in the
+:c:expr:`float complex` type were silent. Patch by Sergey B Kirpichev.
+
+..
+
+.. date: 2026-09-02-17-28-16
+.. gh-issue: 156810
+.. nonce: cLpEnc
+.. section: Library
+
+Fix a :exc:`UnicodeEncodeError` crash in the sampling profiler's
+collapsed-stack export (``--collapsed``) when a sampled frame's function or
+file name contains non-ASCII or surrogate-escaped characters. The output
+file is now written as UTF-8.
+
+..
+
+.. date: 2026-09-02-12-11-00
+.. gh-issue: 124697
+.. nonce: sUbScp
+.. section: Library
+
+The :mod:`symtable` module now represents inlined list, set and dict
+comprehensions (:pep:`709`) as their own symbol table entries of type
+:attr:`~symtable.SymbolTableType.INLINED_COMPREHENSION`.
+
+..
+
+.. date: 2026-09-01-16-58-30
+.. gh-issue: 156797
+.. nonce: Qm4tRs
+.. section: Library
+
+Fix :class:`xml.sax.saxutils.XMLGenerator`: the namespace URI is now escaped
+in the namespace declaration. Previously a URI containing ``&``, ``<`` or a
+quote character produced a document which cannot be parsed.
+
+..
+
+.. date: 2026-09-01-02-30-00
+.. gh-issue: 63102
+.. nonce: Pz3wK8
+.. section: Library
+
+:class:`~xml.etree.ElementTree.XMLPullParser` and
+:func:`~xml.etree.ElementTree.iterparse` now support the *target* parameter.
+The reported object is the value returned by the corresponding method of the
+target, so no tree is built if the target does not build one. Only the
+standard :class:`~xml.etree.ElementTree.TreeBuilder` was supported in the C
+implementation before.
+
+..
+
+.. date: 2026-09-01-00-30-00
+.. gh-issue: 61290
+.. nonce: Vx7pQ2
+.. section: Library
+
+:mod:`xml.etree.ElementTree` no longer refuses to serialize attributes
+without a namespace when the *default_namespace* option is used. The default
+namespace declaration does not apply to attribute names, so an unqualified
+attribute name is written as is, and a qualified attribute name is always
+written with a prefix.
+
+..
+
+.. date: 2026-08-31-23-10-00
+.. gh-issue: 83895
+.. nonce: Jm5tR3
+.. section: Library
+
+:mod:`xml.etree.ElementTree` now accepts input larger than 2 GiB in the C
+implementation. The data is fed to Expat in chunks, as
+:mod:`xml.parsers.expat` already did, instead of raising
+:exc:`OverflowError`.
+
+..
+
+.. date: 2026-08-31-20-30-00
+.. gh-issue: 99064
+.. nonce: Rt4mZ9
+.. section: Library
+
+Fix :func:`xml.etree.ElementTree.parse` with a text file or other source of
+:class:`str` data in the C implementation. The encoding declared in the
+document was applied to the already decoded text, which produced mojibake.
+It is now ignored, as when parsing with :meth:`!XMLParser.feed` or
+:func:`~xml.etree.ElementTree.fromstring`.
+
+..
+
+.. date: 2026-08-31-19-30-00
+.. gh-issue: 89499
+.. nonce: Kx8vQ1
+.. section: Library
+
+:meth:`ElementTree.write() `,
+:func:`~xml.etree.ElementTree.tostring` and
+:func:`~xml.etree.ElementTree.tostringlist` now support the *standalone*
+parameter, the value of the standalone document declaration in the XML
+declaration.
+
+..
+
+.. date: 2026-08-31-17-10-00
+.. gh-issue: 156713
+.. nonce: Nt2URL
+.. section: Library
+
+Fix :func:`!nturl2path.pathname2url` and :func:`!nturl2path.url2pathname`:
+the filesystem encoding and error handler are now used for percent-encoding
+and decoding, as in :mod:`urllib.request`. Previously paths containing
+surrogate characters raised :exc:`UnicodeEncodeError`.
+
+..
+
+.. date: 2026-08-31-11-40-00
+.. gh-issue: 156774
+.. nonce: Pd8Lz1
+.. section: Library
+
+Speed up :mod:`pdb` startup by only importing :mod:`asyncio` when the
+program being debugged has already imported it.
+
+..
+
+.. date: 2026-08-31-09-01-22
+.. gh-issue: 156439
+.. nonce: j9WHCc
+.. section: Library
+
+:func:`socket.if_nametoindex` and :func:`socket.if_indextoname` are now
+available on platforms that provide them but not ``if_nameindex``, such as
+Android before API level 24.
+
+..
+
+.. date: 2026-08-31-00-00-00
+.. gh-issue: 156698
+.. nonce: gyDxUe
+.. section: Library
+
+Fix :class:`asyncio.ProactorEventLoop` UDP transports so that a write error
+no longer strands a paused protocol: the write loop is now rescheduled when
+data remains buffered, and the protocol is resumed when the buffer has
+drained.
+
+..
+
+.. date: 2026-08-31-00-00-00
+.. gh-issue: 127057
+.. nonce: N9yg62
+.. section: Library
+
+Fix :class:`asyncio.ProactorEventLoop` UDP transports so that a
+:exc:`ConnectionResetError` raised by ``WSARecvFrom`` no longer stops the
+read loop.
+
+..
+
+.. date: 2026-08-30-21-00-00
+.. gh-issue: 156665
+.. nonce: Jm3Kp9
+.. section: Library
+
+:mod:`xml.dom.minidom` now validates namespaces in
+:meth:`~xml.dom.Document.createElementNS`,
+:meth:`~xml.dom.Document.createAttributeNS` and
+:meth:`~xml.dom.Element.setAttributeNS`, and when setting
+:attr:`~xml.dom.Node.prefix` of an attribute. :exc:`~xml.dom.NamespaceErr`
+is now raised for a malformed qualified name, for a prefix with an empty
+namespace, and for illegal use of the ``xml`` and ``xmlns`` prefixes.
+
+..
+
+.. date: 2026-08-30-19-30-00
+.. gh-issue: 156658
+.. nonce: Xq5Nt7
+.. section: Library
+
+:mod:`xml.dom` and :mod:`xml.etree.ElementTree` no longer treat characters
+which are not white space in XML (such as U+00A0) as white space. Previously
+they could be lost in :func:`~xml.etree.ElementTree.indent`,
+:func:`~xml.etree.ElementTree.canonicalize` with ``strip_text=True``, and
+when parsing with the ``whitespace-in-element-content`` feature turned off.
+
+..
+
+.. date: 2026-08-30-18-00-00
+.. gh-issue: 81623
+.. nonce: Vh2Kt6
+.. section: Library
+
+:meth:`~xml.dom.minidom.Node.toprettyxml` in :mod:`xml.dom.minidom` and
+:func:`~xml.etree.ElementTree.indent` in :mod:`xml.etree.ElementTree` no
+longer add whitespace inside an element which is marked with
+``xml:space="preserve"`` or which contains text (:meth:`!toprettyxml` also
+takes into account the content model declared in the DTD). Previously such
+indentation changed the content of the element.
+
+..
+
+.. date: 2026-08-30-13-37-47
+.. gh-issue: 54092
+.. nonce: Tq8Wm3
+.. section: Library
+
+Implement :meth:`~xml.dom.minidom.Node.writexml` for document fragments in
+:mod:`xml.dom.minidom`, so that :meth:`~xml.dom.minidom.Node.toxml` and
+:meth:`~xml.dom.minidom.Node.toprettyxml` now work for them. They write the
+children of the fragment, without adding a level of indentation.
+
+..
+
+.. date: 2026-08-30-13-25-53
+.. gh-issue: 156512
+.. nonce: tVTOIV
+.. section: Library
+
+Fix :mod:`asyncio` losing a connection twice when ``resume_writing()``
+closes the transport.
+
+..
+
+.. date: 2026-08-30-12-00-00
+.. gh-issue: 44376
+.. nonce: Kp4Vz9
+.. section: Library
+
+:meth:`~xml.dom.minidom.Node.writexml` in :mod:`xml.dom.minidom` now writes
+the namespace declarations needed to serialize the namespaces of the element
+and its attributes, if they are not already declared for an ancestor. The
+document is not modified.
+
+..
+
+.. date: 2026-08-29-11-37-40
+.. gh-issue: 156545
+.. nonce: fLaMe1
+.. section: Library
+
+Fix the sampling profiler's flamegraph export so that profiling a deeply
+recursive program no longer fails with :exc:`RecursionError` instead of
+producing a flamegraph. Patch by tonghuaroot.
+
+..
+
+.. date: 2026-08-28-18-10-25
+.. gh-issue: 156523
+.. nonce: llJqo9
+.. section: Library
+
+Fix :func:`asyncio.as_completed` not recording the awaiting task in the call
+graph.
+
+..
+
+.. date: 2026-08-28-00-59-00
+.. gh-issue: 156476
+.. nonce: rQhxc7
+.. section: Library
+
+The pure Python implementation of :meth:`queue.SimpleQueue.get` now ignores
+*timeout* when *block* is false, matching the documented behavior and the C
+implementation. It previously raised :exc:`ValueError`.
+
+..
+
+.. date: 2026-08-27-08-31-29
+.. gh-issue: 156444
+.. nonce: klcySy
+.. section: Library
+
+Fix matching of a negated character set in a bytes pattern compiled with
+both :const:`re.IGNORECASE` and :const:`re.LOCALE`. The case closure is now
+applied to the members of the set, so that ``[^bc]`` no longer matches
+``b'B'``.
+
+..
+
+.. date: 2026-08-26-15-28-59
+.. gh-issue: 156360
+.. nonce: ctZMHf
+.. section: Library
+
+Add the :envvar:`PYTHON_TURTLE_LANG` environment variable to select the
+language of :mod:`turtle` docstrings. Docstring dictionary entries naming a
+method which does not exist in the running version are no longer reported.
+
+..
+
+.. date: 2026-08-26-13-58-01
+.. gh-issue: 156400
+.. nonce: dGrmP1
+.. section: Library
+
+Fix socket and pipe leaks in :mod:`asyncio` when ``protocol_factory()``
+raises in :meth:`loop.create_datagram_endpoint
+`, :meth:`loop.connect_read_pipe
+`, and :meth:`loop.connect_write_pipe
+`. The socket or pipe is now closed instead
+of leaking until garbage collection.
+
+..
+
+.. date: 2026-08-26-12-48-10
+.. gh-issue: 156408
+.. nonce: -Yd0k7
+.. section: Library
+
+Fix :func:`asyncio.print_call_graph` raising :exc:`AttributeError` when
+called on a task that has already finished.
+
+..
+
+.. date: 2026-08-26-08-20-07
+.. gh-issue: 156404
+.. nonce: 2gP33I
+.. section: Library
+
+Restore compatibility with :file:`.pth` files generated before Python 3.15
+in the :mod:`site` module. Inject the ``fullname`` variable in the frame
+which executes pth code.
+
+..
+
+.. date: 2026-08-26-02-30-00
+.. gh-issue: 156353
+.. nonce: abcdef
+.. section: Library
+
+Fix :mod:`configparser` parsing when using whitespace in *delimiters*.
+
+..
+
+.. date: 2026-08-24-22-20-55
+.. gh-issue: 156327
+.. nonce: arC8Ph
+.. section: Library
+
+Fix :func:`asyncio.print_call_graph` including its own frame in the printed
+call stack.
+
+..
+
+.. date: 2026-08-24-14-28-47
+.. gh-issue: 108549
+.. nonce: XZ34WD
+.. section: Library
+
+Fix :class:`asyncio.Task`, when the task has a pending cancellation, replace
+**exc** exception with a :exc:`asyncio.CancelledError` unless it is
+:exc:`SystemExit` or :exc:`KeyboardInterrupt`, which must propagate
+unchanged.
+
+..
+
+.. date: 2026-08-22-19-00-00
+.. gh-issue: 156261
+.. nonce: Nq4tWv
+.. section: Library
+
+:func:`pwd.getpwuid` now raises :exc:`OverflowError` instead of
+:exc:`KeyError` if the user id is out of the range of the C ``uid_t`` type,
+as :func:`grp.getgrgid` does for the group id.
+
+..
+
+.. date: 2026-08-22-14-12-40
+.. gh-issue: 156230
+.. nonce: Lt9wQd
+.. section: Library
+
+:meth:`curses.window.instr`, :meth:`~curses.window.in_wstr` and
+:meth:`~curses.window.in_wchstr` no longer limit the count to 2047, which
+silently truncated a longer line.
+
+..
+
+.. date: 2026-08-22-10-30-00
+.. gh-issue: 156228
+.. nonce: k3Rmxw
+.. section: Library
+
+The :mod:`ssl` and :mod:`hashlib` modules now route OpenSSL memory
+allocations through the Python raw memory allocators, making OpenSSL memory
+usage visible to :mod:`tracemalloc` and to custom allocators installed with
+:c:func:`PyMem_SetAllocator`.
+
+..
+
+.. date: 2026-08-21-14-30-00
+.. gh-issue: 156180
+.. nonce: Qz3Lv8
+.. section: Library
+
+:func:`zlib.adler32_combine` and :func:`zlib.crc32_combine` now raise
+:exc:`ValueError` if the *len2* argument is negative, instead of returning
+rubbish or hanging indefinitely, respectively.
+
+..
+
+.. date: 2026-08-21-13-30-00
+.. gh-issue: 156166
+.. nonce: Xv8pQm
+.. section: Library
+
+:mod:`ssl`: A failed assignment or deletion of the ``_msg_callback``
+attribute of :class:`ssl.SSLContext` no longer removes the current callback.
+Deleting it now raises :exc:`AttributeError` instead of :exc:`TypeError`.
+
+..
+
+.. date: 2026-08-21-11-56-28
+.. gh-issue: 156173
+.. nonce: mhZa8a
+.. section: Library
+
+Calling :meth:`zlib.Decompress.flush` on invalid compressed data now raises
+:exc:`zlib.error` instead of being silently ignored.
+
+..
+
+.. date: 2026-08-20-16-30-00
+.. gh-issue: 156124
+.. nonce: Kq3vXz
+.. section: Library
+
+Fix a crash in the free-threaded build when deleting the :attr:`!contents`
+attribute of a :mod:`ctypes` pointer.
+
+..
+
+.. date: 2026-08-20-13-50-49
+.. gh-issue: 156112
+.. nonce: yEcma8
+.. section: Library
+
+:mod:`!_ios_support` no longer fails to import when
+:func:`ctypes.util.find_library` cannot resolve the ObjC runtime through the
+dyld shared cache, as is the case on iOS 13. The runtime is now loaded by
+name, which dyld resolves against the cache directly.
+
+..
+
+.. date: 2026-08-20-12-10-00
+.. gh-issue: 156101
+.. nonce: Qb2xNv
+.. section: Library
+
+Fix :attr:`sqlite3.Cursor.arraysize` being set to 0 if the assigned value is
+too large. The attribute is now left unchanged if the assignment fails.
+
+..
+
+.. date: 2026-08-20-12-05-00
+.. gh-issue: 156100
+.. nonce: Lm7qWz
+.. section: Library
+
+Fix crashes in :class:`sqlite3.Connection` when deleting the
+:attr:`~sqlite3.Connection.autocommit` attribute or setting it to an integer
+which does not fit in C :c:expr:`long`. Both now raise an exception.
+
+..
+
+.. date: 2026-08-20-12-00-00
+.. gh-issue: 156099
+.. nonce: Kp4vRt
+.. section: Library
+
+Fix a crash when deleting the ``keylog_filename`` attribute of
+:class:`ssl.SSLContext`. It now raises :exc:`AttributeError`.
+
+..
+
+.. date: 2026-08-19-21-01-19
+.. gh-issue: 156067
+.. nonce: 1CXkqc
+.. section: Library
+
+Fix error handling in the :mod:`zoneinfo` accelerator module when a
+transition index is ``-1`` or a TZ string's ``__bool__`` raises.
+
+..
+
+.. date: 2026-08-18-13-41-00
+.. gh-issue: 155997
+.. nonce: CjbD1F
+.. section: Library
+
+Fix :func:`concurrent.interpreters.list_all`. It failed if an interpreter
+was destroyed during the call, in particular by a garbage collection which
+finalized the object owning the last reference to it.
+
+..
+
+.. date: 2026-08-17-22-51-22
+.. gh-issue: 155974
+.. nonce: Qz3Vb7
+.. section: Library
+
+Fix a regression in Python 3.15: :meth:`~curses.window.addstr`,
+:meth:`~curses.window.addnstr`, :meth:`~curses.window.insstr` and
+:meth:`~curses.window.insnstr` again restore the window attributes when the
+write fails, instead of leaving the temporary *attr* applied.
+
+..
+
+.. date: 2026-08-17-21-00-00
+.. gh-issue: 155941
+.. nonce: strmCb
+.. section: Library
+
+Fix :func:`asyncio.start_server` when a plain-function *client_connected_cb*
+raises: the error is now reported like the coroutine case and the transport
+is closed, instead of leaving the connection open forever (which also made
+:meth:`asyncio.Server.wait_closed` hang).
+
+..
+
+.. date: 2026-08-17-18-00-00
+.. gh-issue: 155934
+.. nonce: acCept
+.. section: Library
+
+Fix a socket leak in :mod:`asyncio` when transport creation fails for a
+connection accepted by a server, and report the error via the loop exception
+handler even when debug mode is disabled.
+
+..
+
+.. date: 2026-08-17-17-39-41
+.. gh-issue: 155966
+.. nonce: 0YOADY
+.. section: Library
+
+:func:`math.tanpi` now raises :exc:`ValueError` for half-integer values
+(e.g., ``tanpi(1.5)``), as these are poles of the function.
+
+..
+
+.. date: 2026-08-17-12-40-00
+.. gh-issue: 155952
+.. nonce: Vq3Lm8
+.. section: Library
+
+Fix the signatures of :meth:`sqlite3.Connection.execute`,
+:func:`warnings.warn` and :func:`locale.setlocale` which rendered
+```` instead of the correct defaults for parameters.
+
+..
+
+.. date: 2026-08-17-12-07-38
+.. gh-issue: 155596
+.. nonce: Rt4mZq
+.. section: Library
+
+Fix :func:`pprint.pprint` and :func:`pprint.pformat` with ``expand=True``
+not honouring *width* for nested values. The width of the ``'key':`` prefix
+was not counted when deciding whether a value fitted on the current line, so
+values under long keys could overflow *width* instead of being expanded.
+
+..
+
+.. date: 2026-08-16-11-38-17
+.. gh-issue: 155888
+.. nonce: pO-nAp
+.. section: Library
+
+Fix :meth:`asyncio.WriteTransport.writelines` hanging the transport when the
+last data chunk is empty.
+
+..
+
+.. date: 2026-08-15-21-55-31
+.. gh-issue: 155869
+.. nonce: yRUnQW
+.. section: Library
+
+Fix :meth:`!reorganize` in :mod:`dbm.dumb` failing to persist updated value
+offsets, which could cause data loss after reopening the database.
+
+..
+
+.. date: 2026-08-15-18-16-16
+.. gh-issue: 121291
+.. nonce: WljPkh
+.. section: Library
+
+:class:`enum.Flag` (and :class:`enum.IntFlag`) subclasses no longer have a
+mixin base's own ``__or__``, ``__and__``, ``__xor__``, ``__ror__``,
+``__rand__``, ``__rxor__``, or ``__invert__`` override silently replaced by
+:class:`~enum.Flag`'s default implementation.
+
+..
+
+.. date: 2026-08-15-17-40-12
+.. gh-issue: 155863
+.. nonce: Kw3Vqp
+.. section: Library
+
+Add the ``WACS_*`` constants to the :mod:`curses` module. They are the
+counterparts of the ``ACS_*`` line-drawing codes as
+:class:`curses.complexchar` cells, and are added, like the latter, by
+:func:`curses.initscr` and :func:`curses.newterm`.
+
+..
+
+.. date: 2026-08-15-13-54-22
+.. gh-issue: 155843
+.. nonce: PD5Af3
+.. section: Library
+
+:mod:`hmac`: ensure that HMAC objects are properly initialized to prevent
+rare crashes on allocation failures. Patch by Bénédikt Tran.
+
+..
+
+.. date: 2026-08-15-13-18-01
+.. gh-issue: 155835
+.. nonce: mlyLWp
+.. section: Library
+
+:mod:`hashlib`: Fix a data race when accessing
+:attr:`~hashlib.hash.digest_size` on BLAKE-2 objects. Patch by Bénédikt
+Tran.
+
+..
+
+.. date: 2026-08-15-13-12-09
+.. gh-issue: 155835
+.. nonce: DsbSmy
+.. section: Library
+
+:mod:`hashlib`: Fix data races when accessing
+:attr:`~hashlib.hash.digest_size` and :attr:`~hashlib.hash.block_size` on
+SHA-3 objects. Patch by Bénédikt Tran.
+
+..
+
+.. date: 2026-08-15-10-20-40
+.. gh-issue: 155811
+.. nonce: knP-YB
+.. section: Library
+
+Add a sequence counter to GC statistics to prevent :mod:`!_remote_debugging`
+returning inconsistent snapshots caused by non-atomic reads. Patch by
+Maurycy Pawłowski-Wieroński.
+
+..
+
+.. date: 2026-08-15-09-47-23
+.. gh-issue: 155717
+.. nonce: jWFLR2
+.. section: Library
+
+:mod:`multiprocessing`'s default start method is now :ref:`"spawn"
+` instead of ``"forkserver"`` when there is
+no writable temporary directory, such as on a read-only file system.
+Previously starting a process failed with an :exc:`OSError` there. Patch by
+Bénédikt Tran.
+
+..
+
+.. date: 2026-08-14-14-10-00
+.. gh-issue: 155775
+.. nonce: Kq3vTx
+.. section: Library
+
+Fix a regression in :mod:`imaplib` introduced in the fix for :gh:`63121`:
+refreshing the capabilities after a successful :meth:`~imaplib.IMAP4.login`
+or :meth:`~imaplib.IMAP4.authenticate` consumed the ``CAPABILITY`` response,
+so it could no longer be read with :meth:`~imaplib.IMAP4.response`.
+
+..
+
+.. date: 2026-08-14-12-46-07
+.. gh-issue: 113318
+.. nonce: DYGQjo
+.. section: Library
+
+Fix crashes when deleting an attribute whose setter is generated by Argument
+Clinic and is not prepared for deletion, among them
+:attr:`frame.f_trace_opcodes` and the ``context``, ``owner`` and ``session``
+attributes of ``_ssl._SSLSocket``. Deleting such attribute now raises
+:exc:`AttributeError`.
+
+..
+
+.. date: 2026-08-14-11-12-18
+.. gh-issue: 155781
+.. nonce: sqlite-converter
+.. section: Library
+
+Fix a possible crash in free-threaded builds when the :mod:`sqlite3`
+converter registry is modified concurrently while a cursor builds its row
+cast map.
+
+..
+
+.. date: 2026-08-14-10-49-45
+.. gh-issue: 83371
+.. nonce: Km4Rt7
+.. section: Library
+
+Fix a deadlock in :class:`multiprocessing.pool.Pool` when *callback* or
+*error_callback* raises an exception. It killed the thread which handles
+results, so that the pool hung forever. The exception is now the result of
+the job, as an error raised while iterating the input, and is raised by
+:meth:`!AsyncResult.get`.
+
+..
+
+.. date: 2026-08-13-16-02-13
+.. gh-issue: 155702
+.. nonce: Kb7Qm4
+.. section: Library
+
+Fix :class:`sqlite3.Blob` slice assignment with a step. It patched the bytes
+object read from the blob, which for a single byte is an immortal singleton,
+so that the value of that byte was changed in the whole process.
+
+..
+
+.. date: 2026-08-12-22-15-00
+.. gh-issue: 90756
+.. nonce: Qn7dLm
+.. section: Library
+
+:meth:`xml.etree.ElementTree.ElementTree.write` now treats the ``utf-8-sig``
+encoding as ``utf-8`` in the XML declaration.
+
+..
+
+.. date: 2026-08-12-21-34-12
+.. gh-issue: 44871
+.. nonce: Rt7Nv2
+.. section: Library
+
+Parser objects of the :mod:`XML parser ` have a new
+method :meth:`!GetSpecifiedAttributeCount`. It tells how many of the
+attributes reported to :attr:`!StartElementHandler` were given in the start
+tag rather than defaulted from the DTD.
+
+..
+
+.. date: 2026-08-12-21-34-12
+.. gh-issue: 44871
+.. nonce: Qw3Lm8
+.. section: Library
+
+:mod:`xml.dom.minidom` now conforms closer to the DOM Level 1 specification.
+The factory methods now raise :exc:`~xml.dom.InvalidCharacterErr` if the
+name is not a valid XML name. Removing an absent attribute with
+:meth:`!Element.removeAttribute` or :meth:`!Element.removeAttributeNS` no
+longer raises :exc:`~xml.dom.NotFoundErr`, it has no effect as the DOM
+specifies. Inserting or setting a node created by another document now
+raises :exc:`~xml.dom.WrongDocumentErr`, setting an attribute node which
+belongs to another element now raises :exc:`~xml.dom.InuseAttributeErr`, and
+inserting a node into itself or its descendant now raises
+:exc:`~xml.dom.HierarchyRequestErr`. A document can no longer have two
+element or two document type children, and a document fragment can no longer
+have notation children. Attributes defaulted in the DTD are no longer
+omitted when parsing, and :attr:`!Attr.specified` now reports whether the
+attribute was given in the start tag. :class:`!EntityReference` nodes and
+:meth:`!Document.createEntityReference` are now implemented.
+
+..
+
+.. date: 2026-08-12-14-30-00
+.. gh-issue: 80762
+.. nonce: Kp3vQa
+.. section: Library
+
+Fix :func:`dir` on :class:`unittest.mock.Mock` objects created with a tuple
+*spec*: it raised :exc:`TypeError`. Such *spec* is now also documented.
+
+..
+
+.. date: 2026-08-12-09-30-00
+.. gh-issue: 61366
+.. nonce: Wr7cKm
+.. section: Library
+
+:meth:`!http.cookiejar.MozillaCookieJar.save` now writes ``0`` in the
+expiration time field for session cookies, as curl and Wget do. Previously
+this field was left empty, and such lines were ignored by curl and Wget.
+
+..
+
+.. date: 2026-08-10-22-23-29
+.. gh-issue: 153400
+.. nonce: nucElC
+.. section: Library
+
+On Linux, :func:`os.copy_file_range` and :func:`os.memfd_create` now fall
+back to the raw syscall when the libc Python is built against does not
+provide the wrapper function, so they stay available on interpreters built
+against a libc older than glibc 2.27.
+
+..
+
+.. date: 2026-08-10-22-11-15
+.. gh-issue: 153400
+.. nonce: Ds3GI3
+.. section: Library
+
+:mod:`os` and :mod:`signal`: Use glibc functions instead of ``syscall()``:
+``pidfd_open()``, ``pidfd_getfd()`` and ``pidfd_send_signal()`` (glibc
+2.36), ``gettid()`` and ``getdents64()`` (glibc 2.30), and ``getrandom()``
+(glibc 2.25). Patch by Victor Stinner.
+
+..
+
+.. date: 2026-08-10-19-49-12
+.. gh-issue: 155496
+.. nonce: tJtiAt
+.. section: Library
+
+The ``ctypes.set_errno`` and ``ctypes.set_last_error`` auditing events are
+now raised after the argument is converted to an integer, therefore they are
+no longer raised if the argument is invalid.
+
+..
+
+.. date: 2026-08-10-19-49-11
+.. gh-issue: 155496
+.. nonce: B4rMR1
+.. section: Library
+
+:meth:`io.RawIOBase.readinto` and :meth:`io.RawIOBase.write` now raise
+:exc:`TypeError` instead of :exc:`NotImplementedError` if they are called
+without the required argument.
+
+..
+
+.. date: 2026-08-10-15-24-13
+.. gh-issue: 155468
+.. nonce: W7qL2p
+.. section: Library
+
+Fix :mod:`netrc` to distinguish empty quoted tokens from end-of-file, so
+malformed files no longer cause the remaining content to be silently
+ignored.
+
+..
+
+.. date: 2026-08-10-13-27-36
+.. gh-issue: 155519
+.. nonce: 9M6SFX
+.. section: Library
+
+Avoid a data-race in free-threaded builds when reading and writing context
+variables from different threads.
+
+..
+
+.. date: 2026-08-10-09-00-18
+.. gh-issue: 155336
+.. nonce: vrTXoU
+.. section: Library
+
+Fix error handling in :func:`socket.gethostbyaddr` and
+:func:`socket.gethostbyname_ex` when hostname resolution fails.
+
+..
+
+.. date: 2026-08-09-21-30-00
+.. gh-issue: 118318
+.. nonce: Xr4Kd8
+.. section: Library
+
+Remove the ``write_c14n()`` method of
+:class:`xml.etree.ElementTree.ElementTree` and the support of
+``method="c14n"`` in :meth:`~xml.etree.ElementTree.ElementTree.write` and
+:func:`~xml.etree.ElementTree.tostring`. They never worked and always
+raised :exc:`ValueError`. Use :func:`xml.etree.ElementTree.canonicalize`
+instead.
+
+..
+
+.. date: 2026-08-09-16-14-38
+.. gh-issue: 155433
+.. nonce: KL7tHV
+.. section: Library
+
+Fix :class:`asyncio.TaskGroup` losing outside cancellation after
+``cancel()``.
+
+..
+
+.. date: 2026-08-09-14-27-23
+.. gh-issue: 155418
+.. nonce: kCXUIG
+.. section: Library
+
+Fix :class:`asyncio.TaskGroup` hang when a task created by
+:func:`asyncio.eager_task_factory` cancels the group before suspending.
+
+..
+
+.. date: 2026-08-09-01-30-00
+.. gh-issue: 102475
+.. nonce: rpjoin
+.. section: Library
+
+Fix :func:`os.path.realpath` on Windows: the unresolved part of the path is
+now appended, not joined, so a file name which looks like a drive (e.g.
+``spam:eggs``) no longer discards the resolved part. A path relative to
+another drive is now resolved against the root directory of that drive.
+
+..
+
+.. date: 2026-08-09-00-30-00
+.. gh-issue: 89760
+.. nonce: rpvol
+.. section: Library
+
+Fix :func:`os.path.realpath` on Windows: the ``\\?\`` prefix is no longer
+stripped from a volume GUID path, which made the result invalid.
+
+..
+
+.. date: 2026-08-08-21-40-00
+.. gh-issue: 84419
+.. nonce: statexe
+.. section: Library
+
+Fix :func:`os.stat` on Windows: trailing dots and spaces, which are ignored
+by the operating system, are no longer taken into account when the execute
+permissions are guessed from the file extension.
+
+..
+
+.. date: 2026-08-08-18-30-00
+.. gh-issue: 111331
+.. nonce: bioclose
+.. section: Library
+
+Closing a :class:`io.BytesIO` object which has exported buffers no longer
+fails with :exc:`BufferError`. The exported buffers keep the data alive and
+stay usable. As a result, destroying or garbage collecting such object no
+longer emits an unraisable exception.
+
+..
+
+.. date: 2026-08-08-09-14-22
+.. gh-issue: 108885
+.. nonce: C4ktfw
+.. section: Library
+
+Doctests run by the :mod:`unittest` test runner now report every example, as
+in verbose mode, if the runner reports more than the test names, i.e. its
+verbosity is 3 or higher. The :option:`!-v` option of :mod:`unittest` can
+now be repeated, so ``python -m unittest -vv`` asks for this. Added also
+the :attr:`~unittest.TestResult.verbosity` attribute of
+:class:`unittest.TestResult`.
+
+..
+
+.. date: 2026-08-07-02-20-00
+.. gh-issue: 155319
+.. nonce: srcline
+.. section: Library
+
+:func:`warnings.warn_explicit` now displays the source line taken from the
+loader of the module whose globals are passed as *module_globals*. It also
+no longer raises :exc:`IndexError` if *lineno* is out of the range of the
+module source.
+
+..
+
+.. date: 2026-08-07-01-10-00
+.. gh-issue: 123011
+.. nonce: warnexp
+.. section: Library
+
+:func:`warnings.warn_explicit` no longer emits a spurious
+:exc:`DeprecationWarning` or raises :exc:`ImportError` when it is called
+with the globals of the :mod:`__main__` module.
+
+..
+
+.. date: 2026-08-05-17-30-00
+.. gh-issue: 69370
+.. nonce: inspCLI
+.. section: Library
+
+:program:`python -m inspect --details` no longer fails with
+:exc:`UnicodeEncodeError` if the path of the module contains characters
+unencodable in the encoding of :data:`sys.stdout`. Such characters are now
+escaped with backslashes.
+
+..
+
+.. date: 2026-08-05-16-40-00
+.. gh-issue: 69371
+.. nonce: pyDocU
+.. section: Library
+
+Fix :mod:`pydoc` for modules whose path contains undecodable bytes.
+:func:`!pydoc.writedoc` and the pydoc HTTP server no longer fail with
+:exc:`UnicodeEncodeError`: the file URL is now percent-encoded using the
+filesystem encoding, and characters unencodable in the generated HTML page
+are escaped with backslashes.
+
+..
+
+.. date: 2026-08-05-16-30-12
+.. gh-issue: 155236
+.. nonce: Kd7pQr
+.. section: Library
+
+Add the *dedent* parameter in :func:`inspect.cleandoc` and
+:func:`inspect.getdoc`. :mod:`pydoc` no longer dedents documentation
+strings, so the indentation of the parameter descriptions generated by
+Argument Clinic is preserved.
+
+..
+
+.. date: 2026-08-05-02-36-18
+.. gh-issue: 155009
+.. nonce: YiJAiP
+.. section: Library
+
+Fix :class:`argparse.ArgumentParser` to preserve the program name from
+``sys.argv[0]`` when a named module is executed as the main program without
+replacing ``sys.argv[0]``.
+
+..
+
+.. date: 2026-08-04-19-50-52
+.. gh-issue: 150942
+.. nonce: B8ytes
+.. section: Library
+
+Improve the performance of :meth:`~io.IOBase.readlines` for
+:class:`io.BytesIO`.
+
+..
+
+.. date: 2026-08-04-19-03-20
+.. gh-issue: 155063
+.. nonce: gN_mCU
+.. section: Library
+
+Bump the version of pip bundled in ensurepip to version 26.2.1
+
+..
+
+.. date: 2026-08-04-14-14-31
+.. gh-issue: 153711
+.. nonce: PBpc1g
+.. section: Library
+
+On macOS, add run-time checks around the syscalls :manpage:`pipe2 (2)` and
+:manpage:`dup3 (2)`, in addition to the existing build-time checks. This
+means that Python built on macOS 27 (where these calls are available) can
+run on macOS 26 (where they aren't).
+
+..
+
+.. date: 2026-08-03-22-46-07
+.. gh-issue: 155143
+.. nonce: 9-byZp
+.. section: Library
+
+Fix :func:`asyncio.shield` leaking the calling task via the await-graph and
+callbacks when called on a future that never resolves.
+
+..
+
+.. date: 2026-08-01-23-50-47
+.. gh-issue: 75008
+.. nonce: 0Boa3r
+.. section: Library
+
+:meth:`csv.Sniffer.sniff` now detects the *lineterminator* parameter by a
+majority vote among the line endings of the sample.
+
+..
+
+.. date: 2026-08-01-21-00-00
+.. gh-issue: 155051
+.. nonce: Lc1Non
+.. section: Library
+
+:func:`decimal.localcontext` now raises :exc:`TypeError` if a keyword
+argument is ``None``, as the pure Python implementation already did.
+Previously the C implementation silently ignored it.
+
+..
+
+.. date: 2026-08-01-20-21-37
+.. gh-issue: 99772
+.. nonce: q7M3vP
+.. section: Library
+
+Fix comparisons and hashing of :class:`datetime.time` objects with
+sub-minute UTC offsets.
+
+..
+
+.. date: 2026-08-01-19-05-00
+.. gh-issue: 155044
+.. nonce: Op1Val
+.. section: Library
+
+:class:`optparse.Values` objects now support :func:`copy.replace`.
+
+..
+
+.. date: 2026-08-01-19-04-00
+.. gh-issue: 155043
+.. nonce: Ar1Nsp
+.. section: Library
+
+:class:`argparse.Namespace` objects now support :func:`copy.replace`.
+
+..
+
+.. date: 2026-08-01-19-02-00
+.. gh-issue: 155041
+.. nonce: Dc1Ctx
+.. section: Library
+
+:class:`decimal.Context` objects now support :func:`copy.replace`.
+
+..
+
+.. date: 2026-08-01-19-01-00
+.. gh-issue: 155040
+.. nonce: Tr1nFo
+.. section: Library
+
+:class:`tarfile.TarInfo` objects now support :func:`copy.replace`.
+
+..
+
+.. date: 2026-08-01-18-37-56
+.. gh-issue: 155063
+.. nonce: xC9PcH
+.. section: Library
+
+Bump the version of pip bundled in ensurepip to version 26.2
+
+..
+
+.. date: 2026-08-01-12-00-00
+.. gh-issue: 155033
+.. nonce: dR3pLc
+.. section: Library
+
+CSV dialects (instances of :class:`csv.Dialect` subclasses and dialect
+objects returned by :func:`csv.get_dialect`) now support
+:func:`copy.replace`.
+
+..
+
+.. date: 2026-07-30-23-29-56
+.. gh-issue: 154936
+.. nonce: a90443
+.. section: Library
+
+Fix the pure Python :mod:`json` decoder to report the correct position for
+invalid literal control characters in JSON strings.
+
+..
+
+.. date: 2026-07-30-02-15-00
+.. gh-issue: 154904
+.. nonce: Kx9mAq
+.. section: Library
+
+Speed up :mod:`shutil` import by probing the ``_bz2``, ``_lzma`` and
+``_zstd`` extension modules instead of importing the :mod:`bz2`, :mod:`lzma`
+and :mod:`compression.zstd` wrappers, which are now only imported when an
+archive is actually created or extracted.
+
+..
+
+.. date: 2026-07-29-21-37-39
+.. gh-issue: 154892
+.. nonce: eQyJ3Z
+.. section: Library
+
+Fix a bug in the C accelerator for :mod:`zoneinfo` where
+:class:`datetime.datetime` subclasses returning ``-1`` for ``hour``,
+``minute``, or ``second`` could incorrectly raise a :exc:`SystemError`.
+
+..
+
+.. date: 2026-07-29-19-48-59
+.. gh-issue: 154871
+.. nonce: tgZILS
+.. section: Library
+
+Fixed a crash in :meth:`asyncio.Task.get_context` when called on an
+uninitialized task.
+
+..
+
+.. date: 2026-07-29-18-30-00
+.. gh-issue: 154848
+.. nonce: Fr4meB
+.. section: Library
+
+The :mod:`pickle` C accelerator now enforces frame boundaries when
+unpickling, as the pure Python implementation already did. An argument that
+straddles a frame boundary, or a frame that begins before the previous one
+has ended, now raises :exc:`pickle.UnpicklingError` instead of being
+silently read across the boundary. This prevents the loaded data from
+diverging from the :mod:`pickletools` disassembly of the same pickle.
+
+..
+
+.. date: 2026-07-29-16-53-50
+.. gh-issue: 154885
+.. nonce: ptofmI
+.. section: Library
+
+:func:`os.get_terminal_size` now checks ``isatty`` before calling ``ioctl``,
+which reduces log noise on Android.
+
+..
+
+.. date: 2026-07-29-14-20-40
+.. gh-issue: 154855
+.. nonce: vfF453
+.. section: Library
+
+Fix :meth:`curses.window.instr`, :meth:`~curses.window.in_wstr` and
+:meth:`~curses.window.in_wchstr` returning one character too few when the
+:mod:`curses` module is built against a curses library that counts the
+terminator in the requested length, such as the NetBSD one.
+
+..
+
+.. date: 2026-07-29-11-58-17
+.. gh-issue: 154874
+.. nonce: NAPdBp
+.. section: Library
+
+Fix :func:`curses.termattrs` returning a negative value on a terminal that
+supports :const:`curses.A_ITALIC`, which left its result unusable as an
+attribute mask.
+
+..
+
+.. date: 2026-07-29-11-05-00
+.. gh-issue: 151728
+.. nonce: Kq3vTn
+.. section: Library
+
+Clear the internal :mod:`typing` caches from an exit handler. Previously, an
+extension module that leaked a reference to :mod:`typing` would also keep
+every subscripted type alive past interpreter shutdown, including types
+owned by unrelated extension modules.
+
+..
+
+.. date: 2026-07-28-08-02-41
+.. gh-issue: 154791
+.. nonce: ey7POa
+.. section: Library
+
+Fix :class:`asyncio.Future` (C implementation) losing the initial exception
+traceback frames when ``Future.result()`` is called more than once.
+Previously, the C implementation cleared the stored traceback after the
+first call, causing subsequent raises to omit the original raise site. The
+pure-Python implementation was unaffected.
+
+..
+
+.. date: 2026-07-27-12-00-00
+.. gh-issue: 94984
+.. nonce: Xr3vFq
+.. section: Library
+
+Add the *mode* parameter to :meth:`asyncio.loop.create_unix_server` and
+:func:`asyncio.start_unix_server` to set the permissions of the Unix socket
+file created for *path*, applied before the server starts accepting
+connections.
+
+..
+
+.. date: 2026-07-26-13-40-00
+.. gh-issue: 154744
+.. nonce: Sk1Psp
+.. section: Library
+
+Improve detection of ``skipinitialspace`` in :meth:`csv.Sniffer.sniff`.
+
+..
+
+.. date: 2026-07-26-11-45-34
+.. gh-issue: 154726
+.. nonce: hLJk5-
+.. section: Library
+
+Fix :func:`shutil.copyfile` to copy a symbolic link to a special file when
+``follow_symlinks=False`` instead of raising
+:exc:`~shutil.SpecialFileError`.
+
+..
+
+.. date: 2026-07-26-00-00-00
+.. gh-issue: 154738
+.. nonce: Rd5Pxe
+.. section: Library
+
+Fix :meth:`!ExternalEntityParserCreate` not propagating the reparse-deferral
+setting to the subparser, which left :meth:`!GetReparseDeferralEnabled`
+returning an uninitialized value. Patch by tonghuaroot.
+
+..
+
+.. date: 2026-07-25-13-30-00
+.. gh-issue: 93251
+.. nonce: gAiErr
+.. section: Library
+
+Fix :exc:`UnicodeDecodeError` in :mod:`socket` functions (such as
+:func:`~socket.getaddrinfo` and :func:`~socket.gethostbyaddr`) when the
+localized error message of the C library is not UTF-8: decode it from the
+locale encoding.
+
+..
+
+.. date: 2026-07-24-21-49-45
+.. gh-issue: 148468
+.. nonce: pHoF_Q
+.. section: Library
+
+Fix a regression in :mod:`argparse` where colorized argument help containing
+format specifiers did not accept string-like proxy objects.
+
+..
+
+.. date: 2026-07-24-17-02-46
+.. gh-issue: 154638
+.. nonce: 7YnFHH
+.. section: Library
+
+Improve import time of :mod:`argparse` by lazily importing several
+dependencies.
+
+..
+
+.. date: 2026-07-24-15-54-35
+.. gh-issue: 142035
+.. nonce: ZpNfl6
+.. section: Library
+
+Fix incorrect wrapping of :mod:`argparse` help text when color is enabled.
+
+..
+
+.. date: 2026-07-24-12-29-15
+.. gh-issue: 135736
+.. nonce: DyvA2m
+.. section: Library
+
+Fix ::class:`asyncio.TaskGroup` to not wrap a :exc:`GeneratorExit` into a
+:exc:`BaseExceptionGroup` if it was raised by the body of the task group and
+none of the tasks in the group raised exceptions.
+
+..
+
+.. date: 2026-07-24-00-02-00
+.. gh-issue: 154594
+.. nonce: Xk7mQ2
+.. section: Library
+
+Fix :func:`copy.deepcopy` so that an object whose deep copy is ``None`` is
+still memoized. Patch by tonghuaroot.
+
+..
+
+.. date: 2026-07-23-21-00-00
+.. gh-issue: 154568
+.. nonce: float16-reconstructor
+.. section: Library
+
+Fix :mod:`array` unpickling of little-endian float16.
+
+..
+
+.. date: 2026-07-23-20-00-00
+.. gh-issue: 154566
+.. nonce: byteswap-zd
+.. section: Library
+
+Fix :meth:`array.array.byteswap` corrupting data for ``'Zd'`` (complex
+double) arrays with more than one element: the 16-byte item loop advanced
+the buffer pointer by only 8 bytes per iteration, causing items after the
+first to be scrambled.
+
+..
+
+.. date: 2026-07-23-19-45-00
+.. gh-issue: 154551
+.. nonce: Ct7pL9
+.. section: Library
+
+Fix :func:`ctypes.util.find_library` returning ``None`` in non-UTF-8
+locales.
+
+..
+
+.. date: 2026-07-23-18-53-48
+.. gh-issue: 154523
+.. nonce: XUSRBO
+.. section: Library
+
+Fixed data-race when calling :meth:`io.TextIOBase.detach` in
+:term:`free-threaded build`.
+
+..
+
+.. date: 2026-07-23-14-13-39
+.. gh-issue: 135683
+.. nonce: droBu7
+.. section: Library
+
+:class:`logging.FileHandler` and
+:class:`logging.handlers.WatchedFileHandler` now honor
+:data:`logging.raiseExceptions` for errors that occur while opening the
+file, like for other errors during logging.
+
+..
+
+.. date: 2026-07-23-13-09-25
+.. gh-issue: 154199
+.. nonce: hmBfrS
+.. section: Library
+
+Make :func:`ctypes.util.find_msvcrt` always return ``None`` for
+compatibility reasons.
+
+..
+
+.. date: 2026-07-23-12-27-52
+.. gh-issue: 135736
+.. nonce: hkuGvu
+.. section: Library
+
+Fix :class:`asyncio.TaskGroup` silently discarding errors from sibling tasks
+whenever the ``async with`` block exits with a :exc:`SystemExit` or
+:exc:`KeyboardInterrupt`. These errors are now reported via
+:meth:`loop.call_exception_handler() `
+instead of being lost.
+
+..
+
+.. date: 2026-07-23-06-53-01
+.. gh-issue: 79366
+.. nonce: 3gMT7I
+.. section: Library
+
+Fixed a race condition in :mod:`logging`: if a handler was removed while a
+record was being emitted, the following handlers of the same logger could be
+skipped.
+
+..
+
+.. date: 2026-07-22-19-21-20
+.. gh-issue: 82535
+.. nonce: METFqd
+.. section: Library
+
+:class:`logging.handlers.SysLogHandler` no longer fails if the address
+cannot be resolved when the handler is created. The address is resolved
+again when a record is emitted.
+
+..
+
+.. date: 2026-07-22-17-35-24
+.. gh-issue: 70990
+.. nonce: xVHKwt
+.. section: Library
+
+:class:`logging.handlers.SysLogHandler` now accepts a :class:`bytes` address
+of a Unix domain socket, including an address in the abstract namespace.
+Previously only :class:`str` was recognized, and a :class:`bytes` address
+raised :exc:`ValueError`.
+
+..
+
+.. date: 2026-07-22-15-56-11
+.. gh-issue: 154189
+.. nonce: 7zWWNZ
+.. section: Library
+
+Fixed a potential use-after-free when calling :func:`functools.partial`.
+Now, when invoking a :func:`~functools.partial` object, the stored function,
+positional arguments, and keyword arguments are preserved for the duration
+of the call in case of reentrancy.
+
+..
+
+.. date: 2026-07-22-13-39-58
+.. gh-issue: 154470
+.. nonce: zGcz6K
+.. section: Library
+
+Fixed a spurious ``^J`` printed at the end of every source line by the
+``list`` command of :mod:`pdb` when the output is colorized (for example
+when attaching to a running process). The source line is now stripped before
+it is colorized, like the ``where`` command already did.
+
+..
+
+.. date: 2026-07-22-13-01-24
+.. gh-issue: 73458
+.. nonce: byxSPi
+.. section: Library
+
+Fix :func:`logging.config.listen`: it left the caller waiting for the
+``ready`` event forever if the server could not be started, for example if
+the port was invalid or already in use. It now also binds to an IPv6 address
+if the host has no IPv4 address, for example if ``localhost`` is only
+aliased to ``::1``.
+
+..
+
+.. date: 2026-07-22-13-00-00
+.. gh-issue: 154460
+.. nonce: wCsFtM
+.. section: Library
+
+Fix :func:`time.strftime` and :meth:`datetime.datetime.strftime` returning a
+wrong ISO 8601 week number (``%V``) on OpenBSD.
+
+..
+
+.. date: 2026-07-22-12-59-26
+.. gh-issue: 154467
+.. nonce: AA9w1D
+.. section: Library
+
+Fixed :mod:`pdb` remote attaching (``python -m pdb -p PID``) sending an
+empty prompt to the client instead of ``(Pdb)`` when the target process has
+an interactive terminal.
+
+..
+
+.. date: 2026-07-22-12-00-00
+.. gh-issue: 153970
+.. nonce: Kq7Wn3
+.. section: Library
+
+Calling :func:`str` on a :exc:`subprocess.CalledProcessError` no longer
+raises :exc:`TypeError` when its :attr:`!returncode` is not an integer, such
+as ``None``.
+
+..
+
+.. date: 2026-07-22-10-30-08
+.. gh-issue: 154435
+.. nonce: xCxm0T
+.. section: Library
+
+Fix :func:`os.posix_fadvise` and :func:`os.posix_fallocate` on DragonFly
+BSD: they raised :exc:`OSError` with a meaningless error code, because these
+functions return -1 and set ``errno`` there.
+
+..
+
+.. date: 2026-07-21-21-36-59
+.. gh-issue: 154399
+.. nonce: VSa6oH
+.. section: Library
+
+Fix :mod:`venv` activation in a non-interactive csh: ``activate.csh`` no
+longer fails when the ``prompt`` variable is not set.
+
+..
+
+.. date: 2026-07-21-20-34-05
+.. gh-issue: 154389
+.. nonce: DlTiii
+.. section: Library
+
+Fix :func:`uuid.uuid1` on OpenBSD: it returned a version 4 UUID, because
+``uuid_create()`` generates random UUIDs on this platform.
+
+..
+
+.. date: 2026-07-21-12-23-48
+.. gh-issue: 154335
+.. nonce: SRf8Gr
+.. section: Library
+
+The :mod:`profiling.sampling` profiler now respects ``NO_COLOR``,
+``FORCE_COLOR``, and ``PYTHON_COLORS`` and avoids colored output when not
+writing to a terminal.
+
+..
+
+.. date: 2026-07-21-08-31-55
+.. gh-issue: 154324
+.. nonce: vDxV5U
+.. section: Library
+
+Fix :func:`os.sendfile` on illumos: it no longer reports a successful
+transfer when the underlying system call failed without writing any data.
+
+..
+
+.. date: 2026-07-21-01-13-39
+.. gh-issue: 154307
+.. nonce: UNFKL4
+.. section: Library
+
+Fix :meth:`tempfile.TemporaryDirectory.cleanup` on DragonFly BSD, where
+removing a file with the ``UF_NOUNLINK`` flag failed with ``EISDIR`` instead
+of ``EPERM``.
+
+..
+
+.. date: 2026-07-20-22-03-44
+.. gh-issue: 154291
+.. nonce: Mi5HeQ
+.. section: Library
+
+Fix :func:`socket.has_dualstack_ipv6` to return ``False`` on platforms such
+as DragonFly BSD where setting ``IPV6_V6ONLY`` to 0 silently has no effect.
+
+..
+
+.. date: 2026-07-20-21-36-40
+.. gh-issue: 154283
+.. nonce: Xip7xE
+.. section: Library
+
+On DragonFly BSD, :func:`threading.get_native_id` now returns a value that
+is unique across processes, matching the other platforms.
+
+..
+
+.. date: 2026-07-20-18-30-00
+.. gh-issue: 154258
+.. nonce: mmapresize
+.. section: Library
+
+Fix a crash in :meth:`mmap.mmap.resize` on NetBSD when growing a shared
+anonymous mapping. :meth:`!resize` now raises :exc:`ValueError` in this
+case, as it already did on Linux.
+
+..
+
+.. date: 2026-07-20-17-15-00
+.. gh-issue: 131565
+.. nonce: dllist
+.. section: Library
+
+:func:`ctypes.util.dllist` now works on NetBSD. It is implemented in the
+:mod:`!_ctypes` extension module so that ``dl_iterate_phdr()`` reports all
+loaded shared libraries: on NetBSD it only reports the link-map group of the
+calling object, which excluded them when called through ctypes.
+
+..
+
+.. date: 2026-07-20-14-10-00
+.. gh-issue: 154225
+.. nonce: openpty
+.. section: Library
+
+Fix :func:`os.openpty` on Solaris and illumos: it no longer leaves the
+pseudo-terminal as the controlling terminal of the calling process.
+
+..
+
+.. date: 2026-07-20-14-00-00
+.. gh-issue: 154227
+.. nonce: openpt
+.. section: Library
+
+Fix :func:`os.posix_openpt` on OpenBSD, where it rejected the
+:data:`~os.O_CLOEXEC` flag.
+
+..
+
+.. date: 2026-07-20-12-45-00
+.. gh-issue: 139373
+.. nonce: qL7xKm
+.. section: Library
+
+Fix :meth:`asyncio.subprocess.Process.communicate` losing already-read
+output when it is cancelled; the output is now retained and returned by a
+subsequent ``communicate()`` call. Patch by Kumar Aditya.
+
+..
+
+.. date: 2026-07-20-12-40-00
+.. gh-issue: 145030
+.. nonce: TFJm6k
+.. section: Library
+
+Fix :mod:`asyncio` write pipe transports for named FIFOs on macOS and
+Solaris. Unread data sitting in the FIFO made the transport misinterpret a
+poll event as the reader disconnecting, wrongly closing the transport.
+
+..
+
+.. date: 2026-07-19-22-08-05
+.. gh-issue: 154194
+.. nonce: 1bqRdx
+.. section: Library
+
+Fix the sampling profiler dropping entire samples when a non-fatal read
+fails; frames now keep any readable metadata, and long funcnames and
+filenames are truncated instead. Patch by Maurycy Pawłowski-Wieroński.
+
+..
+
+.. date: 2026-07-19-21-30-00
+.. gh-issue: 154176
+.. nonce: strxfrm
+.. section: Library
+
+Fix a crash in :func:`locale.strxfrm` on DragonFly BSD, whose ``wcsxfrm()``
+does not support the zero size.
+
+..
+
+.. date: 2026-07-19-20-00-00
+.. gh-issue: 154836
+.. nonce: kqWait
+.. section: Library
+
+Fix :meth:`subprocess.Popen.wait` raising :exc:`TypeError` (macOS and other
+BSDs) or :exc:`OverflowError` (Linux) for very large *timeout* values such
+as ``float('inf')``, a 3.15 regression in the new event-driven wait. Also
+fix :meth:`select.kqueue.control` masking :exc:`OverflowError` for
+out-of-range timeouts as :exc:`TypeError`.
+
+..
+
+.. date: 2026-07-19-19-05-00
+.. gh-issue: 154146
+.. nonce: acospi
+.. section: Library
+
+Fix accuracy of :func:`math.acospi` for arguments close to 1 on platforms
+that do not provide ``acospi()`` in libm.
+
+..
+
+.. date: 2026-07-19-17-45-00
+.. gh-issue: 153005
+.. nonce: F6WH92
+.. section: Library
+
+:meth:`!concurrent.interpreters.Queue.get` and
+:meth:`!concurrent.interpreters.Queue.put` now compute their ``timeout``
+deadline from :func:`time.monotonic` instead of the wall clock, so adjusting
+the system clock during the call no longer makes them over- or under-wait.
+
+..
+
+.. date: 2026-07-19-17-05-00
+.. gh-issue: 153772
+.. nonce: cobjTK
+.. section: Library
+
+:func:`isinstance` checks against :mod:`collections.abc` classes such as
+:class:`~collections.abc.Mapping` no longer raise :exc:`AttributeError` when
+the instance has no ``__class__``. The abstract base class machinery now
+falls back to the object's type in that case, matching the behaviour of the
+built-in :func:`isinstance`.
+
+..
+
+.. date: 2026-07-19-14-00-00
+.. gh-issue: 154090
+.. nonce: q2kH1b
+.. section: Library
+
+Record the profiling mode in Tachyon binary profiles and reject differential
+comparisons whose known modes do not match.
+
+..
+
+.. date: 2026-07-19-13-00-00
+.. gh-issue: 154086
+.. nonce: MJKrQV
+.. section: Library
+
+Store per-thread sample counts in Tachyon flamegraphs so filtering a thread
+updates frame widths and totals.
+
+..
+
+.. date: 2026-07-19-12-10-00
+.. gh-issue: 154060
+.. nonce: cR6tYn
+.. section: Library
+
+Store measured duration and sampling rate in Tachyon binary profiles so they
+remain available in replayed flamegraphs.
+
+..
+
+.. date: 2026-07-19-12-00-00
+.. gh-issue: 154085
+.. nonce: Qm8fLd
+.. section: Library
+
+Prevent differential flamegraphs from duplicating self time across line
+nodes for the same function.
+
+..
+
+.. date: 2026-07-19-11-30-00
+.. gh-issue: 154088
+.. nonce: pC7nRa
+.. section: Library
+
+Make Tachyon count and render elided stacks consistently in differential
+flamegraphs.
+
+..
+
+.. date: 2026-07-19-11-20-00
+.. gh-issue: 154089
+.. nonce: Vp2qHx
+.. section: Library
+
+Do not show unavailable sampling efficiency statistics in replayed Tachyon
+flamegraphs.
+
+..
+
+.. date: 2026-07-19-11-00-00
+.. gh-issue: 154062
+.. nonce: N5ks3A
+.. section: Library
+
+Stop normalizing differential flamegraph baselines to the duration of the
+current profile.
+
+..
+
+.. date: 2026-07-19-00-00-00
+.. gh-issue: 154053
+.. nonce: LibreSSLsigalgs
+.. section: Library
+
+Fix compilation of the :mod:`ssl` module against LibreSSL, which does not
+provide ``SSL_CTX_set1_sigalgs_list()`` and
+``SSL_CTX_set1_client_sigalgs_list()``. The :meth:`!set_server_sigalgs` and
+:meth:`!set_client_sigalgs` methods of :class:`ssl.SSLContext` now raise
+:exc:`NotImplementedError` on LibreSSL.
+
+..
+
+.. date: 2026-07-18-18-12-44
+.. gh-issue: 154002
+.. nonce: Qw9zTn
+.. section: Library
+
+The pure-Python :mod:`pickle` unpickler no longer replaces a
+:exc:`TypeError` raised by an old-style instance constructor with a new one
+carrying the traceback object in its ``args``. The original error now
+propagates, as it already did in the C implementation.
+
+..
+
+.. date: 2026-07-18-17-09-49
+.. gh-issue: 154001
+.. nonce: 3brrUv
+.. section: Library
+
+Fix :func:`random.binomialvariate` raising :exc:`ZeroDivisionError` when
+:func:`random.random` returns zero.
+
+..
+
+.. date: 2026-07-18-16-43-02
+.. gh-issue: 118150
+.. nonce: x0mV8P
+.. section: Library
+
+Expose automated junk heuristic kwarg-only flag ``autojunk`` from
+:class:`difflib.SequenceMatcher` to the public functions and class methods
+in the :mod:`difflib`. See :class:`difflib.SequenceMatcher` documentation
+for details and issue :gh:`118150` for the motivation.
+
+..
+
+.. date: 2026-07-18-16-05-38
+.. gh-issue: 153967
+.. nonce: -OUNXe
+.. section: Library
+
+:meth:`argparse.ArgumentParser.print_usage` and
+:meth:`argparse.ArgumentParser.print_help` won't silently fail when an
+invalid file object is specified. Patch by Timothy Poon.
+
+..
+
+.. date: 2026-07-18-13-30-00
+.. gh-issue: 153906
+.. nonce: mHtNdY
+.. section: Library
+
+Modernize the HTML output of :mod:`pydoc`: use semantic HTML5 markup and a
+new style sheet based on the python-docs-theme used by docs.python.org, with
+dark mode support. Class members inherited from other classes are now
+collapsed by default.
+
+..
+
+.. date: 2026-07-18-11-16-41
+.. gh-issue: 153908
+.. nonce: 82FiGk
+.. section: Library
+
+Fix data race when calling :func:`repr` on :class:`itertools.count` under
+the :term:`free-threaded build`.
+
+..
+
+.. date: 2026-07-18-10-52-10
+.. gh-issue: 153896
+.. nonce: 87oevp
+.. section: Library
+
+Deduplicate unhashable args in :data:`typing.Literal`.
+
+..
+
+.. date: 2026-07-18-06-16-55
+.. gh-issue: 153903
+.. nonce: mJFrs8
+.. section: Library
+
+Add :func:`ctypes.util.wrap_dll_function` for creating
+:class:`~ctypes._CFuncPtr` objects from a function signature.
+
+..
+
+.. date: 2026-07-18-04-09-44
+.. gh-issue: 81241
+.. nonce: gGRbBr
+.. section: Library
+
+Fix :exc:`OSError` when importing :mod:`ctypes` from a statically linked
+interpreter.
+
+..
+
+.. date: 2026-07-17-20-56-32
+.. gh-issue: 153864
+.. nonce: WmA9By
+.. section: Library
+
+On a wide :mod:`curses` build, :meth:`curses.window.insch` now inserts a
+non-ASCII byte as the character it encodes in the window's encoding,
+consistently with :meth:`~curses.window.addch`, instead of its code point.
+
+..
+
+.. date: 2026-07-17-20-31-00
+.. gh-issue: 153862
+.. nonce: X3kjoY
+.. section: Library
+
+On a wide :mod:`curses` build, :meth:`curses.window.inch` now returns the
+locale-encoded byte of a non-ASCII character, matching
+:meth:`~curses.window.instr`, instead of the low byte of its code point.
+
+..
+
+.. date: 2026-07-17-14-30-00
+.. gh-issue: 153856
+.. nonce: JEHepm
+.. section: Library
+
+Add :data:`os.RWF_NOSIGNAL` constant for Linux 6.18+.
+
+..
+
+.. date: 2026-07-17-14-30-00
+.. gh-issue: 153844
+.. nonce: pYs7Kq
+.. section: Library
+
+:func:`symtable.symtable` now accepts an AST object, like the builtin
+:func:`compile`.
+
+..
+
+.. date: 2026-07-17-12-00-00
+.. gh-issue: 153838
+.. nonce: HmCp5s
+.. section: Library
+
+Skip non-regular files in the ``profiling.sampling`` heatmap exporter
+instead of reading them unconditionally. Patch by tonghuaroot.
+
+..
+
+.. date: 2026-07-15-21-56-40
+.. gh-issue: 146011
+.. nonce: nWmHif
+.. section: Library
+
+Fix a heap-use-after-free in the C implementation of :mod:`decimal` when
+calling :func:`repr` after deleting the :class:`~decimal.Context`.
+
+..
+
+.. date: 2026-07-15-21-45-33
+.. gh-issue: 141276
+.. nonce: xH7qP2
+.. section: Library
+
+Fix duplicate :exc:`SyntaxWarning` messages when importing source modules
+from ZIP archives. :meth:`zipimport.zipimporter.get_filename`, and therefore
+:meth:`~zipimport.zipimporter.find_spec`, no longer compile source modules.
+A :exc:`SyntaxError` in a zipped source module is now raised when the module
+is executed rather than when it is found, matching the behavior of
+filesystem-based loaders.
+
+..
+
+.. date: 2026-07-15-15-19-08
+.. gh-issue: 104533
+.. nonce: pQJxCk
+.. section: Library
+
+Add :func:`ctypes.util.struct` and :class:`ctypes.util.CFieldInfo` for
+generating structure types using annotations.
+
+..
+
+.. date: 2026-07-15-14-24-18
+.. gh-issue: 153761
+.. nonce: 8jqs67
+.. section: Library
+
+Fix cancelling :meth:`asyncio.loop.sock_accept` dropping a pending
+connection.
+
+..
+
+.. date: 2026-07-14-19-45-21
+.. gh-issue: 153695
+.. nonce: UYdZJZ
+.. section: Library
+
+Hashing a :class:`sqlite3.Row` that contains an unhashable value now raises
+:exc:`TypeError` instead of :exc:`SystemError`. Patch by tonghuaroot.
+
+..
+
+.. date: 2026-07-14-15-00-00
+.. gh-issue: 127049
+.. nonce: pQw7Rk
+.. section: Library
+
+Fix a race condition in :mod:`asyncio` on Unix where
+:meth:`asyncio.subprocess.Process.send_signal`,
+:meth:`~asyncio.subprocess.Process.terminate` or
+:meth:`~asyncio.subprocess.Process.kill` could signal an unrelated process
+that was recycled onto the PID of the already-reaped child when
+ThreadedChildWatcher is used. Patch by Kumar Aditya.
+
+..
+
+.. date: 2026-07-14-12-00-00
+.. gh-issue: 83273
+.. nonce: SnifQ7
+.. section: Library
+
+:meth:`csv.Sniffer.sniff` now deduces the dialect by trial parsing with the
+actual CSV parser instead of heuristics based on matching isolated fragments
+and on character frequencies. It can now detect the *escapechar* parameter,
+accepts non-ASCII delimiters in the *delimiters* argument, no longer
+misdetects the delimiter when the sample contains delimiter characters
+inside quoted fields, handles samples truncated at an arbitrary point, and
+no longer takes quadratic time on quoted samples. A sample consisting of a
+single column of quoted fields now raises :exc:`csv.Error` instead of
+guessing a delimiter from the content of the fields.
+
+..
+
+.. date: 2026-07-13-10-27-08
+.. gh-issue: 153658
+.. nonce: A6o4n5
+.. section: Library
+
+Fix :meth:`sqlite3.Connection.iterdump` raising
+:exc:`sqlite3.OperationalError` when a table name contains a single quote.
+Patch by tonghuaroot.
+
+..
+
+.. date: 2026-07-12-10-00-00
+.. gh-issue: 98078
+.. nonce: fA3lRt
+.. section: Library
+
+Fix :mod:`asyncio` SSL transports not sending the fatal TLS alert to the
+peer when the TLS handshake fails or when receiving corrupted data, and not
+sending the ``close_notify`` alert to the peer when the TLS shutdown fails.
+The peer can now tell why the connection was dropped (for example,
+certificate verification failure or no TLS version in common) instead of
+seeing the connection abruptly closed.
+
+..
+
+.. date: 2026-07-12-00-00-00
+.. gh-issue: 85943
+.. nonce: 8f906e
+.. section: Library
+
+Fix :mod:`struct` functions raising :exc:`BytesWarning` under the ``-bb``
+command line option when a :class:`str` format is used after an equal
+:class:`bytes` format (or vice versa). The internal format cache no longer
+mixes :class:`str` and :class:`bytes` keys.
+
+..
+
+.. date: 2026-07-11-13-24-49
+.. gh-issue: 153603
+.. nonce: YbKlry
+.. section: Library
+
+Fix a crash in the ISO-2022 decoders when decoding a byte after an unknown
+charset designation is set via the decoder's ``setstate`` method. Patch by
+tonghuaroot.
+
+..
+
+.. date: 2026-07-11-12-21-12
+.. gh-issue: 153539
+.. nonce: gBs2T5
+.. section: Library
+
+Fix a crash in the C implementation of :meth:`io.TextIOWrapper.tell` when
+the decoder's ``getstate`` method triggers a reentrant seek, or when another
+thread seeks the same stream concurrently. Patch by tonghuaroot.
+
+..
+
+.. date: 2026-07-10-18-30-00
+.. gh-issue: 153502
+.. nonce: uIdKw0
+.. section: Library
+
+:meth:`imaplib.IMAP4.copy`, :meth:`~imaplib.IMAP4.move`,
+:meth:`~imaplib.IMAP4.fetch`, :meth:`~imaplib.IMAP4.store`,
+:meth:`~imaplib.IMAP4.search`, :meth:`~imaplib.IMAP4.sort`,
+:meth:`~imaplib.IMAP4.thread` and :meth:`~imaplib.IMAP4.expunge` now accept
+a keyword-only *uid* argument that selects the corresponding ``UID``
+command, as a more convenient alternative to :meth:`~imaplib.IMAP4.uid`.
+
+..
+
+.. date: 2026-07-10-16-00-00
+.. gh-issue: 153494
+.. nonce: qCh8rT
+.. section: Library
+
+:meth:`imaplib.IMAP4.search`, :meth:`~imaplib.IMAP4.sort` and
+:meth:`~imaplib.IMAP4.thread` (and the corresponding ``uid`` commands) now
+encode :class:`str` search criteria to the declared *charset*, so
+international search text can be passed as ordinary :class:`str`. When
+*charset* is ``None`` (as it must be under ``UTF8=ACCEPT``), the criteria
+are sent using the connection encoding instead. A criterion passed as
+:class:`bytes` is sent unchanged, for use with a charset that Python has no
+codec for.
+
+..
+
+.. date: 2026-07-10-12-33-30
+.. gh-issue: 153513
+.. nonce: GxrPuY
+.. section: Library
+
+Values of several Tcl object types returned by :mod:`tkinter` are now
+converted to the corresponding Python type instead of being wrapped in a
+:class:`!_tkinter.Tcl_Obj`: ``index``, ``window``, ``nsName`` and
+``parsedVarName`` objects to :class:`str`, and ``pixel`` screen distances
+with no unit suffix to :class:`int` or :class:`float`.
+
+..
+
+.. date: 2026-07-09-16-35-47
+.. gh-issue: 153404
+.. nonce: daRkes
+.. section: Library
+
+:class:`urllib.robotparser.RobotFileParser` now silently ignores a
+``Crawl-delay`` or ``Request-rate`` value written with non-decimal digits
+(such as ``U+00B2 SUPERSCRIPT TWO``) instead of raising :exc:`ValueError`
+and aborting the parse of the whole ``robots.txt`` file.
+
+..
+
+.. date: 2026-07-09-15-18-23
+.. gh-issue: 151292
+.. nonce: f4NQSW
+.. section: Library
+
+Store the sample count in :mod:`profiling.sampling` binary format, as a
+64-bit integer, widening from previously used 32-bit integer. This breaks
+the existing recordings. Long or thread-heavy profiling sessions will no
+longer fail because of :exc:`OverflowError`. Patch by Maurycy
+Pawłowski-Wieroński.
+
+..
+
+.. date: 2026-07-09-14-56-24
+.. gh-issue: 152754
+.. nonce: CyyC5j
+.. section: Library
+
+Fix a crash when the same :func:`os.scandir` iterator is used concurrently
+from multiple threads. It no longer releases the directory handle while
+another thread is reading from it. Sharing an iterator between threads
+remains subject to race conditions: which entries each thread receives is
+unspecified.
+
+..
+
+.. date: 2026-07-09-14-00-00
+.. gh-issue: 153417
+.. nonce: Bw7Rq2
+.. section: Library
+
+Error messages from :meth:`imaplib.IMAP4.select` and
+:meth:`imaplib.IMAP4.uid` no longer raise :exc:`BytesWarning` under
+:option:`!-bb` when the mailbox or command argument is :class:`bytes`.
+
+..
+
+.. date: 2026-07-09-12-35-19
+.. gh-issue: 153422
+.. nonce: tKb0Xq
+.. section: Library
+
+:meth:`!winfo_exists`, :meth:`!winfo_ismapped` and :meth:`!winfo_viewable`
+methods of :mod:`tkinter` widgets and :meth:`!edit_modified` of
+:class:`tkinter.Text` now return a :class:`bool` instead of an integer or,
+depending on ``wantobjects``, a string.
+
+..
+
+.. date: 2026-07-09-12-00-00
+.. gh-issue: 49555
+.. nonce: Ka9Lm2
+.. section: Library
+
+:mod:`imaplib` now encodes non-ASCII mailbox names as modified UTF-7
+(:rfc:`3501`, section 5.1.3) in the default mode, so international mailbox
+names can be passed as ordinary :class:`str`; under ``UTF8=ACCEPT`` they are
+sent as UTF-8 instead. A name that is not valid modified UTF-7, such as one
+with a bare ``&``, is now encoded correctly instead of being sent as is. A
+``str`` that is already valid modified UTF-7, or a :class:`bytes` object, is
+sent unchanged.
+
+..
+
+.. date: 2026-07-09-10-14-08
+.. gh-issue: 153395
+.. nonce: N8FuG3
+.. section: Library
+
+:mod:`curses.ascii` predicates and the :func:`~curses.ascii.ctrl` and
+:func:`~curses.ascii.unctrl` functions now accept a
+:class:`curses.complexchar`. :func:`~curses.ascii.ctrl` now returns a
+non-ASCII argument unchanged instead of masking it to a control character.
+
+..
+
+.. date: 2026-07-09-08-40-00
+.. gh-issue: 153290
+.. nonce: GTzSEa
+.. section: Library
+
+Fix a data race on the free-threaded build when
+:meth:`!io.BytesIO.__setstate__` installs the instance dictionary while
+another thread concurrently calls a method on the same object.
+
+..
+
+.. date: 2026-07-09-00-00-00
+.. gh-issue: 153406
+.. nonce: vyMmB6
+.. section: Library
+
+:func:`email.utils.parsedate_to_datetime` now raises :exc:`ValueError`
+instead of :exc:`OverflowError` when the parsed year or timezone offset is
+out of range, matching its documented behavior.
+
+..
+
+.. date: 2026-07-08-23-20-00
+.. gh-issue: 152907
+.. nonce: oyPV9Y
+.. section: Library
+
+Restore cooked-mode terminal output flags around :c:data:`PyOS_InputHook`
+callbacks in the new :term:`REPL` (:mod:`!_pyrepl`), so that output written
+by an input hook (for example a GUI toolkit event loop) is no longer emitted
+with ``OPOST`` disabled and keeps its carriage returns.
+
+..
+
+.. date: 2026-07-08-22-18-04
+.. gh-issue: 153364
+.. nonce: JBFHEg
+.. section: Library
+
+Make frame, coroutine and task-waiter walks iterative and bounded, avoiding
+potential hangs and stack overflows. Fix asyncio task inspection when
+awaited-by sets contain removed entries. Patch by Maurycy
+Pawłowski-Wieroński.
+
+..
+
+.. date: 2026-07-08-21-15-00
+.. gh-issue: 153333
+.. nonce: Kp3mZq
+.. section: Library
+
+The ``readprofile`` method of :class:`tkinter.Tk` now reads the user's
+profile scripts using the encoding declared in the file, instead of the
+locale encoding.
+
+..
+
+.. date: 2026-07-08-19-40-00
+.. gh-issue: 153319
+.. nonce: Qk7bE2
+.. section: Library
+
+The :mod:`turtledemo` viewer now reads each demo script as UTF-8 instead of
+the locale encoding.
+
+..
+
+.. date: 2026-07-08-15-26-00
+.. gh-issue: 153296
+.. nonce: Twix12
+.. section: Library
+
+Fix a data race and use-after-free when iterating over an
+:class:`io.StringIO` object while it is being concurrently mutated. The
+``__next__`` method now properly acquires the object's lock.
+
+..
+
+.. date: 2026-07-08-06-54-57
+.. gh-issue: 152936
+.. nonce: TaFl0J
+.. section: Library
+
+:func:`os.chroot`, :func:`os.initgroups`, :func:`os.setegid`,
+:func:`os.seteuid`, :func:`os.setgid`, :func:`os.setregid`,
+:func:`os.setresgid`, :func:`os.setresuid`, :func:`os.setreuid`,
+:func:`os.setuid`, and :func:`socket.sethostname` are now available on
+Android. Calling them without sufficient privileges now raises
+:exc:`PermissionError` instead of the functions being unavailable.
+
+..
+
+.. date: 2026-07-08-01-47-15
+.. gh-issue: 153083
+.. nonce: XbKZCp
+.. section: Library
+
+Defer GC tracking of an :class:`array.array` to the end of its construction.
+Patch by Donghee Na.
+
+..
+
+.. date: 2026-07-08-01-03-17
+.. gh-issue: 153292
+.. nonce: oHDt3l
+.. section: Library
+
+Fix data race in repr of :class:`threading.RLock` in free-threading build.
+
+..
+
+.. date: 2026-07-08-00-00-00
+.. gh-issue: 153291
+.. nonce: rdlnCS
+.. section: Library
+
+Fix a data race in :func:`readline.get_completer` and
+:func:`readline.get_pre_input_hook` on the :term:`free-threaded ` build: the getters read the stored hook without the critical
+section that the corresponding setters hold.
+
+..
+
+.. date: 2026-07-07-22-06-52
+.. gh-issue: 153293
+.. nonce: 0DvYdc
+.. section: Library
+
+Fix the live sampling profiler TUI keeping stale aggregated opcode
+statistics after a stats reset.
+
+..
+
+.. date: 2026-07-07-17-50-54
+.. gh-issue: 143990
+.. nonce: FoNtCf
+.. section: Library
+
+A :class:`tkinter.font.Font` created from a named font, including by
+:meth:`~tkinter.font.Font.copy`, now copies its configured options rather
+than the options resolved by Tcl's ``font actual``, preserving a size
+specified in pixels (a negative size).
+
+..
+
+.. date: 2026-07-07-13-31-52
+.. gh-issue: 148286
+.. nonce: -qu-em
+.. section: Library
+
+Fix undefined behavior in
+:attr:`compression.zstd.ZstdDecompressor.unused_data` when a complete frame
+was decompressed in a single call.
+
+..
+
+.. date: 2026-07-07-02-26-43
+.. gh-issue: 153210
+.. nonce: LUXIcm
+.. section: Library
+
+Fix crash on :mod:`array` import under a memory pressure.
+
+..
+
+.. date: 2026-07-06-14-30-00
+.. gh-issue: 153521
+.. nonce: iMaP47
+.. section: Library
+
+Add support for structured arguments in :mod:`imaplib` command methods. A
+*message_set* and lists of flags or other atoms can now be passed as
+sequences instead of preformatted strings, and the
+:meth:`~imaplib.IMAP4.search`, :meth:`~imaplib.IMAP4.fetch`,
+:meth:`~imaplib.IMAP4.sort`, :meth:`~imaplib.IMAP4.thread` and
+:meth:`~imaplib.IMAP4.uid` methods accept a *params* keyword argument that
+substitutes and quotes ``?`` placeholders.
+
+..
+
+.. date: 2026-07-06-14-18-33
+.. gh-issue: 153256
+.. nonce: tkPrnt
+.. section: Library
+
+Added the :meth:`!tk_print` method to :class:`tkinter.Canvas` and
+:class:`tkinter.Text` which prints the contents of the widget using the
+native print dialog. It requires Tk 8.7/9.0 or newer.
+
+..
+
+.. date: 2026-07-06-14-05-40
+.. gh-issue: 153259
+.. nonce: sysTr1
+.. section: Library
+
+Added the :mod:`tkinter.systray` module which provides the
+:class:`~tkinter.systray.SysTrayIcon` class as an interface to the system
+tray icon and the :func:`~tkinter.systray.notify` function which sends a
+desktop notification. They require Tk 8.7/9.0 or newer.
+
+..
+
+.. date: 2026-07-06-13-42-17
+.. gh-issue: 72880
+.. nonce: fcXhWr
+.. section: Library
+
+Added the :mod:`tkinter.fontchooser` module which provides the
+:class:`~tkinter.fontchooser.FontChooser` class as an interface to the
+native font selection dialog.
+
+..
+
+.. date: 2026-07-06-12-00-00
+.. gh-issue: 153200
+.. nonce: isqrtLt
+.. section: Library
+
+Fix :func:`math.isqrt` returning an incorrect result for arguments not less
+than 2**64 that are instances of an :class:`int` subclass with an overridden
+comparison operator.
+
+..
+
+.. date: 2026-07-06-10-30-00
+.. gh-issue: 153158
+.. nonce: m0nthP
+.. section: Library
+
+Remove the erroneous *width* argument of
+:meth:`!calendar.HTMLCalendar.formatmonthpage`, which could drop the year
+from the heading.
+
+..
+
+.. date: 2026-07-05-22-30-00
+.. gh-issue: 66788
+.. nonce: tM7pQ2
+.. section: Library
+
+Add the ``utf-7-imap`` codec, implementing the modified UTF-7 encoding used
+for international IMAP4 mailbox names (:rfc:`3501`, section 5.1.3).
+
+..
+
+.. date: 2026-07-05-21-40-00
+.. gh-issue: 89869
+.. nonce: XG7aHz
+.. section: Library
+
+Add :meth:`imaplib.IMAP4.login_plain`, which authenticates using the
+``PLAIN`` SASL mechanism (:rfc:`4616`). Unlike
+:meth:`~imaplib.IMAP4.login`, it supports non-ASCII user names and
+passwords.
+
+..
+
+.. date: 2026-07-05-20-15-00
+.. gh-issue: 98092
+.. nonce: iDcmd1
+.. section: Library
+
+Add :meth:`imaplib.IMAP4.id`, a wrapper for the IMAP ``ID`` command
+(:rfc:`2971`).
+
+..
+
+.. date: 2026-07-05-17-39-16
+.. gh-issue: 153133
+.. nonce: kKSH7g
+.. section: Library
+
+Fix a socket leak in :meth:`asyncio.loop.create_connection` when the
+transport cannot be created.
+
+..
+
+.. date: 2026-07-05-16-09-31
+.. gh-issue: 153068
+.. nonce: huY9Jh
+.. section: Library
+
+Fix :meth:`!cProfile.Profile.enable` to no longer overwrite errors from
+:mod:`sys.monitoring`.
+
+..
+
+.. date: 2026-07-05-14-30-00
+.. gh-issue: 153062
+.. nonce: teeFT1
+.. section: Library
+
+Fix a crash when concurrently iterating an :func:`itertools.tee` iterator on
+the free-threaded build.
+
+..
+
+.. date: 2026-07-05-12-00-00
+.. gh-issue: 153056
+.. nonce: tMpLat
+.. section: Library
+
+Fix :class:`string.Template` raising a spurious :exc:`ValueError` when the
+*pattern* attribute is a compiled regular expression object, which the
+documentation allows. On the free-threaded build this also occurred as a
+data race on the first concurrent use.
+
+..
+
+.. date: 2026-07-05-11-36-51
+.. gh-issue: 59396
+.. nonce: Apl7sI
+.. section: Library
+
+:class:`tkinter.scrolledtext.ScrolledText` gained a *use_ttk* parameter to
+use the themed :mod:`tkinter.ttk` frame and scroll bar instead of the
+classic :mod:`tkinter` widgets.
+
+..
+
+.. date: 2026-07-05-10-24-30
+.. gh-issue: 143921
+.. nonce: wQx3Tn
+.. section: Library
+
+Narrow the control character check in :mod:`imaplib` commands: only NUL, CR
+and LF are now rejected. Other control characters are valid in quoted
+strings and can occur in mailbox names returned by the server, so they are
+now accepted and sent quoted.
+
+..
+
+.. date: 2026-07-04-20-28-51
+.. gh-issue: 153037
+.. nonce: XUSp_g
+.. section: Library
+
+Fix :class:`~compression.zstd.ZstdFile` raising :exc:`AttributeError`
+instead of :exc:`io.UnsupportedOperation` when iterating over a file that is
+not open for reading.
+
+..
+
+.. date: 2026-07-04-13-00-00
+.. gh-issue: 135661
+.. nonce: CIkADG
+.. section: Library
+
+Fix :class:`html.parser.HTMLParser`: an abruptly closed empty comment
+(```` or ````) no longer extends up to a later ``-->`` in the
+same :meth:`~html.parser.HTMLParser.feed` call.
+
+..
+
+.. date: 2026-07-04-11-26-24
+.. gh-issue: 153009
+.. nonce: KGl-nQ
+.. section: Library
+
+Fix compilation of :mod:`curses` on platforms that define the ``stdscr``
+macro. Patch by Bénédikt Tran.
+
+..
+
+.. date: 2026-07-04-11-14-06
+.. gh-issue: 152851
+.. nonce: diYvTf
+.. section: Library
+
+Prevent a crash when allocation fails while copying a :func:`BLAKE-2s/2b
+` object. Patch by Bénédikt Tran.
+
+..
+
+.. date: 2026-07-04-00-19-23
+.. gh-issue: 127636
+.. nonce: o_uD9U
+.. section: Library
+
+Fix :meth:`tarfile.TarFile.extract` to accept archive member names with a
+trailing forward slash, including those returned by
+:meth:`tarfile.TarFile.getnames`. Contributed by Xiao Yuan.
+
+..
+
+.. date: 2026-07-03-21-10-00
+.. gh-issue: 54930
+.. nonce: hq09Er
+.. section: Library
+
+Error responses of :class:`http.server.BaseHTTPRequestHandler` to malformed
+request lines now include a status line and headers instead of being sent in
+the bare HTTP/0.9 style. Only a valid HTTP/0.9 request (a two-word ``GET``
+request line) now receives an HTTP/0.9 style response.
+
+..
+
+.. date: 2026-07-03-19-51-47
+.. gh-issue: 152997
+.. nonce: i1ErzB
+.. section: Library
+
+On platforms providing the C library's :manpage:`iconv(3)` function, the
+:mod:`codecs` module now exposes every encoding known to ``iconv`` for which
+Python has no built-in codec. Such an encoding can be used by its name (for
+example ``"cp1133"``) or, to force the ``iconv``-based engine even when a
+built-in codec exists, with an ``"iconv:"`` prefix (for example
+``"iconv:latin1"``).
+
+..
+
+.. date: 2026-07-03-18-30-00
+.. gh-issue: 119592
+.. nonce: mQr3Vx
+.. section: Library
+
+Fix :class:`concurrent.futures.ProcessPoolExecutor` stranding submitted work
+forever when a worker process exited upon reaching its *max_tasks_per_child*
+limit after :meth:`~concurrent.futures.Executor.shutdown` was called with
+``wait=False``: a replacement worker is now spawned and the remaining work
+executed as documented. If the executor has instead been garbage collected
+without ``shutdown()`` (:gh:`152967`), or a replacement worker cannot be
+started, the remaining futures now fail with
+:exc:`~concurrent.futures.process.BrokenProcessPool` instead of never
+resolving. A worker exit racing ``shutdown(wait=False)`` can also no longer
+crash the executor management thread.
+
+..
+
+.. date: 2026-07-03-17-29-34
+.. gh-issue: 150579
+.. nonce: 0tLpQukIU
+.. section: Library
+
+:mod:`concurrent.futures` now uses lazy imports for its executor submodules
+instead of a module ``__getattr__`` hook.
+
+..
+
+.. date: 2026-07-03-14-54-33
+.. gh-issue: 152951
+.. nonce: u8tPCI
+.. section: Library
+
+:class:`collections.deque` prevent rare crash when calling ``extend`` under
+high memory pressure conditions.
+
+..
+
+.. date: 2026-07-03-02-11-00
+.. gh-issue: 152912
+.. nonce: Mv3KpR
+.. section: Library
+
+``sys.addaudithook()`` now correctly suppresses only :exc:`RuntimeError`
+instead of all :exc:`Exception` subclasses when an existing audit hook
+raises during hook registration. Patch by Yeongu Kim.
+
+..
+
+.. date: 2026-07-02-22-19-53
+.. gh-issue: 150880
+.. nonce: vPZ7jK
+.. section: Library
+
+Normalize non-extended Windows paths before appending the wildcard used by
+``os.listdir()`` and ``os.scandir()``, making paths with trailing spaces
+behave consistently with other filesystem APIs.
+
+..
+
+.. date: 2026-07-02-19-21-15
+.. gh-issue: 152068
+.. nonce: ThsmJU
+.. section: Library
+
+Fixes a bug when a line was split (particularly on macOS Terminal.app) in
+the middle of a colorized keyword, causing the ANSI Color Reset sequence
+(ESC0m) to not be properly printed, causing the output to be colored when it
+shouldn't
+
+..
+
+.. date: 2026-07-02-15-26-51
+.. gh-issue: 151292
+.. nonce: nmnQlp
+.. section: Library
+
+Fix ``profiling.sampling --binary`` leaving unreadable profile files when
+the binary format reaches a size limit. Preserve collected samples when the
+writer can still finalize safely. Patch by Maurycy Pawłowski-Wieroński.
+
+..
+
+.. date: 2026-07-02-13-30-00
+.. gh-issue: 152849
+.. nonce: K9dRvP
+.. section: Library
+
+Out-of-range float and integer timestamps now raise :exc:`OverflowError`
+with the same message. Patch by tonghuaroot.
+
+..
+
+.. date: 2026-07-02-12-00-00
+.. gh-issue: 152847
+.. nonce: PitKqc
+.. section: Library
+
+Reject a POSIX TZ transition rule with non-digit characters in the
+day-of-year field in the pure-Python :mod:`zoneinfo` parser. Patch by
+tonghuaroot.
+
+..
+
+.. date: 2026-07-01-23-17-27
+.. gh-issue: 152905
+.. nonce: wLnGqR
+.. section: Library
+
+On glibc, :func:`locale.nl_langinfo` now decodes the ``LC_TIME`` items (such
+as the month and day names) using the wide locale data, so the result no
+longer depends on the ``LC_CTYPE`` encoding.
+
+..
+
+.. date: 2026-07-01-22-59-25
+.. gh-issue: 152586
+.. nonce: WuEae6
+.. section: Library
+
+:class:`!tempfile._TemporaryFileWrapper` has been renamed to the public
+:class:`tempfile.TemporaryFileWrapper`. The old private name is kept as a
+deprecated alias and will be removed in Python 3.21.
+
+..
+
+.. date: 2026-07-01-18-00-00
+.. gh-issue: 152721
+.. nonce: rlequad
+.. section: Library
+
+Fix quadratic replay time in the :mod:`profiling.sampling` binary reader
+when a profile's run-length-encoded samples alternate thread status.
+
+..
+
+.. date: 2026-07-01-15-30-00
+.. gh-issue: 77508
+.. nonce: Bn2kXt
+.. section: Library
+
+Add :meth:`imaplib.IMAP4.move`, a wrapper for the IMAP ``MOVE`` command
+(:rfc:`6851`), analogous to :meth:`~imaplib.IMAP4.copy`.
+
+..
+
+.. date: 2026-07-01-14-00-00
+.. gh-issue: 49680
+.. nonce: Lm5rQv
+.. section: Library
+
+Add the *translate_line_endings* parameter to :meth:`imaplib.IMAP4.append`.
+By default line endings in the message are translated to CRLF, as before;
+passing ``False`` sends the message literal exactly as given, preserving
+bare CR or LF octets.
+
+..
+
+.. date: 2026-07-01-12-00-00
+.. gh-issue: 152718
+.. nonce: pr0f1l
+.. section: Library
+
+Fix unbounded memory allocation in the :mod:`profiling.sampling` binary
+profile reader when a file declares more string or frame entries than it
+contains.
+
+..
+
+.. date: 2026-07-01-12-00-00
+.. gh-issue: 108280
+.. nonce: Nq8vTr
+.. section: Library
+
+Connecting :mod:`imaplib` to a server that does not send a valid IMAP4
+greeting (for example a POP3 server answering on the IMAP port) now raises
+an error reporting the server's response instead of ``imaplib.IMAP4.error:
+None``.
+
+..
+
+.. date: 2026-07-01-11-29-13
+.. gh-issue: 151126
+.. nonce: eElGy5
+.. section: Library
+
+Fix a crash caused by failing to set :exc:`MemoryError` on allocation
+failure when passing :class:`ctypes.Structure` or :class:`ctypes.Union`
+instances by value to ctypes foreign functions.
+
+..
+
+.. date: 2026-07-01-10-30-00
+.. gh-issue: 63121
+.. nonce: Rm4tZp
+.. section: Library
+
+:mod:`imaplib` now refreshes the cached capability list after a successful
+:meth:`~imaplib.IMAP4.login` or :meth:`~imaplib.IMAP4.authenticate`, using
+the ``CAPABILITY`` response sent by the server or, if none was sent, by
+querying it, so that capabilities that become available only after
+authentication (such as ``ENABLE`` on Gmail) are recognized. Capabilities
+advertised in the server greeting are now also used, avoiding a redundant
+``CAPABILITY`` command.
+
+..
+
+.. date: 2026-07-01-10-00-00
+.. gh-issue: 88574
+.. nonce: Kz3wQm
+.. section: Library
+
+:mod:`imaplib` no longer fails when a server sends a spurious blank line
+after the counted data of a literal, including after a literal that
+terminates a response (such as a mailbox name returned by ``LIST``). Such
+blank lines are now skipped without swallowing the following line.
+
+..
+
+.. date: 2026-06-30-15-00-00
+.. gh-issue: 152692
+.. nonce: tr3pr0
+.. section: Library
+
+Fix :func:`annotationlib.type_repr` returning a string such as
+``None.list.append`` for bound built-in methods, whose ``__module__`` is
+``None``. It now returns the qualified name, as it already did for other
+builtins.
+
+..
+
+.. date: 2026-06-30-14-30-00
+.. gh-issue: 152502
+.. nonce: Mq7Kx2
+.. section: Library
+
+Detect the :mod:`curses` mouse interface (:func:`~curses.getmouse`,
+:func:`~curses.has_mouse`, the ``BUTTON*`` constants, and others) and the
+window ``is_*`` state-query methods with configure capability probes or
+library macros instead of gating them on ncurses-specific macros. They are
+now also available with other curses implementations that provide them, such
+as NetBSD curses and PDCurses (the latter underpins ``windows-curses``).
+
+..
+
+.. date: 2026-06-30-13-00-00
+.. gh-issue: 151842
+.. nonce: OOM31g
+.. section: Library
+
+Fix a crash in :func:`!_interpreters.capture_exception` when
+:exc:`MemoryError` happens. Patch by Amrutha Modela.
+
+..
+
+.. date: 2026-06-30-12-00-00
+.. gh-issue: 40038
+.. nonce: qK7mGv
+.. section: Library
+
+:mod:`imaplib` now again quotes command arguments when necessary, for
+example mailbox names containing a space. Such quoting was inadvertently
+disabled when the module was ported to Python 3, and the arguments are now
+quoted according to the :rfc:`3501` grammar. For backward compatibility, an
+argument already enclosed in double quotes is left unchanged, so code that
+quotes arguments itself keeps working.
+
+..
+
+.. date: 2026-06-29-22-16-57
+.. gh-issue: 50966
+.. nonce: Tq5mLp
+.. section: Library
+
+Fix unbounded recursion in :mod:`turtle` when a mouse event handler that
+moves the turtle is reentered while the screen is being redrawn, for example
+with ``screen.ondrag(turtle.goto)``. This could previously crash the
+interpreter.
+
+..
+
+.. date: 2026-06-29-21-59-08
+.. gh-issue: 152638
+.. nonce: 92dpzo
+.. section: Library
+
+Deprecate :func:`tkinter.filedialog.askopenfiles`. Opening several files at
+once is error-prone and the returned list cannot be used in a
+:keyword:`with` statement; iterate over the names returned by
+:func:`tkinter.filedialog.askopenfilenames` and open them one by one
+instead.
+
+..
+
+.. date: 2026-06-29-12-50-28
+.. gh-issue: 152587
+.. nonce: Lq8wVn
+.. section: Library
+
+In :mod:`tkinter`, the *name* parameter of the
+:meth:`~tkinter.Misc.wait_variable`, :meth:`~tkinter.Misc.setvar` and
+:meth:`~tkinter.Misc.getvar` methods and the *value* parameter of
+:meth:`!setvar` are now required. Their former default values (``'PY_VAR'``
+and ``'1'``) were not meaningful.
+
+..
+
+.. date: 2026-06-29-09-45-00
+.. gh-issue: 152569
+.. nonce: Kf7Lq2
+.. section: Library
+
+Fix :func:`asyncio.wait` leaking waiting tasks via the await-graph when
+racing a future that never resolves. The waiting task is now discarded from
+every future's ``awaited_by`` set once :func:`~asyncio.wait` returns, even
+for pending futures.
+
+..
+
+.. date: 2026-06-29-01-08-53
+.. gh-issue: 110357
+.. nonce: QGWdZQ
+.. section: Library
+
+Importing :mod:`hashlib` no longer logs an error to stderr when a normally
+guaranteed hash algorithm is unavailable in the current runtime (for example
+under an OpenSSL FIPS configuration or a build using
+:option:`--without-builtin-hashlib-hashes <--with-builtin-hashlib-hashes>`).
+Code that actually uses the missing algorithm still gets a clear
+:exc:`ValueError`.
+
+..
+
+.. date: 2026-06-28-16-20-07
+.. gh-issue: 152503
+.. nonce: N55ose
+.. section: Library
+
+Fix :meth:`curses.window.in_wch`, :meth:`curses.window.in_wchstr` and
+:meth:`curses.window.getbkgrnd` returning garbage text when :mod:`curses` is
+built against a curses library that does not NUL-terminate the ``cchar_t``
+text array (such as NetBSD curses).
+
+..
+
+.. date: 2026-06-28-12-45-09
+.. gh-issue: 152356
+.. nonce: Dr4w2Q
+.. section: Library
+
+Fix a hang in ``profiling.sampling run --blocking`` on Windows when the
+target process exits. The profiler now finalizes binary profiles instead of
+continuing to sample the exited process.
+
+..
+
+.. date: 2026-06-28-12-00-00
+.. gh-issue: 152470
+.. nonce: Wn7Kp3
+.. section: Library
+
+The wide-character :mod:`curses` functions and methods
+:meth:`curses.window.get_wch`, :meth:`curses.window.get_wstr`,
+:func:`curses.unget_wch`, :func:`curses.erasewchar`,
+:func:`curses.killwchar` and :func:`curses.wunctrl` now also work when
+Python is not built against a wide-character-aware curses library, on an
+8-bit locale, where each character is a single byte in the relevant
+encoding. :func:`curses.ungetch` now also accepts a one-character string,
+like :func:`curses.unget_wch`; on a wide-character build it can be any
+character (previously a multibyte character raised :exc:`OverflowError`).
+
+..
+
+.. date: 2026-06-28-11-00-40
+.. gh-issue: 78335
+.. nonce: Kp3mWq
+.. section: Library
+
+Update the docstrings of :mod:`tkinter` and :mod:`tkinter.ttk` widget
+classes to list all supported widget options, including options added in Tk
+9.0 and 9.1. ``tkinter.Menubutton`` and ``tkinter.Message`` previously had
+no option list at all.
+
+..
+
+.. date: 2026-06-28-00-00-00
+.. gh-issue: 152431
+.. nonce: Ja3K9m
+.. section: Library
+
+Fix ``asyncio.StreamWriter.start_tls()`` to keep the linked ``StreamReader``
+transport in sync with the upgraded transport.
+
+..
+
+.. date: 2026-06-27-19-02-17
+.. gh-issue: 103878
+.. nonce: 216fa7
+.. section: Library
+
+The :mod:`tkinter.filedialog` functions that return a filename
+(:func:`~tkinter.filedialog.askopenfilename`,
+:func:`~tkinter.filedialog.asksaveasfilename` and
+:func:`~tkinter.filedialog.askdirectory`) now consistently return an empty
+string when the dialog is cancelled, instead of an empty tuple or ``b''`` on
+some platforms. :func:`~tkinter.filedialog.askopenfilenames` likewise
+always returns an empty tuple, and :func:`~tkinter.filedialog.askopenfiles`
+an empty list.
+
+..
+
+.. date: 2026-06-27-17-19-09
+.. gh-issue: 151126
+.. nonce: huUyOM
+.. section: Library
+
+Fix two crashes in :mod:`tkinter` and :mod:`socket` modules initialization
+under a memory pressure. Sets missing :exc:`MemoryError`.
+
+..
+
+.. date: 2026-06-27-12-45-00
+.. gh-issue: 133031
+.. nonce: Wide00
+.. section: Library
+
+:class:`curses.textpad.Textbox` now supports entering and reading back the
+full Unicode range, including combining characters, when curses is built
+with wide-character support.
+
+..
+
+.. date: 2026-06-27-12-30-00
+.. gh-issue: 133031
+.. nonce: Na8Bit
+.. section: Library
+
+:class:`curses.textpad.Textbox` now enters and reads back the non-ASCII
+characters of an 8-bit locale encoding, instead of mangling them with a
+7-bit mask.
+
+..
+
+.. date: 2026-06-27-12-00-00
+.. gh-issue: 43699
+.. nonce: Zt46MI
+.. section: Library
+
+The drag cursor in :mod:`tkinter.dnd` is now changed only once the pointer
+starts moving rather than on the initial button press, so that a plain click
+no longer flashes it.
+
+..
+
+.. date: 2026-06-27-11-32-37
+.. gh-issue: 50409
+.. nonce: Pw3Kq9
+.. section: Library
+
+Deprecate the *tagOrId* parameter of
+:meth:`!tkinter.PanedWindow.paneconfigure` (and its :meth:`!paneconfig`
+alias) in favor of *child*, for consistency with the other pane methods; it
+will be removed in Python 3.18.
+
+..
+
+.. date: 2026-06-27-10-30-00
+.. gh-issue: 152409
+.. nonce: Tr8cE2
+.. section: Library
+
+Fix the :mod:`trace` command-line tool not saving the ``--file`` counts when
+``--no-report`` is used, which prevented accumulating counts over several
+runs. Patch by tonghuaroot.
+
+..
+
+.. date: 2026-06-26-23-56-40
+.. gh-issue: 71880
+.. nonce: 782D31
+.. section: Library
+
+:class:`curses.textpad.Textbox` now lets the lower-right cell of the window
+be edited. Writing it with :meth:`~curses.window.addch` would move the
+cursor past the end of the window, raising an error and scrolling a
+scrollable window, so it is now written with :meth:`~curses.window.insch`,
+which keeps the cursor in place.
+
+..
+
+.. date: 2026-06-26-22-50-00
+.. gh-issue: 152334
+.. nonce: Mt7vQx
+.. section: Library
+
+Add the :func:`curses.define_key`, :func:`curses.key_defined` and
+:func:`curses.keyok` key-management functions.
+
+..
+
+.. date: 2026-06-26-22-15-00
+.. gh-issue: 152332
+.. nonce: Lp3WqN
+.. section: Library
+
+Add the :func:`curses.term_attrs` function, the counterpart of
+:func:`curses.termattrs` for the ``WA_*`` attributes.
+
+..
+
+.. date: 2026-06-26-22-06-07
+.. gh-issue: 87904
+.. nonce: F71C70
+.. section: Library
+
+The :mod:`curses` types and exceptions now report their public module in
+:attr:`~type.__module__`, :func:`repr` and :func:`help` -- for example
+``curses.window`` instead of ``_curses.window`` and ``curses.panel.error``
+instead of ``_curses_panel.error``.
+
+..
+
+.. date: 2026-06-26-21-30-00
+.. gh-issue: 152325
+.. nonce: Km9xQr
+.. section: Library
+
+Add the :func:`curses.has_mouse` function and the
+:meth:`curses.window.mouse_trafo` method.
+
+..
+
+.. date: 2026-06-26-19-01-13
+.. gh-issue: 121249
+.. nonce: p1SBW0
+.. section: Library
+
+Deprecate using ``'F'`` and ``'D'`` type codes in the :mod:`struct` module.
+
+..
+
+.. date: 2026-06-26-17-18-01
+.. gh-issue: 152275
+.. nonce: V64zKa
+.. section: Library
+
+The :mod:`curses` module now raises :exc:`OverflowError` instead of silently
+truncating an out-of-range value: :func:`curses.color_pair` rejects a color
+pair number that does not fit in the ``chtype`` color field, and the
+``attr`` argument of the character-cell and attribute methods
+(:meth:`~curses.window.addch`, :meth:`~curses.window.addstr`,
+:meth:`~curses.window.attron`, :meth:`~curses.window.attrset` and others) is
+checked against the ``chtype`` range.
+
+..
+
+.. date: 2026-06-26-16-30-00
+.. gh-issue: 83274
+.. nonce: Kx9mQv
+.. section: Library
+
+Deallocating a :mod:`tkinter` application from a thread other than the one
+it was created in no longer crashes the interpreter. The underlying Tcl
+interpreter is leaked instead, and a :exc:`RuntimeWarning` is reported.
+
+..
+
+.. date: 2026-06-26-16-15-55
+.. gh-issue: 81954
+.. nonce: MfUjgS
+.. section: Library
+
+Deleting a writable, open :class:`zipfile.ZipFile` now emits a
+:exc:`ResourceWarning`. Use as a :term:`context manager` or call
+:meth:`~zipfile.ZipFile.close` explicitly.
+
+..
+
+.. date: 2026-06-26-15-41-34
+.. gh-issue: 152305
+.. nonce: WnbbBc
+.. section: Library
+
+Fix the pure-Python :meth:`datetime.time.strftime` implementation raising
+:exc:`AttributeError` for the year directives. Patch by tonghuaroot.
+
+..
+
+.. date: 2026-06-26-15-30-00
+.. gh-issue: 88758
+.. nonce: Qw7nLp
+.. section: Library
+
+:meth:`!tkinter.Misc.focus_get`, :meth:`!focus_displayof`,
+:meth:`!focus_lastfor` and :meth:`!winfo_containing` now return ``None``
+instead of raising :exc:`KeyError` when the widget was not created by
+:mod:`tkinter` (for example a torn-off menu).
+
+..
+
+.. date: 2026-06-26-15-10-00
+.. gh-issue: 152260
+.. nonce: Rk4nP9
+.. section: Library
+
+Add the :mod:`curses` functions :func:`~curses.scr_dump`,
+:func:`~curses.scr_restore`, :func:`~curses.scr_init` and
+:func:`~curses.scr_set`, which dump the whole screen to a file and restore
+it.
+
+..
+
+.. date: 2026-06-26-15-00-00
+.. gh-issue: 38464
+.. nonce: yDPjKH
+.. section: Library
+
+:meth:`!tkinter.Misc.nametowidget` now resolves the auto-generated names of
+cloned menus (a menu used as a menubar or a cascade) back to the original
+widget.
+
+..
+
+.. date: 2026-06-26-14-34-28
+.. gh-issue: 152263
+.. nonce: 5PHQP4
+.. section: Library
+
+Add the soft-label-key functions to the :mod:`curses` module:
+:func:`~curses.slk_init`, :func:`~curses.slk_set`,
+:func:`~curses.slk_label`, :func:`~curses.slk_refresh`,
+:func:`~curses.slk_noutrefresh`, :func:`~curses.slk_clear`,
+:func:`~curses.slk_restore`, :func:`~curses.slk_touch`,
+:func:`~curses.slk_attron`, :func:`~curses.slk_attroff`,
+:func:`~curses.slk_attrset`, :func:`~curses.slk_attr`,
+:func:`~curses.slk_attr_on`, :func:`~curses.slk_attr_off`,
+:func:`~curses.slk_attr_set` and :func:`~curses.slk_color`.
+
+..
+
+.. date: 2026-06-26-14-05-00
+.. gh-issue: 116946
+.. nonce: Kp7raZ
+.. section: Library
+
+The internal :mod:`!_tkinter` ``tkapp`` and ``tktimertoken`` types now
+implement the garbage collector protocol, so reference cycles involving a
+Tcl interpreter or a timer handler can be collected.
+
+..
+
+.. date: 2026-06-26-13-40-00
+.. gh-issue: 152258
+.. nonce: Qe7Lm3
+.. section: Library
+
+Add the :mod:`curses` window method :meth:`~curses.window.dupwin`, which
+returns a new window that is an independent duplicate of an existing one.
+
+..
+
+.. date: 2026-06-26-13-39-11
+.. gh-issue: 152248
+.. nonce: N2Rmaf
+.. section: Library
+
+Make the C and pure-Python :mod:`zoneinfo` parsers validate POSIX TZ
+abbreviations consistently, rejecting unquoted abbreviations with non-letter
+characters and empty quoted abbreviations. Patch by tonghuaroot.
+
+..
+
+.. date: 2026-06-26-13-10-00
+.. gh-issue: 80937
+.. nonce: Hq3mNp
+.. section: Library
+
+Fix a memory leak in :mod:`tkinter` when a Tcl command created with
+``createcommand`` was not explicitly removed before the interpreter was
+deleted. The command no longer keeps the interpreter alive through a
+reference cycle.
+
+..
+
+.. date: 2026-06-26-13-00-46
+.. gh-issue: 111330
+.. nonce: DBcCXA
+.. section: Library
+
+Update pure-Python :class:`io.BytesIO` to close cleanly when the data has an
+export such as a :class:`memoryview`.
+
+..
+
+.. date: 2026-06-26-12-50-26
+.. gh-issue: 152246
+.. nonce: MfXMd1
+.. section: Library
+
+Fix the pure-Python :mod:`zoneinfo` parser accepting an invalid POSIX TZ
+transition rule with a non-period separator. Patch by tonghuaroot.
+
+..
+
+.. date: 2026-06-26-11-20-00
+.. gh-issue: 152233
+.. nonce: Kp7mQ2
+.. section: Library
+
+Add the :class:`curses.complexstr` type, an immutable string of styled
+character cells (the counterpart of :class:`curses.complexchar`), and the
+:mod:`curses` window method :meth:`~curses.window.in_wchstr` that returns
+one. The string-cell methods :meth:`~curses.window.addstr`,
+:meth:`~curses.window.addnstr`, :meth:`~curses.window.insstr` and
+:meth:`~curses.window.insnstr` now also accept a
+:class:`~curses.complexstr`. Like :class:`curses.complexchar`, it works
+whether or not Python was built against a wide-character-aware curses
+library.
+
+..
+
+.. date: 2026-06-25-22-41-49
+.. gh-issue: 152233
+.. nonce: pEhm3q
+.. section: Library
+
+Add the :class:`curses.complexchar` type, representing a styled character
+cell (text, attributes and color pair), and the :mod:`curses` window methods
+:meth:`~curses.window.in_wch` and :meth:`~curses.window.getbkgrnd` that
+return one. The character-cell methods (:meth:`~curses.window.addch`,
+:meth:`~curses.window.bkgd`, :meth:`~curses.window.border`,
+:meth:`~curses.window.hline` and others) now also accept a
+:class:`~curses.complexchar`. This works whether or not Python was built
+against a wide-character-aware curses library; on a narrow build a cell
+holds a single character representable as one byte in the window's encoding.
+
+..
+
+.. date: 2026-06-25-22-19-04
+.. gh-issue: 152099
+.. nonce: L7fKq9
+.. section: Library
+
+``asyncio``'s ``loop.sendfile(..., fallback=False)`` now consistently raises
+:exc:`asyncio.SendfileNotAvailableError` for fallback-only transports, such
+as SSL/TLS transports, when native sendfile cannot be used. Previously, this
+case raised :exc:`RuntimeError`.
+
+..
+
+.. date: 2026-06-25-20-00-00
+.. gh-issue: 151496
+.. nonce: kMnT3x
+.. section: Library
+
+Fixed ``profiling.sampling --gecko`` with ``--async-aware`` by flattening
+async task stacks before generating Gecko samples. ``--binary`` now rejects
+``--async-aware`` until the binary format supports async task data.
+
+..
+
+.. date: 2026-06-25-19-44-16
+.. gh-issue: 152219
+.. nonce: ndj4Ib
+.. section: Library
+
+Add the :mod:`curses` window methods :meth:`~curses.window.attr_get`,
+:meth:`~curses.window.attr_set`, :meth:`~curses.window.attr_on`,
+:meth:`~curses.window.attr_off` and :meth:`~curses.window.color_set`, which
+use a separate color pair argument instead of packing it into the attribute
+value, and the corresponding ``WA_*`` attribute constants.
+
+..
+
+.. date: 2026-06-25-14-32-43
+.. gh-issue: 139816
+.. nonce: Lq2vXa
+.. section: Library
+
+Fix a hang in :mod:`tkinter` on interactive Python built without
+:mod:`readline`. An exception raised in a callback no longer causes the
+event loop to stop and wait for the user to press Enter; pending callbacks
+now keep running until input is actually available on stdin.
+
+..
+
+.. date: 2026-06-25-14-32-42
+.. gh-issue: 139145
+.. nonce: kT9rmP
+.. section: Library
+
+Fix a busy loop in :mod:`tkinter` on interactive Python. When a Tcl command
+running its own event loop (such as ``vwait`` or :meth:`!wait_variable`) was
+active and input arrived on stdin, the event loop kept spinning at 100% CPU.
+The stdin file handler is now removed as soon as input is available. Based
+on a patch by Michiel de Hoon.
+
+..
+
+.. date: 2026-06-25-14-05-00
+.. gh-issue: 152204
+.. nonce: k9Qm3v
+.. section: Library
+
+Fix the pure-Python implementations of :meth:`datetime.date.fromisoformat`,
+:meth:`datetime.time.fromisoformat` and
+:meth:`datetime.datetime.fromisoformat` silently accepting some malformed
+ISO 8601 strings, such as non-ASCII digits or a sign in a fixed-width field
+(for example ``'2020+12'`` or ``'20201212T0102٣٤'``). Each field is now
+required to be exactly *N* ASCII digits, matching the C implementation.
+
+..
+
+.. date: 2026-06-25-12-00-00
+.. gh-issue: 152212
+.. nonce: Zk7Qm2
+.. section: Library
+
+Fix the pure-Python :mod:`zoneinfo` parser accepting a POSIX TZ string with
+a ``std`` abbreviation but no offset. This is invalid per POSIX and now
+raises :exc:`ValueError`, matching the C accelerator. Patch by tonghuaroot.
+
+..
+
+.. date: 2026-06-25-10-07-54
+.. gh-issue: 152156
+.. nonce: gscPU9
+.. section: Library
+
+Fix a possible crash in :func:`concurrent.interpreters.create` under limited
+memory conditions.
+
+..
+
+.. date: 2026-06-25-07-08-17
+.. gh-issue: 152157
+.. nonce: dt5Ef0
+.. section: Library
+
+The C implementations of :meth:`~datetime.datetime.fromisoformat` and
+:meth:`~datetime.time.fromisoformat` now reject a decimal separator that is
+not followed by any fractional digit before a timezone designator.
+
+..
+
+.. date: 2026-06-25-01-00-43
+.. gh-issue: 151763
+.. nonce: wWeHBe
+.. section: Library
+
+Fix crash in :func:`!_interpqueues.create` whe :exc:`MemoryError` happens on
+queue creation.
+
+..
+
+.. date: 2026-06-24-23-28-42
+.. gh-issue: 151669
+.. nonce: tPUavQ
+.. section: Library
+
+On Windows, when populating tar archives from filesystem content, to conform
+to the tar format standard, backslashes in symlink targets are be replaced
+by slashes.
+
+..
+
+.. date: 2026-06-24-22-16-35
+.. gh-issue: 105895
+.. nonce: hRkuEw
+.. section: Library
+
+Add :keyword:`match` and :keyword:`case` to the list of supported topics by
+:func:`help`.
+
+..
+
+.. date: 2026-06-24-16-40-15
+.. gh-issue: 151378
+.. nonce: iYWa_6
+.. section: Library
+
+Fix a bug in the binary collector in Tachyon that caused unbounded memory
+growth while profiling a thread that stayed asleep. Patch by Maurycy
+Pawłowski-Wieroński.
+
+..
+
+.. date: 2026-06-24-16-08-44
+.. gh-issue: 152074
+.. nonce: PsbS-I
+.. section: Library
+
+Increase the buffer size to 256 KiB in :meth:`asyncio.loop.sendfile` method
+fallback.
+
+..
+
+.. date: 2026-06-24-12-00-00
+.. gh-issue: 152100
+.. nonce: Set0ps
+.. section: Library
+
+Support set operations and nested sets in regular expression character
+classes, as described in Unicode Technical Standard #18: set difference
+(``[A--B]``), intersection (``[A&&B]``) and union (``[A||B]``).
+
+..
+
+.. date: 2026-06-24-12-00-00
+.. gh-issue: 152079
+.. nonce: f1tzus
+.. section: Library
+
+Fix :meth:`datetime.datetime.fromisoformat` in the C implementation dropping
+the sub-second part of a UTC offset whose whole-second part is zero,
+matching the pure-Python implementation.
+
+..
+
+.. date: 2026-06-24-12-00-00
+.. gh-issue: 152052
+.. nonce: yBssDE
+.. section: Library
+
+The :mod:`json` C accelerator now correctly reports an unterminated string
+for a ``\uXXXX`` escape at the end of the input.
+
+..
+
+.. date: 2026-06-24-10-46-35
+.. gh-issue: 152060
+.. nonce: f2asrt
+.. section: Library
+
+Fix :meth:`datetime.datetime.fromisoformat` raising :exc:`AssertionError`
+instead of :exc:`ValueError` for some malformed strings in the pure-Python
+implementation, matching the C implementation.
+
+..
+
+.. date: 2026-06-24-10-30-00
+.. gh-issue: 152056
+.. nonce: Qk7mZ2
+.. section: Library
+
+Optimize matching of a character set that contains a single character
+category, such as ``[\d]`` or ``[^\s]``: it is now compiled to a single
+``CATEGORY`` opcode, the same as the corresponding ``\d`` or ``\S`` escape,
+instead of being wrapped in an ``IN`` block. This speeds up matching and
+reduces the size of the compiled byte code. Patch by Pieter Eendebak.
+
+..
+
+.. date: 2026-06-23-22-15-00
+.. gh-issue: 152033
+.. nonce: Ct1Egy
+.. section: Library
+
+Optimize matching of character class escapes (``\d``, ``\D``, ``\s``,
+``\S``, ``\w`` and ``\W``) that occur outside a character set: they are now
+compiled to a single ``CATEGORY`` opcode instead of being wrapped in an
+``IN`` block. This speeds up patterns such as ``\d+`` and reduces the size
+of the compiled byte code.
+
+..
+
+.. date: 2026-06-23-18-42-37
+.. gh-issue: 143990
+.. nonce: o65v7O
+.. section: Library
+
+:class:`tkinter.font.Font` can now wrap a font description without creating
+a new named font, by passing it as *font* with ``exists=True`` and no
+*name*. This avoids a loss of precision in
+:meth:`~tkinter.font.Font.actual`, :meth:`~tkinter.font.Font.measure` and
+:meth:`~tkinter.font.Font.metrics`. Keyword options now override the
+corresponding settings of the given *font* instead of being ignored.
+
+..
+
+.. date: 2026-06-23-17-14-04
+.. gh-issue: 127802
+.. nonce: nGSxo6
+.. section: Library
+
+The deprecated :class:`tkinter.Variable` methods :meth:`!trace_variable`,
+:meth:`!trace`, :meth:`!trace_vdelete` and :meth:`!trace_vinfo` are now
+scheduled for removal in Python 3.17.
+
+..
+
+.. date: 2026-06-23-13-27-14
+.. gh-issue: 126219
+.. nonce: kOfv2g
+.. section: Library
+
+Fixed a crash in :class:`tkinter.Tk` when *className* contains a non-BMP
+character and tkinter is built against Tcl/Tk 8.x. Such a name is now
+rejected with a :exc:`ValueError`.
+
+..
+
+.. date: 2026-06-23-12-00-00
+.. gh-issue: 101284
+.. nonce: Ab3Xy9
+.. section: Library
+
+:class:`tkinter.OptionMenu` now accepts arbitrary
+:class:`!tkinter.Menubutton` options as keyword arguments and uses them to
+override its default appearance.
+
+..
+
+.. date: 2026-06-23-11-00-03
+.. gh-issue: 143070
+.. nonce: fV5w7s
+.. section: Library
+
+Automatically generated :mod:`tkinter` widget names now start with ``"+"``
+instead of ``"!"``, so that they can be used as tags in the
+:class:`!tkinter.Canvas` and :class:`!tkinter.Text` widgets.
+
+..
+
+.. date: 2026-06-22-18-01-00
+.. gh-issue: 151955
+.. nonce: 6u5iwm
+.. section: Library
+
+Allow more types to be used in the ``bound`` argument to
+:class:`typing.ParamSpec` and :class:`typing.TypeVarTuple`.
+
+..
+
+.. date: 2026-06-22-14-30-00
+.. gh-issue: 151920
+.. nonce: Th3mSt
+.. section: Library
+
+Add the :meth:`ttk.Style.theme_styles `
+method, wrapping the Tk ``ttk::style theme styles`` subcommand, which
+returns the list of styles defined in a theme.
+
+..
+
+.. date: 2026-06-22-12-00-00
+.. gh-issue: 95555
+.. nonce: Pr0p18
+.. section: Library
+
+Regular expressions now support Unicode property escapes ``\p{...}`` and
+``\P{...}`` for properties that the engine can resolve without the
+unicodedata database: many ``General_Category`` values, a number of binary
+properties, the POSIX compatibility classes, and properties derivable from
+the code point.
+
+..
+
+.. date: 2026-06-22-10-30-22
+.. gh-issue: 151910
+.. nonce: ayi8xK
+.. section: Library
+
+Added :class:`tkinter.ttk.Treeview` methods wrapping the enhanced
+``ttk::treeview`` widget commands added in Tk 9.1 (and the ``detached``
+query added in Tk 9.0): item navigation and queries, opening, hiding,
+sorting and searching of items, and cell focus, selection and tagging. The
+:meth:`~tkinter.ttk.Treeview.expand` and
+:meth:`~tkinter.ttk.Treeview.collapse` methods (without recursion) also work
+on Tk older than 9.1.
+
+..
+
+.. date: 2026-06-22-02-29-02
+.. gh-issue: 151890
+.. nonce: gT6JwI
+.. section: Library
+
+Add the *format* parameter to the :meth:`tkinter.PhotoImage.put` method, the
+*metadata* parameter to the :meth:`~tkinter.PhotoImage.put`,
+:meth:`~tkinter.PhotoImage.read`, :meth:`~tkinter.PhotoImage.write` and
+:meth:`~tkinter.PhotoImage.data` methods, and the *withalpha* parameter to
+the :meth:`~tkinter.PhotoImage.get` method. The *metadata* and *withalpha*
+parameters require Tcl/Tk 9.0 or newer.
+
+..
+
+.. date: 2026-06-22-01-57-55
+.. gh-issue: 151888
+.. nonce: hO7mxi
+.. section: Library
+
+Add the :meth:`!tkinter.PhotoImage.redither` method, wrapping the photo
+image ``redither`` Tk command.
+
+..
+
+.. date: 2026-06-22-01-51-06
+.. gh-issue: 151886
+.. nonce: MsLlNz
+.. section: Library
+
+Add the :meth:`!tkinter.Misc.tk_appname`,
+:meth:`!tkinter.Misc.tk_useinputmethods` and :meth:`!tkinter.Misc.tk_caret`
+methods, wrapping the ``tk appname``, ``tk useinputmethods`` and ``tk
+caret`` Tk commands.
+
+..
+
+.. date: 2026-06-22-01-39-38
+.. gh-issue: 151881
+.. nonce: ShACSZ
+.. section: Library
+
+Add the :meth:`tkinter.Menu.postcascade` method and the
+:meth:`!tkinter.Misc.tk_scaling` and :meth:`!tkinter.Misc.tk_inactive`
+methods, wrapping the ``postcascade``, ``tk scaling`` and ``tk inactive`` Tk
+commands.
+
+..
+
+.. date: 2026-06-22-01-02-33
+.. gh-issue: 151878
+.. nonce: IFIA5C
+.. section: Library
+
+Add the :meth:`!validate` method to the :class:`tkinter.Entry` and
+:class:`tkinter.Spinbox` widgets, forcing an evaluation of the validation
+command.
+
+..
+
+.. date: 2026-06-22-00-55-07
+.. gh-issue: 151876
+.. nonce: sVe0xx
+.. section: Library
+
+Add the :class:`tkinter.Canvas` methods :meth:`!rchars` and :meth:`!rotate`,
+wrapping the ``rchars`` and ``rotate`` Tk canvas commands.
+
+..
+
+.. date: 2026-06-22-00-46-57
+.. gh-issue: 151874
+.. nonce: 8VtTrq
+.. section: Library
+
+Add the :mod:`tkinter` methods :meth:`!Misc.winfo_isdark`,
+:meth:`!Wm.wm_iconbadge` and :meth:`!Wm.wm_stackorder`, wrapping the ``winfo
+isdark``, ``wm iconbadge`` and ``wm stackorder`` Tk commands.
+
+..
+
+.. date: 2026-06-21-23-17-12
+.. gh-issue: 59396
+.. nonce: Fd9Tk2
+.. section: Library
+
+The :class:`!tkinter.filedialog.FileDialog` dialog and its
+:class:`!tkinter.filedialog.LoadFileDialog` and
+:class:`!tkinter.filedialog.SaveFileDialog` subclasses, which follow the
+layout of the classic Motif file selection dialog, were modernized to match
+its look and feel more closely. They are now built from the themed
+:mod:`tkinter.ttk` widgets instead of the classic :mod:`tkinter` widgets,
+and gained a *use_ttk* parameter that selects between the classic Tk widgets
+and the themed ttk widgets. The buttons and field labels gained :kbd:`Alt`
+key accelerators, the default ring follows the keyboard focus, and the
+:kbd:`Escape` key cancels the dialog. The directory and file lists gained a
+horizontal scrollbar and type-ahead selection. The dialog is now centered
+over its parent, and the overwrite confirmation of :class:`!SaveFileDialog`
+uses a themed message box.
+
+..
+
+.. date: 2026-06-21-15-50-24
+.. gh-issue: 86165
+.. nonce: dyac1G
+.. section: Library
+
+Fix :func:`imaplib.Time2Internaldate` to use the local timezone offset for
+``time.struct_time`` values with ``tm_gmtoff`` set to ``None``, as returned
+by ``datetime.datetime.timetuple()``. Contributed by Xiao Yuan.
+
+..
+
+.. date: 2026-06-21-00-00-57
+.. gh-issue: 151822
+.. nonce: bOC2G56F
+.. section: Library
+
+Colorize ``exit``, ``quit``, ``copyright``, ``help``, and ``clear`` as
+commands in the :term:`REPL` when typed alone on a line. Patch by Bartosz
+Sławecki.
+
+..
+
+.. date: 2026-06-20-22-55-22
+.. gh-issue: 59396
+.. nonce: kT9wPq
+.. section: Library
+
+The :mod:`tkinter.simpledialog` dialogs were modernized to match the look
+and feel of the native Tk dialogs.
+:class:`!tkinter.simpledialog.SimpleDialog` and the
+:func:`~tkinter.simpledialog.askinteger`,
+:func:`~tkinter.simpledialog.askfloat` and
+:func:`~tkinter.simpledialog.askstring` dialogs are now built from the
+themed :mod:`tkinter.ttk` widgets instead of the classic :mod:`tkinter`
+widgets; the :class:`!tkinter.simpledialog.Dialog` base class still defaults
+to the classic widgets for compatibility. Both :class:`!Dialog` and
+:class:`!SimpleDialog` gained a *use_ttk* parameter that selects between the
+classic Tk widgets and the themed ttk widgets. :class:`!SimpleDialog` also
+gained *bitmap* and *detail* parameters, draws the standard icons with
+themed images in the ttk version, and accepts mappings of button options as
+*buttons* entries, where an ``underline`` option adds an :kbd:`Alt` key
+accelerator. The font and wrap length of the message and the detail message
+are taken from the Tk option database and can be overridden by the
+application. The dialogs also follow the keyboard conventions of the Tk
+message box: the default ring follows the keyboard focus, the Return key
+activates the focused button, and the :class:`!Dialog` OK and Cancel buttons
+gained :kbd:`Alt` key accelerators. Several bugs were also fixed.
+
+..
+
+.. date: 2026-06-20-21-15-13
+.. gh-issue: 151814
+.. nonce: OIbgsO
+.. section: Library
+
+Fix unbounded memory growth in :class:`io.TextIOWrapper` when repeatedly
+writing an empty string.
+
+..
+
+.. date: 2026-06-20-20-24-03
+.. gh-issue: 133998
+.. nonce: nkqhMz
+.. section: Library
+
+Fix :func:`tarfile.open` in streaming write mode (``w|gz``) raising
+:exc:`struct.error` when given an *mtime* outside the range of the gzip
+header's 32-bit timestamp field. Out-of-range values are now stored as
+``0``, matching :mod:`gzip`.
+
+..
+
+.. date: 2026-06-20-15-00-00
+.. gh-issue: 75666
+.. nonce: Kt9xQ2
+.. section: Library
+
+Fix a reference leak in :mod:`tkinter`: the Tcl commands created for event
+callbacks are now deleted when a binding is replaced or unbound.
+
+..
+
+.. date: 2026-06-20-15-00-00
+.. gh-issue: 151770
+.. nonce: dtiso0
+.. section: Library
+
+Fix :meth:`datetime.datetime.fromisoformat` raising :exc:`AssertionError`
+instead of :exc:`ValueError` for an out-of-range month combined with a
+``24:00`` time.
+
+..
+
+.. date: 2026-06-20-12-10-02
+.. gh-issue: 151776
+.. nonce: BtsXIF
+.. section: Library
+
+Add :mod:`curses` functions and window methods that report state which could
+previously only be set: the window methods
+:meth:`~curses.window.is_cleared`, :meth:`~curses.window.is_idcok`,
+:meth:`~curses.window.is_idlok`, :meth:`~curses.window.is_immedok`,
+:meth:`~curses.window.is_keypad`, :meth:`~curses.window.is_leaveok`,
+:meth:`~curses.window.is_nodelay`, :meth:`~curses.window.is_notimeout`,
+:meth:`~curses.window.is_pad`, :meth:`~curses.window.is_scrollok`,
+:meth:`~curses.window.is_subwin`, :meth:`~curses.window.is_syncok`,
+:meth:`~curses.window.getdelay`, :meth:`~curses.window.getparent` and
+:meth:`~curses.window.getscrreg`, and the functions
+:func:`curses.is_cbreak`, :func:`curses.is_echo`, :func:`curses.is_nl` and
+:func:`curses.is_raw`. They are only available when built against an
+ncurses with ``NCURSES_EXT_FUNCS``.
+
+..
+
+.. date: 2026-06-20-11-11-22
+.. gh-issue: 151774
+.. nonce: O6nrvs
+.. section: Library
+
+Add the :mod:`curses` functions :func:`curses.alloc_pair`,
+:func:`curses.find_pair`, :func:`curses.free_pair` and
+:func:`curses.reset_color_pairs` for dynamic color-pair management. They
+are only available when Python is built against a wide-character version of
+the underlying curses library with extended-color support.
+
+..
+
+.. date: 2026-06-20-02-14-55
+.. gh-issue: 151757
+.. nonce: TP9A2x
+.. section: Library
+
+The :mod:`curses` character-cell window methods now accept a full character
+cell -- a spacing character optionally followed by combining characters --
+in addition to a single integer or byte character. Add the wide-character
+read methods :meth:`curses.window.get_wstr` and
+:meth:`curses.window.in_wstr`, and the functions :func:`curses.erasewchar`,
+:func:`curses.killwchar` and :func:`curses.wunctrl`. On a narrow
+(non-ncursesw) build the character cell holds a single character without
+combining marks, representable as one byte in the window's encoding, and
+:meth:`curses.window.in_wstr` returns its decoded text.
+
+..
+
+.. date: 2026-06-19-18-40-00
+.. gh-issue: 151744
+.. nonce: Kp7mNq
+.. section: Library
+
+Add :func:`curses.nofilter`, which undoes the effect of
+:func:`curses.filter`.
+
+..
+
+.. date: 2026-06-19-12-19-30
+.. gh-issue: 90092
+.. nonce: yBVc0C
+.. section: Library
+
+Add support for multiple terminals to the :mod:`curses` module: the new
+functions :func:`curses.newterm`, :func:`curses.set_term` and
+:func:`curses.new_prescr`, the corresponding :ref:`screen
+` object, and the :meth:`curses.window.use` method.
+
+..
+
+.. date: 2026-06-19-12-00-01
+.. gh-issue: 151675
+.. nonce: acLD7L
+.. section: Library
+
+Add the :meth:`~tkinter.Text.sync` and :meth:`~tkinter.Text.pendingsync`
+methods of :class:`!tkinter.Text`, wrapping the Tk ``sync`` and
+``pendingsync`` subcommands.
+
+..
+
+.. date: 2026-06-19-12-00-00
+.. gh-issue: 151674
+.. nonce: FCYTvs
+.. section: Library
+
+Add the :meth:`~tkinter.Text.edit_canundo` and
+:meth:`~tkinter.Text.edit_canredo` methods of :class:`!tkinter.Text`,
+wrapping the Tk ``edit canundo`` and ``edit canredo`` subcommands.
+
+..
+
+.. date: 2026-06-19-08-30-00
+.. gh-issue: 151627
+.. nonce: xY7kLm
+.. section: Library
+
+Fix a crash in :class:`collections.OrderedDict` iterators in free-threaded
+builds when the dictionary is concurrently cleared or updated.
+
+..
+
+.. date: 2026-06-19-07-26-20
+.. gh-issue: 151695
+.. nonce: IBDlkN
+.. section: Library
+
+Fix a use-after-free in the :mod:`curses` module. The encoding of the
+initial screen, used by :func:`curses.unctrl` and :func:`curses.ungetch` to
+encode non-ASCII characters, is now kept as a private copy instead of a
+borrowed pointer to a window object that may be deallocated.
+
+..
+
+.. date: 2026-06-18-23-59-46
+.. gh-issue: 151596
+.. nonce: 5ma144
+.. section: Library
+
+Add missing ``size`` positional argument to the pure-Python implementation
+of :meth:`io.TextIOBase.readline`.
+
+..
+
+.. date: 2026-06-18-12-48-03
+.. gh-issue: 151640
+.. nonce: R4c3Fx
+.. section: Library
+
+Fix a data race in :class:`io.BytesIO` in free-threaded builds when
+whole-buffer reads or peeks, or :meth:`~io.BytesIO.getvalue`, share the
+internal buffer with concurrent writes.
+
+..
+
+.. date: 2026-06-18-00-39-58
+.. gh-issue: 151615
+.. nonce: PBsCE1
+.. section: Library
+
+Fix :mod:`asyncio` servers repeatedly logging and rescheduling on a single
+event loop iteration when ``accept()`` fails with a resource errors.
+
+..
+
+.. date: 2026-06-17-22-31-57
+.. gh-issue: 151613
+.. nonce: n0nua1
+.. section: Library
+
+Fix another way the Tachyon profiler frame cache could produce impossible
+mixed stack traces when ``_PyInterpreterFrame`` addresses are reused, by
+validating cached frame anchors with a sequence counter.
+
+..
+
+.. date: 2026-06-17-00-00-00
+.. gh-issue: 148660
+.. nonce: odcopy
+.. section: Library
+
+Fix a crash in :meth:`!collections.OrderedDict.copy` when a key's ``__eq__``
+or a subclass method mutates the dict during the copy. Now raises
+:exc:`RuntimeError` instead, as iteration does.
+
+..
+
+.. date: 2026-06-15-15-32-36
+.. gh-issue: 151497
+.. nonce: 1cfmSV
+.. section: Library
+
+Opening a :mod:`tarfile` archive no longer attempts to pre-allocate a huge
+buffer when a crafted or truncated member claims an oversized extended
+header (a GNU long name/link or a pax header). The extended header is now
+read in bounded chunks, so its size field can no longer trigger memory
+exhaustion.
+
+..
+
+.. date: 2026-06-15-07-42-12
+.. gh-issue: 151485
+.. nonce: NiYQPZ
+.. section: Library
+
+Fix command quoting in :exc:`subprocess.CalledProcessError`. Contributed by
+Benjy Wiener.
+
+..
+
+.. date: 2026-06-13-11-57-48
+.. gh-issue: 151436
+.. nonce: UEDowO
+.. section: Library
+
+Fix skewed stack traces in the Tachyon profiler when caching is enabled and
+when generators and coroutines are profiled, by updating
+``tstate->last_profiled_frame`` at every frame-removal site. The issue
+resulted in total erasure of some callers. Patch by Maurycy
+Pawłowski-Wieroński.
+
+..
+
+.. date: 2026-06-13-04-11-00
+.. gh-issue: 151426
+.. nonce: f2V67e
+.. section: Library
+
+Fix impossible stack traces (callers and callees cross called, orphans and
+incorrect lines) in the Tachyon profiler when caching frames, by
+snapshotting the stack chunks before walking the frame chain on a cache
+miss. Patch by Maurycy Pawłowski-Wieroński.
+
+..
+
+.. date: 2026-06-12-22-46-31
+.. gh-issue: 151403
+.. nonce: DalZWh
+.. section: Library
+
+Fixed a crash in :class:`subprocess.Popen` (and
+``_posixsubprocess.fork_exec``) when an ``argv`` item's
+:meth:`~os.PathLike.__fspath__` concurrently mutates the ``args`` sequence
+being converted.
+
+..
+
+.. date: 2026-06-12-07-20-08
+.. gh-issue: 151390
+.. nonce: CmYN9EeJ
+.. section: Library
+
+Colorize ``match`` in the :term:`REPL` when followed by a unary ``+`` or
+``-`` operator. Patch by Bartosz Sławecki.
+
+..
+
+.. date: 2026-06-12-00-17-29
+.. gh-issue: 151128
+.. nonce: -LYO3a
+.. section: Library
+
+Cross-language keyword suggestions are now shown for :exc:`SyntaxError`
+messages. For example, ``switch x:`` suggests ``match``, ``delete x``
+suggests ``del``, ``function f():`` suggests ``def``. Contributed by Zang
+Langyan.
+
+..
+
+.. date: 2026-06-12-00-04-34
+.. gh-issue: 151126
+.. nonce: aHaBYq
+.. section: Library
+
+Fix crash on unset :exc:`MemoryError` on allocation failure in
+:func:`ctypes.get_errno`.
+
+..
+
+.. date: 2026-06-12-00-00-00
+.. gh-issue: 151416
+.. nonce: spawnUA
+.. section: Library
+
+Fix a crash in :func:`os.spawnv` and :func:`os.spawnve` when an *argv*
+item's :meth:`~os.PathLike.__fspath__` method mutates the *argv* list during
+argument conversion. :func:`!os.spawnv` argument conversion errors other
+than :exc:`TypeError`, such as the :exc:`ValueError` for an embedded null,
+are no longer replaced with a generic :exc:`TypeError`.
+
+..
+
+.. date: 2026-06-11-21-43-24
+.. gh-issue: 151337
+.. nonce: JSVV18
+.. section: Library
+
+Avoid possible memory leak in ``tkinter.c`` on Windows.
+
+..
+
+.. date: 2026-06-11-19-46-16
+.. gh-issue: 150285
+.. nonce: wuhAsL
+.. section: Library
+
+:mod:`pydoc` now uses all available space (80 columns) for formatting reprs
+of module and class data, but ensure that they do not overflow.
+
+..
+
+.. date: 2026-06-11-16-25-38
+.. gh-issue: 151126
+.. nonce: bh_Usy
+.. section: Library
+
+Fix a crash when :exc:`MemoryError` in :func:`!os._path_splitroot` was not
+set properly.
+
+..
+
+.. date: 2026-06-11-11-52-23
+.. gh-issue: 149671
+.. nonce: 6Rpr5r
+.. section: Library
+
+Restore compatibility with setuptools ``-nspkg.pth`` files in the
+:mod:`site` module. Inject ``sitedir`` variable in the frame which executes
+pth code. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-06-11-10-00-00
+.. gh-issue: 119710
+.. nonce: Qz7Kp2
+.. section: Library
+
+Fix :mod:`asyncio` subprocess :meth:`~asyncio.subprocess.Process.wait`
+hanging when the process has exited but one of its pipes is kept open by an
+inherited child process (so the pipe never reaches EOF). ``wait()`` now
+returns as soon as the process exits, regardless of the pipes' state.
+
+..
+
+.. date: 2026-06-11-00-00-00
+.. gh-issue: 151295
+.. nonce: NQYUzW
+.. section: Library
+
+Fixed a crash (use-after-free) in :meth:`bytes.join` and
+:meth:`bytearray.join` that could occur if an item's
+:meth:`~object.__buffer__` concurrently mutates the sequence being joined.
+The mutation is now reported as a :exc:`RuntimeError` instead.
+
+..
+
+.. date: 2026-06-10-00-00-02
+.. gh-issue: 109940
+.. nonce: Cx1099
+.. section: Library
+
+Fix Windows :mod:`venv` activation in ``cmd.exe`` to respect
+``VIRTUAL_ENV_DISABLE_PROMPT``.
+
+..
+
+.. date: 2026-06-10-00-00-01
+.. gh-issue: 117807
+.. nonce: Cx1178
+.. section: Library
+
+Fix :mod:`mimetypes` initialization from MIME map files containing invalid
+UTF-8 bytes.
+
+..
+
+.. date: 2026-06-09-19-43-24
+.. gh-issue: 151179
+.. nonce: hl_6Z0
+.. section: Library
+
+Fix a pidfd leak in ``_PidfdChildWatcher`` on Linux: the watcher no longer
+leaks the process file descriptor when ``waitpid()`` fails with an error
+other than :exc:`ChildProcessError`.
+
+..
+
+.. date: 2026-06-09-14-49-17
+.. gh-issue: 80384
+.. nonce: ttRAja
+.. section: Library
+
+:func:`weakref.ref` and :func:`weakref.proxy` now raise :exc:`TypeError` if
+the *callback* argument is not callable or ``None``.
+
+..
+
+.. date: 2026-06-09-12-00-00
+.. gh-issue: 150771
+.. nonce: K7mNx2
+.. section: Library
+
+Fix :mod:`email` messages created with ``shift_jis`` or ``euc-jp`` charsets.
+``set_content()`` now stores the payload using the output charset
+(``iso-2022-jp``) so printing the message no longer raises
+:exc:`UnicodeEncodeError`.
+
+..
+
+.. date: 2026-06-08-15-04-35
+.. gh-issue: 150285
+.. nonce: -Tj94n
+.. section: Library
+
+:mod:`pydoc` now wraps long single-line summary in text output.
+
+..
+
+.. date: 2026-06-07-23-30-34
+.. gh-issue: 151049
+.. nonce: mBlToO
+.. section: Library
+
+:mod:`ipaddress`: fix ``is_global`` and ``is_private`` for the
+``2001:1::3/128`` (DNS-SD Service Registration Protocol Anycast) address,
+which IANA registered as globally reachable per :rfc:`9665`. It is now
+correctly reported with ``is_global`` ``True`` and ``is_private`` ``False``.
+
+..
+
+.. date: 2026-06-07-17-29-33
+.. gh-issue: 151039
+.. nonce: AZ0qBn
+.. section: Library
+
+Fix a crash when static :mod:`datetime` types outlive the ``_datetime``
+module.
+
+..
+
+.. date: 2026-06-07-13-47-05
+.. gh-issue: 151042
+.. nonce: NMdzF2
+.. section: Library
+
+Fixed venv exporting mixed path styles to PATH on Windows inside fish (via
+Cygwin, MinGW or MSYS2)
+
+..
+
+.. date: 2026-06-06-15-20-54
+.. gh-issue: 151021
+.. nonce: J4qk2A
+.. section: Library
+
+Fix :meth:`mmap.mmap.find` and :meth:`~mmap.mmap.rfind` to return ``-1``
+when searching for an empty subsequence with a start position past the end
+of the mapping.
+
+..
+
+.. date: 2026-06-06-15-04-37
+.. gh-issue: 151022
+.. nonce: 1Aw8Tk
+.. section: Library
+
+Fix ``_remote_debugging`` stack traces for code objects with large line
+tables.
+
+..
+
+.. date: 2026-06-06-06-29-17
+.. gh-issue: 150994
+.. nonce: I2119M
+.. section: Library
+
+Make the type annotations in the private ``_colorize`` module resolvable.
+
+..
+
+.. date: 2026-06-05-16-57-03
+.. gh-issue: 143768
+.. nonce: RbLnkFx
+.. section: Library
+
+:mod:`venv`: Replace a dangling interpreter symlink in an existing virtual
+environment instead of failing or silently leaving it broken. Fix by Clay
+Dugo.
+
+..
+
+.. date: 2026-06-04-23-10-31
+.. gh-issue: 62825
+.. nonce: BtG_yQ
+.. section: Library
+
+Encodings "KS_C_5601-1987", "KS X 1001", etc are now aliases of "CP949"
+instead of "EUC-KR".
+
+..
+
+.. date: 2026-06-04-21-49-18
+.. gh-issue: 150913
+.. nonce: EmptyBl
+.. section: Library
+
+Fix :class:`sqlite3.Blob` slice assignment to raise :exc:`TypeError` and
+:exc:`IndexError` for type and size mismatches respectively, even when the
+target slice is empty.
+
+..
+
+.. date: 2026-06-04-19-24-13
+.. gh-issue: 140006
+.. nonce: TD8HKl
+.. section: Library
+
+The :mod:`venv` ``activate.fish`` script now calls fish builtins through
+``builtin`` so a user function that shadows ``.``/``source``, ``echo``,
+``printf``, ``set_color``, or ``functions`` can no longer hijack the virtual
+environment prompt or break exit-status reporting.
+
+..
+
+.. date: 2026-06-04-18-22-56
+.. gh-issue: 143008
+.. nonce: z5tw-J
+.. section: Library
+
+Fix race conditions when re-initializing a :class:`io.TextIOWrapper` object.
+
+..
+
+.. date: 2026-06-04-10-44-36
+.. gh-issue: 150889
+.. nonce: UYNLR_
+.. section: Library
+
+Speed up :func:`unicodedata.normalize` for the NFC and NFKC forms of
+non-ASCII text up to a factor 2.
+
+..
+
+.. date: 2026-06-04-06-50-06
+.. gh-issue: 150898
+.. nonce: 1LkLA3
+.. section: Library
+
+Unconditionally assume :attr:`ssl.SSLContext.keylog_filename` exists.
+
+..
+
+.. date: 2026-06-03-21-59-11
+.. gh-issue: 150886
+.. nonce: r2c25g
+.. section: Library
+
+Remove the private, undocumented function
+``importlib._bootstrap._object_name()``. It had no caller after
+``load_module()`` and its deprecation warnings were removed from
+:mod:`importlib`.
+
+..
+
+.. date: 2026-06-03-19-35-32
+.. gh-issue: 150583
+.. nonce: dedI24
+.. section: Library
+
+Correctly set the default compression level in :mod:`compression.zstd` when
+passing a digested dictionary during compression.
+
+..
+
+.. date: 2026-06-03-18-41-42
+.. gh-issue: 150866
+.. nonce: gXGyX-
+.. section: Library
+
+Fix :meth:`asyncio.loop.shutdown_asyncgens` to report any
+:exc:`BaseException` raised during asynchronous generator cleanup.
+
+..
+
+.. date: 2026-06-03-13-51-29
+.. gh-issue: 150662
+.. nonce: ELT8Vg
+.. section: Library
+
+Fix the ``--gecko`` collector in :mod:`profiling.sampling` that kept every
+sample in memory. It now writes sample and marker data to temporary files
+and reads them back, ultimately building the output file at the end. Patch
+by Pablo Galindo and Maurycy Pawłowski-Wieroński.
+
+..
+
+.. date: 2026-06-02-15-45-00
+.. gh-issue: 150820
+.. nonce: W7tpO7
+.. section: Library
+
+Speed up :func:`json.dumps` for small documents. Patch by Bernát Gábor.
+
+..
+
+.. date: 2026-06-02-15-44-58
+.. gh-issue: 150818
+.. nonce: Orcefu
+.. section: Library
+
+Speed up :func:`logging.getLogger` with a lock-free fast path that returns
+an already-registered logger without acquiring the logging lock. Patch by
+Bernát Gábor.
+
+..
+
+.. date: 2026-06-02-15-44-57
+.. gh-issue: 150817
+.. nonce: lpFCh0
+.. section: Library
+
+Speed up the ``|``, ``&`` and ``^`` operations on :class:`enum.Flag`
+members. Patch by Bernát Gábor.
+
+..
+
+.. date: 2026-06-02-14-21-46
+.. gh-issue: 150750
+.. nonce: SVS2o0
+.. section: Library
+
+Fix a race condition in :meth:`collections.deque.index` with free-threading.
+
+..
+
+.. date: 2026-06-02-13-10-00
+.. gh-issue: 150751
+.. nonce: Hk2Vw9
+.. section: Library
+
+:mod:`http.client` now validates the ``Content-Length`` header and the
+chunked ``chunk-size`` against the RFC 9112 grammar (``1*DIGIT`` and
+``1*HEXDIG``) before parsing them, rejecting values such as ``+5``, ``5_0``
+or a ``0x``-prefixed or negative chunk size that :func:`int` would otherwise
+accept. This avoids framing a response differently from a strict peer.
+
+..
+
+.. date: 2026-06-01-08-12-34
+.. gh-issue: 150717
+.. nonce: LVRJXH
+.. section: Library
+
+Avoid an unnecessary per-call memory allocation when matching :mod:`re`
+patterns that have no capturing groups. Patch by Bernát Gábor.
+
+..
+
+.. date: 2026-05-31-17-47-30
+.. gh-issue: 150685
+.. nonce: EBB2mU
+.. section: Library
+
+Update bundled pip to 26.1.2
+
+..
+
+.. date: 2026-05-31-14-39-25
+.. gh-issue: 150641
+.. nonce: LLIhd1
+.. section: Library
+
+Fix bug where :func:`typing.evaluate_forward_ref` with the ``STRING`` format
+could leak internal names used by the annotation machinery.
+
+..
+
+.. date: 2026-05-31-12-00-00
+.. gh-issue: 150942
+.. nonce: Re7Ref
+.. section: Library
+
+Speed up :func:`re.findall`, :func:`re.sub` and :func:`re.subn` by appending
+result items to the output list without an extra reference-count round-trip
+(using the internal reference-stealing list append helper).
+
+..
+
+.. date: 2026-05-31-10-00-00
+.. gh-issue: 150942
+.. nonce: Tk9aRef
+.. section: Library
+
+Speed up :func:`json.loads` decoding of arrays and objects by storing parsed
+values into the result list/dict without an extra reference-count round-trip
+(using the internal reference-stealing append/insert helpers).
+
+..
+
+.. date: 2026-05-29-10-11-34
+.. gh-issue: 117404
+.. nonce: EeP6xe
+.. section: Library
+
+Add a number of constants in modules :mod:`zlib`, :mod:`bz2`, :mod:`lzma`,
+and :mod:`compression.zstd`, which provide information about the version of
+libraries that were used for building the module and that are actually
+loaded. Make :const:`compression.zstd.zstd_version_info` a named tuple.
+
+..
+
+.. date: 2026-05-28-23-38-46
+.. gh-issue: 150478
+.. nonce: qEr0E-
+.. section: Library
+
+Add ``show_jit`` option to ``dis.dis`` to show JIT entry points in the
+bytecode. This is useful for visualizing where JIT traces are entered from
+the interpreter.
+
+..
+
+.. date: 2026-05-27-23-47-31
+.. gh-issue: 148932
+.. nonce: Y1xmvA
+.. section: Library
+
+Fix ``profiling.sampling`` on Windows virtual environments to resolve the
+actual Python PID from a virtual environment shim.
+
+..
+
+.. date: 2026-05-27-15-51-29
+.. gh-issue: 150534
+.. nonce: 3Nan6S
+.. section: Library
+
+Added trigonometric functions that work in units of half turns, rather than
+radians. The new functions :func:`math.acospi`, :func:`math.asinpi`,
+:func:`math.atanpi`, and :func:`math.atan2pi` return half-turn angles. The
+new functions :func:`math.cospi`, :func:`math.sinpi`, and :func:`math.tanpi`
+take half-turn angle arguments. These functions are recommended by IEEE
+754-2019 and standardized in C23.
+
+..
+
+.. date: 2026-05-27-11-18-36
+.. gh-issue: 150228
+.. nonce: pNPiO-
+.. section: Library
+
+The new :class:`site.StartupState` class lets callers batch-process
+:pep:`829` startup configuration files across multiple site directories
+before any startup code runs, with public
+:meth:`~site.StartupState.addsitedir`,
+:meth:`~site.StartupState.addusersitepackages`,
+:meth:`~site.StartupState.addsitepackages`, and
+:meth:`~site.StartupState.process` methods. The signature of
+:func:`site.addsitedir` is unchanged from Python 3.14. The
+:data:`!defer_processing_start_files` argument and the
+``process_startup_files()`` function added earlier in the 3.15 cycle have
+been removed; use :class:`!site.StartupState` instead.
+
+..
+
+.. date: 2026-05-26-19-30-00
+.. gh-issue: 150479
+.. nonce: Kq7Lm2
+.. section: Library
+
+:func:`email.utils.formataddr` now raises :exc:`ValueError` when the name or
+address contains a carriage return or line feed, matching
+:class:`email.headerregistry.Address`. This check can be disabled by
+passing ``strict=False``.
+
+..
+
+.. date: 2026-05-26-15-53-50
+.. gh-issue: 150449
+.. nonce: GfDWxl
+.. section: Library
+
+:class:`sqlite3.Blob` now supports negative-step slices for reading and
+writing (e.g. ``blob[9:0:-2]``). Previously, such slices would raise
+:exc:`SystemError` or :exc:`ValueError`.
+
+..
+
+.. date: 2026-05-25-17-00-00
+.. gh-issue: 150406
+.. nonce: jF3g63
+.. section: Library
+
+Fix a possible crash occurring during :mod:`socket` module initialization
+when the system is out of memory on platforms without a reentrant
+``gethostbyname``.
+
+..
+
+.. date: 2026-05-25-07-22-05
+.. gh-issue: 150372
+.. nonce: 9hLqhe
+.. section: Library
+
+:mod:`readline`: Fix a potential crash during tab completion caused by an
+out-of-memory error during module initialization.
+
+..
+
+.. date: 2026-05-22-15-30-00
+.. gh-issue: 132372
+.. nonce: YP4a6x
+.. section: Library
+
+Speed up :func:`logging.config.fileConfig` and
+:func:`logging.config.dictConfig` when handling many existing loggers.
+
+..
+
+.. date: 2026-05-21-20-47-45
+.. gh-issue: 150157
+.. nonce: ZvmO-bQZ
+.. section: Library
+
+Fix a crash in free-threaded builds that occurs when pickling by name
+objects without a ``__module__`` attribute while :data:`sys.modules` is
+concurrently being modified.
+
+..
+
+.. date: 2026-05-21-11-25-58
+.. gh-issue: 150175
+.. nonce: 8H4Caz
+.. section: Library
+
+Fix race condition in :class:`unittest.mock.ThreadingMock` where concurrent
+calls could lose increments to ``call_count`` and other attributes due to a
+missing lock in ``_increment_mock_call``.
+
+..
+
+.. date: 2026-05-20-14-00-00
+.. gh-issue: 145856
+.. nonce: Pl5kZx
+.. section: Library
+
+Fix :func:`plistlib.dumps` and :func:`plistlib.dump` so that
+``skipkeys=True`` together with ``sort_keys=True`` correctly drops
+non-string keys when the dictionary contains a mix of string and non-string
+keys. Previously the sort ran before the filter and raised
+:exc:`TypeError`.
+
+..
+
+.. date: 2026-05-19-19-00-49
+.. gh-issue: 84353
+.. nonce: ZU5zaQ
+.. section: Library
+
+Preserve non-UTF-8 encoded filenames when appending to a
+:class:`zipfile.ZipFile`. Previously, non-ASCII names stored in a legacy
+encoding (without the UTF-8 flag bit set) could be corrupted when the
+central directory was rewritten: they were decoded as cp437 and then
+re-stored as UTF-8.
+
+..
+
+.. date: 2026-05-19-18-25-00
+.. gh-issue: 150077
+.. nonce: zstopen-close
+.. section: Library
+
+Fix ``tarfile.TarFile.zstopen`` to close the underlying zstd file object
+when opening the tar archive is interrupted by a :exc:`BaseException`
+subclass such as :exc:`KeyboardInterrupt`.
+
+..
+
+.. date: 2026-05-19-12-00-00
+.. gh-issue: 149980
+.. nonce: Kx7p2A
+.. section: Library
+
+Fix :mod:`tarfile` so that GNU long-name directory entries have all trailing
+slashes stripped from their names, matching the behavior for short-name
+entries. Previously, only a single trailing slash was removed.
+
+..
+
+.. date: 2026-05-19-11-42-37
+.. gh-issue: 127949
+.. nonce: Ab3kZq
+.. section: Library
+
+Remove the deprecated :mod:`asyncio` event loop policy system. Patch by
+Kumar Aditya.
+
+..
+
+.. date: 2026-05-18-22-45-54
+.. gh-issue: 149816
+.. nonce: T68vc_
+.. section: Library
+
+Fix race condition in :attr:`ssl.SSLContext.sni_callback`
+
+..
+
+.. date: 2026-05-18-17-17-20
+.. gh-issue: 149189
+.. nonce: a8IooK
+.. section: Library
+
+Revert the changes to :mod:`pprint` defaults. Patch by Hugo van Kemenade.
+
+..
+
+.. date: 2026-05-18-13-43-06
+.. gh-issue: 79413
+.. nonce: OpTXbV
+.. section: Library
+
+Update :func:`dataclasses.make_dataclass` to add a *qualname* parameter. The
+*qualname* parameter will be used to set the :attr:`!__qualname__` of the
+created ``dataclass``.
+
+..
+
+.. date: 2026-05-18-12-42-31
+.. gh-issue: 149816
+.. nonce: F98iME
+.. section: Library
+
+Fix a potential use after free condition in :func:`pickle.dumps` in
+free-threaded mode when serializing lists.
+
+..
+
+.. date: 2026-05-18-07-44-46
+.. gh-issue: 149995
+.. nonce: vvtFHn
+.. section: Library
+
+Update various docstrings in :mod:`typing`.
+
+..
+
+.. date: 2026-05-17-22-37-02
+.. gh-issue: 88726
+.. nonce: BAoL6j
+.. section: Library
+
+The :mod:`email` package now uses standard MIME charset names "gb2312" and
+"big5" instead of non-standard names "eucgb2312_cn" and "big5_tw".
+
+..
+
+.. date: 2026-05-17-12-37-59
+.. gh-issue: 53144
+.. nonce: c5tr1p
+.. section: Library
+
+The :mod:`email` package now supports all aliases of Python codecs and uses
+MIME/IANA names for all IANA registered charsets.
+
+..
+
+.. date: 2026-05-17-02-25-56
+.. gh-issue: 149571
+.. nonce: LNyuWJ
+.. section: Library
+
+Fix the C implementation of :meth:`xml.etree.ElementTree.Element.itertext`:
+it no longer emits text for comments and processing instructions.
+
+..
+
+.. date: 2026-05-16-22-00-00
+.. gh-issue: 146406
+.. nonce: 10e0da
+.. section: Library
+
+Add cross-language hints for ``.clear()`` on :class:`tuple`,
+:class:`frozenset`, and :class:`frozendict`, suggesting the mutable
+counterpart. Follow-up to :gh:`146406`.
+
+..
+
+.. date: 2026-05-16-21-08-33
+.. gh-issue: 149921
+.. nonce: I1yNML
+.. section: Library
+
+Fix reference leaks in error paths of the :mod:`!_interpchannels` and
+:mod:`!_interpqueues` extension modules.
+
+..
+
+.. date: 2026-05-15-19-52-41
+.. gh-issue: 149891
+.. nonce: BJUIGB
+.. section: Library
+
+Add support for more encoding aliases `officially registered in IANA
+`__.
+
+..
+
+.. date: 2026-05-15-18-44-20
+.. gh-issue: 142349
+.. nonce: fHK3v1
+.. section: Library
+
+Add :keyword:`lazy` to the list of support topic by :func:`help`.
+
+..
+
+.. date: 2026-05-15-16-28-00
+.. gh-issue: 149819
+.. nonce: fixpth
+.. section: Library
+
+Fix regression in :func:`site.addsitedir` where ``.pth`` files were no
+longer processed in Python subprocesses. This happened because
+:func:`site.main` seeded ``known_paths`` with entries inherited from the
+parent process, causing ``addsitedir`` to skip ``.pth`` processing.
+
+..
+
+.. date: 2026-05-14-17-01-19
+.. gh-issue: 62259
+.. nonce: ytlFD5
+.. section: Library
+
+Add support for multiple multi-byte encodings in the :mod:`XML parser
+`: "cp932", "cp949", "cp950", "Big5","EUC-JP", "GB2312",
+"GBK", "johab", and "Shift_JIS". Add partial support (only BMP characters)
+for multi-byte encodings "Big5-HKSCS", "EUC_JIS-2004", "EUC_JISX0213",
+"Shift_JIS-2004", "Shift_JISX0213", "utf-8-sig" and non-standard aliases
+like "UTF8" (without hyphen). The parser now raises :exc:`ValueError` for
+known unsupported multi-byte encodings such us "ISO-2022-JP" or
+"raw-unicode-escape" instead of failing later, when encounter non-ASCII
+data.
+
+..
+
+.. date: 2026-05-14-15-55-28
+.. gh-issue: 149816
+.. nonce: ZaXQ0q
+.. section: Library
+
+Fix a race condition in ``_random.Random.__init__`` method in free-threading
+mode.
+
+..
+
+.. date: 2026-05-13-23-18-39
+.. gh-issue: 149801
+.. nonce: S_FfGr
+.. section: Library
+
+Add IANA registered names and aliases with leading zeros before number (like
+IBM00858, CP00858, IBM01140, CP01140) for corresponding codecs.
+
+..
+
+.. date: 2026-05-13-12-16-54
+.. gh-issue: 149473
+.. nonce: nOQZqn
+.. section: Library
+
+Calling ``os.environ.clear()`` now emits ``os._clearenv`` auditing event.
+Patch by Victor Stinner.
+
+..
+
+.. date: 2026-05-12-14-44-39
+.. gh-issue: 149720
+.. nonce: ccsoW-
+.. section: Library
+
+Remove support for undotted *ext* in :meth:`mimetypes.MimeTypes.add_type`.
+
+..
+
+.. date: 2026-05-12-13-03-45
+.. gh-issue: 149718
+.. nonce: SaM1NJ
+.. section: Library
+
+Coalesce consecutive identical stack frames in Tachyon, so aggregating
+collectors (pstats, collapsed, flamegraph, gecko) receive one collect.
+Improves sample rate 3x, error rate and missed rate drop by 70%. Patch by
+Maurycy Pawłowski-Wieroński.
+
+..
+
+.. date: 2026-05-12-06-24-54
+.. gh-issue: 149701
+.. nonce: 8v9RTm
+.. section: Library
+
+Fix bad return code from Lib/venv/bin/activate if hashing is disabled
+
+..
+
+.. date: 2026-05-10-23-51-23
+.. gh-issue: 149504
+.. nonce: pDSCbn
+.. section: Library
+
+Fix :func:`site.addsitedir` to allow re-entrant calls from within startup
+files. Previously, a ``.pth`` file containing an ``import`` line that
+called :func:`site.addsitedir` (or a ``.start`` entry point doing the same)
+could crash with ``RuntimeError: dictionary changed size during iteration``
+during site initialization, breaking tools such as ``uv run --with``.
+
+..
+
+.. date: 2026-05-10-19-26-50
+.. gh-issue: 149584
+.. nonce: x7Qm9A
+.. section: Library
+
+Fix excessive overhead in the Tachyon profiler when inspecting a remote
+process by avoiding repeated remote page-cache scans, batching predicted
+remote reads, and reusing cached profiler result objects. Patch by Pablo
+Galindo and Maurycy Pawłowski-Wieroński.
+
+..
+
+.. date: 2026-05-10-16-06-27
+.. gh-issue: 149609
+.. nonce: yLKPXo
+.. section: Library
+
+Raise :exc:`DeprecationWarning` on using :class:`abc.abstractclassmethod`,
+:class:`abc.abstractstaticmethod`, and :class:`abc.abstractproperty`,
+schedule its removal for Python 3.21.
+
+..
+
+.. date: 2026-05-10-14-10-00
+.. gh-issue: 149634
+.. nonce: iT5cwC
+.. section: Library
+
+Remove deprecated and unused :attr:`!tarfile.TarInfo.tarfile` attribute.
+
+..
+
+.. date: 2026-05-10-12-00-00
+.. gh-issue: 149578
+.. nonce: 5cgq7iV
+.. section: Library
+
+Fix :func:`tarfile.open` failing with :exc:`~tarfile.ReadError` when opening
+a PAX format tar archive that contains only global headers and no regular
+members.
+
+..
+
+.. date: 2026-05-10-07-21-51
+.. gh-issue: 139489
+.. nonce: rS7LTA
+.. section: Library
+
+Add :func:`xml.is_valid_text` to ``xml.__all__``.
+
+..
+
+.. date: 2026-05-09-21-02-08
+.. gh-issue: 149614
+.. nonce: U4snj3
+.. section: Library
+
+Fix a regression that broke the ability to deepcopy
+:class:`argparse.ArgumentParser` instances.
+
+..
+
+.. date: 2026-05-09-15-42-54
+.. gh-issue: 149600
+.. nonce: ZbL-iv
+.. section: Library
+
+Remove deprecated :func:`!asyncio.iscoroutinefunction` function.
+
+..
+
+.. date: 2026-05-09-15-17-59
+.. gh-issue: 149598
+.. nonce: aLrXRw
+.. section: Library
+
+Remove support of deprecated *strm* argument for :mod:`logging` handlers.
+
+..
+
+.. date: 2026-05-09-11-22-29
+.. gh-issue: 149595
+.. nonce: 1nuYXw
+.. section: Library
+
+Remove the :func:`!sys._enablelegacywindowsfsencoding` function which has
+been deprecated since Python 3.13.
+
+..
+
+.. date: 2026-05-08-16-44-20
+.. gh-issue: 149567
+.. nonce: iiZKEj
+.. section: Library
+
+Remove the :exc:`!shutil.ExecError` exception which has been deprecated
+since Python 3.14.
+
+..
+
+.. date: 2026-05-08-15-08-35
+.. gh-issue: 112821
+.. nonce: t9T1YD
+.. section: Library
+
+In the REPL, autocompletion might run arbitrary code in the getter of a
+descriptor. If that getter raised an exception, autocompletion would fail to
+present any options for the entire object. Autocompletion now works as
+expected for these objects.
+
+..
+
+.. date: 2026-05-08-14-24-16
+.. gh-issue: 149436
+.. nonce: dEV02X
+.. section: Library
+
+Improve performance of :meth:`inspect.getattr_static`.
+
+..
+
+.. date: 2026-05-08-09-11-48
+.. gh-issue: 149534
+.. nonce: Tw7eeY
+.. section: Library
+
+Fix merging of :class:`collections.defaultdict` and :class:`frozendict`.
+
+..
+
+.. date: 2026-05-08-08-24-01
+.. gh-issue: 149537
+.. nonce: hVFVnt
+.. section: Library
+
+Remove kw parameters from python version of :func:`functools.reduce`
+function.
+
+..
+
+.. date: 2026-05-08-07-51-54
+.. gh-issue: 80480
+.. nonce: nnA4p1
+.. section: Library
+
+Remove deprecated ``'u'`` type code (:c:type:`wchar_t`) for the :mod:`array`
+module. Use ``'w'`` format code instead (:c:type:`Py_UCS4`, always 4
+bytes).
+
+..
+
+.. date: 2026-05-08-06-56-57
+.. gh-issue: 149530
+.. nonce: cl2AJ8
+.. section: Library
+
+Removed :meth:`!symtable.Class.get_methods` which has been deprecated since
+3.14.
+
+..
+
+.. date: 2026-05-08-06-12-26
+.. gh-issue: 149528
+.. nonce: AxdDxa
+.. section: Library
+
+Remove ``annotationlib.ForwardRef._evaludate`` deprecated method.
+
+..
+
+.. date: 2026-05-07-21-58-17
+.. gh-issue: 149388
+.. nonce: DDBPeA
+.. section: Library
+
+Make :class:`!asyncio.windows_utils.PipeHandle` closing idempotent.
+
+..
+
+.. date: 2026-05-07-17-35-47
+.. gh-issue: 149499
+.. nonce: G2ER-R
+.. section: Library
+
+Removed the :func:`!sysconfig.expand_makefile_vars` function which has been
+deprecated since Python 3.14. Use the ``vars`` argument of
+:func:`sysconfig.get_paths` instead.
+
+..
+
+.. date: 2026-05-07-14-18-47
+.. gh-issue: 149489
+.. nonce: bX9iHe
+.. section: Library
+
+Fix :mod:`~xml.etree.ElementTree` serialization to HTML. The content of
+comments, processing instructions and elements "xmp", "iframe", "noembed",
+"noframes", and "plaintext" is no longer escaped. The "plaintext" element no
+longer have the closing tag. Add support of empty attributes (with value
+``None``).
+
+..
+
+.. date: 2026-05-06-23-13-40
+.. gh-issue: 149319
+.. nonce: PLM93t
+.. section: Library
+
+The :mod:`asyncio` REPL now ignores :envvar:`PYTHONSTARTUP` and
+:envvar:`PYTHON_BASIC_REPL` when :option:`-E` or :option:`-I` is used. Patch
+by Jonathan Dung.
+
+..
+
+.. date: 2026-05-06-20-10-44
+.. gh-issue: 149464
+.. nonce: 3mPhcr
+.. section: Library
+
+Add :func:`os.pidfd_getfd` for duplicating a file descriptor from another
+process via a pidfd. Available on Linux 5.6+. Patch by Maurycy
+Pawłowski-Wieroński.
+
+..
+
+.. date: 2026-04-29-08-10-17
+.. gh-issue: 149056
+.. nonce: jnaD4W
+.. section: Library
+
+Fix :func:`json.load` not forwarding the *array_hook* argument to
+:func:`json.loads`. Patch by Thomas Kowalski.
+
+..
+
+.. date: 2026-04-27-11-12-00
+.. gh-issue: 149046
+.. nonce: 74shDd
+.. section: Library
+
+:mod:`io`: Fix :class:`io.StringIO` serialization: no longer call
+``str(obj)`` on :class:`str` subclasses. Patch by Thomas Kowalski.
+
+..
+
+.. date: 2026-04-26-11-25-38
+.. gh-issue: 118158
+.. nonce: xIy05H
+.. section: Library
+
+Ensure py_compile CLI error messages end with a newline. Contributed by Xiao
+Yuan.
+
+..
+
+.. date: 2026-04-24-19-54-00
+.. gh-issue: 148954
+.. nonce: v1
+.. section: Library
+
+Fix XML injection vulnerability in :func:`xmlrpc.client.dumps` where the
+``methodname`` was not being escaped before interpolation into the XML body.
+
+..
+
+.. date: 2026-04-23-12-50-15
+.. gh-issue: 148441
+.. nonce: zvpCkR
+.. section: Library
+
+:mod:`xml.parsers.expat`: prevent a crash in
+:meth:`~xml.parsers.expat.xmlparser.CharacterDataHandler` when the character
+data size exceeds the parser's :attr:`buffer size
+`.
+
+..
+
+.. date: 2026-04-21-06-30-59
+.. gh-issue: 119670
+.. nonce: pMWZfY
+.. section: Library
+
+Add keyword-only parameter *force* to :func:`shlex.quote` to force quoting a
+string, even if it is already safe for a shell without being quoted.
+
+..
+
+.. date: 2026-04-20-01-24-22
+.. gh-issue: 92455
+.. nonce: vXhmad
+.. section: Library
+
+Fix :mod:`mimetypes` to prefer case-sensitive matches for suffix mappings
+and MIME type suffixes before falling back to case-insensitive matches.
+Contributed by Xiao Yuan.
+
+..
+
+.. date: 2026-04-18-12-00-00
+.. gh-issue: 148736
+.. nonce: ag-frame
+.. section: Library
+
+Fix a latent :exc:`AttributeError` in :mod:`asyncio` call-graph capture when
+walking an async generator's ``ag_await`` chain: the walker referenced
+``cr_frame`` instead of ``ag_frame``.
+
+..
+
+.. date: 2026-04-17-05-58-27
+.. gh-issue: 148665
+.. nonce: AlUajE
+.. section: Library
+
+socket.shutdown function is now enabled for Emscripten builds. However, if
+the runtime does not implement the shutdown syscall, it will show "Function
+not implemented" error.
+
+..
+
+.. date: 2026-04-04-14-25-43
+.. gh-issue: 148085
+.. nonce: o97yTo
+.. section: Library
+
+Speed up :meth:`~datetime.date.timetuple` and
+:meth:`~datetime.date.strftime` by caching the ``time.struct_time`` and
+``time.strftime`` lookups, and :meth:`~datetime.datetime.today` by reading
+the clock directly instead of calling :func:`time.time`. Patching
+:mod:`time` after importing :mod:`datetime` no longer affects these methods.
+Patch by Maurycy Pawłowski-Wieroński.
+
+..
+
+.. date: 2026-03-31-21-25-44
+.. gh-issue: 147950
+.. nonce: 5JR0sK
+.. section: Library
+
+Bind ``yank-arg`` to :kbd:`M-_` in the REPL.
+
+..
+
+.. date: 2026-03-26-09-30-00
+.. gh-issue: 146452
+.. nonce: Y2N6qZ8J
+.. section: Library
+
+Fix segfault in :mod:`pickle` when pickling a dictionary concurrently
+mutated by another thread in the free-threaded build.
+
+..
+
+.. date: 2026-03-26-00-00-00
+.. gh-issue: 47005
+.. nonce: xxc89c
+.. section: Library
+
+Fix :meth:`!urllib.request.AbstractHTTPHandler.do_open` to give regular
+headers set via :meth:`~urllib.request.Request.add_header` priority over
+unredirected headers, consistent with
+:meth:`~urllib.request.Request.get_header` and
+:meth:`~urllib.request.Request.header_items`.
+
+..
+
+.. date: 2026-02-22-11-27-57
+.. gh-issue: 145107
+.. nonce: ZlQXEZ
+.. section: Library
+
+Simplify ``asyncio.staggered_race`` by using ``eager_start=False``.
+
+..
+
+.. date: 2026-02-11-16-47-27
+.. gh-issue: 140729
+.. nonce: 2uTPQp
+.. section: Library
+
+Fix a pickling error in the ``cProfile`` module when profiling a script that
+uses :class:`multiprocessing.Process` with the ``spawn`` and ``forkserver``
+start methods.
+
+..
+
+.. date: 2026-01-18-06-42-47
+.. gh-issue: 143988
+.. nonce: MtLtCP
+.. section: Library
+
+Fixed crashes in :meth:`socket.socket.sendmsg` and
+:meth:`socket.socket.recvmsg_into` that could occur if buffer sequences are
+concurrently mutated.
+
+..
+
+.. date: 2025-12-21-17-56-37
+.. gh-issue: 143008
+.. nonce: aakErJ
+.. section: Library
+
+Fix crash in :class:`io.TextIOWrapper` when reentrant
+:meth:`io.TextIOBase.detach` is called reentrantly from the underlying
+buffer.
+
+..
+
+.. date: 2025-12-14-06-44-34
+.. gh-issue: 81881
+.. nonce: qancdQ
+.. section: Library
+
+:func:`shutil.copyfile` now raises :exc:`~shutil.SpecialFileError` for
+sockets and device files.
+
+..
+
+.. date: 2025-11-02-22-24-13
+.. gh-issue: 140924
+.. nonce: NQVbR_
+.. section: Library
+
+Add :func:`locale.localize`, :func:`locale.delocalize` and platform-specific
+locale constants from the :mod:`!_locale` module to ``locale.__all__``.
+
+..
+
+.. date: 2025-11-02-05-28-56
+.. gh-issue: 115634
+.. nonce: JbcNnF
+.. section: Library
+
+Fix a deadlock in :class:`concurrent.futures.ProcessPoolExecutor` when using
+``max_tasks_per_child``, present since the feature was introduced in Python
+3.11. The executor stopped scheduling queued tasks after a worker process
+exited upon reaching its task limit. Based on a fix proposed by Tabrez
+Mohammed.
+
+..
+
+.. date: 2025-10-20-09-12-18
+.. gh-issue: 140344
+.. nonce: WjbYg-
+.. section: Library
+
+The classes ``ast.slice``, ``ast.ExtSlice``, ``ast.Index``, ``ast.Suite``,
+``ast.AugLoad``, ``ast.AugStore``, and ``ast.Param``, deprecated since
+Python 3.9, now issue deprecation warnings on use. They are now scheduled
+for removal in Python 3.21.
+
+The ``dims`` property of ``ast.Tuple`` objects, deprecated since Python 3.9,
+now issues a deprecation warning when accessed. The property is scheduled
+for removal in Python 3.21. Use the (non-deprecated) ``elts`` property of
+``ast.Tuple`` objects instead.
+
+The deprecated global names are also no longer imported by ``from ast import
+*``.
+
+..
+
+.. date: 2025-10-19-17-34-07
+.. gh-issue: 140326
+.. nonce: kZM0pV
+.. section: Library
+
+Fix the :mod:`asyncio` REPL namespace so that relative imports no longer
+resolve against the :mod:`asyncio` package and ``__file__`` is no longer
+set.
+
+..
+
+.. date: 2025-10-12-08-46-26
+.. gh-issue: 139398
+.. nonce: hESOMl
+.. section: Library
+
+Add supported ``_sunder_`` names to the :func:`dir` method of the
+:mod:`enum` module to support them in :term:`REPL` autocompletion.
+
+..
+
+.. date: 2025-10-09-12-13-29
+.. gh-issue: 139819
+.. nonce: YxUDyH
+.. section: Library
+
+:mod:`rlcompleter`: Avoid suggesting attributes that are not accessible on
+instances (e.g., Enum members showing ``__name__``). Patch by Peter
+(ttw225).
+
+..
+
+.. date: 2025-09-05-20-50-35
+.. gh-issue: 79638
+.. nonce: Y-JfaH
+.. section: Library
+
+Disallow all access in :mod:`urllib.robotparser` if the ``robots.txt`` file
+is unreachable due to server or network errors.
+
+..
+
+.. date: 2025-08-30-07-44-30
+.. gh-issue: 86533
+.. nonce: pathlib
+.. section: Library
+
+The :func:`os.makedirs` function and :meth:`pathlib.Path.mkdir` method now
+have a *parent_mode* parameter to specify the mode for intermediate
+directories when creating parent directories. This allows one to match the
+behavior from Python 3.6 and earlier for :func:`os.makedirs`.
+
+..
+
+.. date: 2025-07-28-11-00-49
+.. gh-issue: 64192
+.. nonce: 7htLtg
+.. section: Library
+
+Add the optional ``buffersize`` parameter to
+:meth:`multiprocessing.pool.Pool.imap` and
+:meth:`multiprocessing.pool.Pool.imap_unordered` to limit the number of
+submitted tasks whose results have not yet been yielded. If the buffer is
+full, iteration over the *iterables* pauses until a result is yielded from
+the buffer. To fully utilize pool's capacity when using this feature, set
+*buffersize* at least to the number of processes in pool (to consume
+*iterable* as you go), or even higher (to prefetch the next
+``N=buffersize-processes`` arguments).
+
+..
+
+.. date: 2025-05-24-11-17-34
+.. gh-issue: 51067
+.. nonce: yHOgfy
+.. section: Library
+
+Add :meth:`~zipfile.ZipFile.remove` and :meth:`~zipfile.ZipFile.repack` to
+:class:`~zipfile.ZipFile`.
+
+..
+
+.. date: 2025-05-19-21-08-25
+.. gh-issue: 134261
+.. nonce: ravGYm
+.. section: Library
+
+zip: On reproducible builds, ZipFile uses UTC instead of the local time when
+writing file datetimes to avoid underflows.
+
+..
+
+.. date: 2025-05-19-20-29-35
+.. gh-issue: 133998
+.. nonce: KmElUw
+.. section: Library
+
+Fix :exc:`struct.error` exception when creating a file with
+:class:`gzip.GzipFile` or compressing data with :func:`gzip.compress` if the
+system time is outside the range 00:00:00 UTC, January 1, 1970 through
+06:28:15 UTC, February 7, 2106, or explicitly passed *mtime* argument is
+outside the range ``0`` to ``2**32-1``.
+
+..
+
+.. date: 2025-05-19-07-32-51
+.. gh-issue: 68164
+.. nonce: XhFbJD
+.. section: Library
+
+Fix :func:`zipfile.ZipFile.writestr` so it sets the "regular file" bit by
+default.
+
+..
+
+.. date: 2025-05-07-18-31-31
+.. gh-issue: 46927
+.. nonce: sF02gj
+.. section: Library
+
+Prevent :mod:`readline` from overriding the ``COLUMNS`` and ``LINES``
+environment variables, as values are not updated on terminal resize.
+
+..
+
+.. date: 2025-05-01-16-44-16
+.. gh-issue: 72902
+.. nonce: 19qwJW
+.. section: Library
+
+Optimize (~x1.4 speedup) :meth:`fractions.Fraction.from_decimal` and
+:meth:`fractions.Fraction.from_float` for :class:`~decimal.Decimal` and
+:class:`float` inputs, respectively. Patch by Sergey B Kirpichev.
+
+..
+
+.. date: 2025-03-01-13-36-02
+.. gh-issue: 128110
+.. nonce: 9wx_G0
+.. section: Library
+
+Fix bug in the parsing of :mod:`email` address headers that could result in
+extraneous spaces in the decoded text when using a modern email policy.
+Space between pairs of adjacent :rfc:`2047` encoded-words is now ignored,
+per section 6.2 (and consistent with existing parsing of unstructured
+headers like *Subject*).
+
+..
+
+.. date: 2025-01-31-02-27-53
+.. gh-issue: 129382
+.. nonce: GI93CM
+.. section: Library
+
+The :class:`venv.EnvBuilder` and :func:`venv.create` APIs now use the
+platform-dependent default for symlinks from :mod:`venv`'s command-line
+interface.
+
+..
+
+.. date: 2024-11-08-18-39-50
+.. gh-issue: 125763
+.. nonce: F2p5_U
+.. section: Library
+
+Remove the broken spacebar quit binding from :mod:`turtledemo`\s
+``sorting_animate`` example.
+
+..
+
+.. date: 2024-11-02-02-02-31
+.. gh-issue: 107398
+.. nonce: uUtA6Q
+.. section: Library
+
+Fix :mod:`tarfile` stream mode exception when process the file with the gzip
+extra field.
+
+..
+
+.. date: 2024-07-02-20-57-43
+.. gh-issue: 121109
+.. nonce: Tp6R2s
+.. section: Library
+
+Fix :mod:`tarfile` performance issue when reading archives in streaming mode
+(e.g. ``r|*``).
+
+..
+
+.. date: 2024-06-18-04-08-37
+.. gh-issue: 120665
+.. nonce: x7T1hV
+.. section: Library
+
+Fixed an issue where ``unittest`` loaders would load and instantiate
+:class:`unittest.TestCase`-derived subclasses that are also abstract base
+classes, which can't be instantiated.
+
+..
+
+.. date: 2024-03-17-22-16-53
+.. gh-issue: 115988
+.. nonce: EshSDM
+.. section: Library
+
+:mod:`lzma` adds constants to support the newer BCJ filters for ARM64 and
+RISC-V.
+
+..
+
+.. date: 2024-02-04-13-56-48
+.. gh-issue: 108518
+.. nonce: 6NCPk_
+.. section: Library
+
+The iterator returned by :meth:`concurrent.futures.Executor.map` is no
+longer automatically closed if a function call raises an exception. Use
+method :meth:`!close` to explicitly close the iterator.
+
+..
+
+.. date: 2023-12-20-22-05-40
+.. gh-issue: 113329
+.. nonce: 1CJy3o
+.. section: Library
+
+Fix :exc:`OSError` being raised when trying to run doctests on a class
+objects in the REPL. Patch by Sten Wessel.
+
+..
+
+.. date: 2023-06-12-21-31-02
+.. gh-issue: 105708
+.. nonce: 5fFwP8
+.. section: Library
+
+Accept an uppercase V prefix in IPvFuture addresses in
+:func:`urllib.parse.urlsplit`.
+
+..
+
+.. date: 2023-04-27-14-50-03
+.. gh-issue: 103925
+.. nonce: khC-El
+.. section: Library
+
+Fix :meth:`csv.Sniffer.sniff` for a sample with ``\r\n`` line endings in
+which a quoted field ends a line: a letter could be detected as the
+delimiter.
+
+..
+
+.. date: 2023-04-24-11-12-00
+.. gh-issue: 60055
+.. nonce: UjP6aX
+.. section: Library
+
+Let ``urllib.robotparser.RobotFileParser`` accept a
+``urllib.request.Request`` object as well as a url string when setting a
+robots.txt url.
+
+..
+
+.. date: 2023-03-23-19-47-05
+.. gh-issue: 102967
+.. nonce: gfIYkN
+.. section: Library
+
+A bug in :func:`!doctest._SpoofOut.truncate` was causing None to be passed
+to :func:`!StringIO.seek` when no size was given. A simple fix skips the
+seek call when no size is given so the buffer can be truncated from the
+current position.
+
+..
+
+.. date: 2023-02-26-14-07-18
+.. gh-issue: 91099
+.. nonce: _QPbEL
+.. section: Library
+
+:meth:`imaplib.IMAP4.login` now raises exceptions with :class:`str` instead
+of :class:`bytes`. Patch by Florian Best.
+
+..
+
+.. date: 2023-02-11-09-49-49
+.. gh-issue: 82039
+.. nonce: caTE7O
+.. section: Library
+
+:meth:`http.cookiejar.FileCookieJar.load` now checks the first, format
+signature line in a case-insensitive manner. Patch by Ashley Harvey.
+
+..
+
+.. date: 2023-01-23-21-23-50
+.. gh-issue: 101267
+.. nonce: _f-cFH
+.. section: Library
+
+When a worker process terminates unexpectedly,
+:class:`concurrent.futures.ProcessPoolExecutor` now sets a separate
+:exc:`~concurrent.futures.process.BrokenProcessPool` exception on each
+pending future instead of sharing a single instance among them all. Sharing
+one exception produced malformed tracebacks: each :meth:`Future.result()
+` call re-raised the same object,
+appending another copy of the traceback to it.
+
+..
+
+.. bpo: 46375
+.. date: 2022-04-10-20-10-59
+.. nonce: 8j1ogZ
+.. section: Library
+
+Add :meth:`io.BytesIO.peek` method to read without advancing position.
+
+..
+
+.. bpo: 47216
+.. date: 2022-04-04-17-58-05
+.. nonce: gPyPte
+.. section: Library
+
+Added *mtime* option to :func:`gzip.open`, which will be passed to the
+constructor of :class:`~gzip.GzipFile`.
+
+..
+
+.. date: 2022-01-03-12-50-42
+.. gh-issue: 70758
+.. nonce: 2NjFW_
+.. section: Library
+
+Creating a new :mod:`turtle` screen after the previous one was closed no
+longer raises ``turtle.Terminator`` on the first turtle command.
+
+..
+
+.. bpo: 45509
+.. date: 2021-10-18-13-46-55
+.. nonce: Upwb60
+.. section: Library
+
+Gzip headers are now checked for corrupted NAME, COMMENT and HCRC fields.
+
+..
+
+.. date: 2021-09-09-10-15-54
+.. gh-issue: 75245
+.. nonce: tLeTkn
+.. section: Library
+
+:meth:`socket.socket.makefile` now supports line buffering (``buffering=1``)
+in text mode, as :func:`open` does and as it worked in Python 2. Previously
+it silently used block buffering. In binary mode it now emits a
+:exc:`RuntimeWarning` and uses the default buffer size, also as :func:`open`
+does.
+
+..
+
+.. bpo: 44012
+.. date: 2021-06-03-22-23-38
+.. nonce: BK3HfA
+.. section: Library
+
+The ``exploded`` attribute of :class:`ipaddress.IPv6Address` and
+:class:`ipaddress.IPv6Interface` now supports addresses with a scope ID
+(link-local addresses). Previously the former raised
+:exc:`~ipaddress.AddressValueError` and the latter omitted the scope ID.
+
+..
+
+.. bpo: 40469
+.. date: 2021-02-26-13-17-57
+.. nonce: yJHeQg
+.. section: Library
+
+:class:`~logging.handlers.TimedRotatingFileHandler` now uses the creation
+time instead of the last modification time of an existing log file as the
+basis for the first rotation after handler creation, if supported by the OS
+and file system. This allows it to be used in short-running programs that
+start and end before the rotation interval expires.
+
+..
+
+.. bpo: 42861
+.. date: 2021-01-09-18-40-15
+.. nonce: T7Ge9O
+.. section: Library
+
+Add :meth:`IPv4Network.next_network() `
+and :meth:`IPv6Network.next_network() `.
+Patch by Faisal Mahmood.
+
+..
+
+.. date: 2020-05-05-06-05-24
+.. gh-issue: 84687
+.. nonce: ggjoGl
+.. section: Library
+
+The :func:`os.exec\* ` functions now set the
+:attr:`~OSError.filename` attribute of the raised :exc:`FileNotFoundError`
+or :exc:`NotADirectoryError` to the program name passed by the caller.
+
+..
+
+.. date: 2020-02-19-16-35-52
+.. gh-issue: 83869
+.. nonce: EPD_zn
+.. section: Library
+
+Fix :mod:`tarfile` reading an archive with a GNU sparse 1.0 member whose
+size is set in the pax extended header. The offset of the next header was
+computed from the offset of the data, which is already past the sparse map,
+and from the size of the member, which can be the apparent size of the
+sparse file. All following members were unreachable.
+
+..
+
+.. date: 2019-02-08-17-33-49
+.. gh-issue: 61366
+.. nonce: k6W5Sp
+.. section: Library
+
+:class:`http.cookiejar.MozillaCookieJar` now reads session cookies written
+by curl and Wget, which use ``0`` in the expiration time field. Contributed
+by Jérémie Detrey.
+
+..
+
+.. date: 2026-09-24-10-10-15
+.. gh-issue: 57491
+.. nonce: UA-2uN
+.. section: Documentation
+
+Reduce the depth of the table of contents in the EPUB documentation from
+three levels to two, making it much shorter and easier to navigate in e-book
+readers.
+
+..
+
+.. date: 2026-09-24-01-20-36
+.. gh-issue: 142083
+.. nonce: WOlkvr
+.. section: Documentation
+
+Document the ``'w'`` type code in the :class:`array.array` docstring, so
+that it lists the same type codes as :data:`array.typecodes` and the
+:mod:`array` module documentation.
+
+..
+
+.. date: 2026-07-17-22-33-43
+.. gh-issue: 118150
+.. nonce: m7iFdP
+.. section: Documentation
+
+Clarify in the :mod:`difflib` documentation what *junk* actually does, its
+drawbacks, and how to control it.
+
+..
+
+.. date: 2026-06-18-16-58-52
+.. gh-issue: 59551
+.. nonce: oNkjTG
+.. section: Documentation
+
+Rename Doc/library/dialog.rst to tkinter.dialogs.rst.
+
+..
+
+.. date: 2026-06-17-12-00-00
+.. gh-issue: 86726
+.. nonce: __bOgH
+.. section: Documentation
+
+Greatly expand the :mod:`tkinter` documentation to cover the full public API
+of the package and its submodules. The descriptions are oriented towards
+Python rather than Tcl/Tk, with corrected return types and
+``versionadded``/``versionchanged`` information.
+
+..
+
+.. date: 2026-05-23-17-27-41
+.. gh-issue: 150319
+.. nonce: ol9tWK
+.. section: Documentation
+
+Generic builtin and standard library types now document the meaning of their
+type parameters.
+
+..
+
+.. date: 2023-09-16-23-42-27
+.. gh-issue: 109503
+.. nonce: mZ-kdU
+.. section: Documentation
+
+Fix documentation for :func:`shutil.move` on usage of :func:`os.rename`
+since nonatomic move might be used even if the files are on the same
+filesystem. Patch by Fang Li
+
+..
+
+.. date: 2026-10-12-11-26-01
+.. gh-issue: 159211
+.. nonce: FWFj-p
+.. section: Tests
+
+The iOS testbed no longer gathers simulator diagnostics when a test run
+fails.
+
+..
+
+.. date: 2026-09-24-10-40-28
+.. gh-issue: 158051
+.. nonce: B1ZBTA
+.. section: Tests
+
+The iOS testbed has been updated for compatibilty with Xcode 27.
+
+..
+
+.. date: 2026-09-16-17-06-54
+.. gh-issue: 157628
+.. nonce: KAwhlY
+.. section: Tests
+
+In regrtest, only consider that a test leaks if all test runs leak at least
+one file descriptor. For example, ignore "[0, 1, -1] file descriptors,
+sum=0" deltas, instead of reporting a leak. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-09-14-14-50-42
+.. gh-issue: 140550
+.. nonce: 7jirEN
+.. section: Tests
+
+Enable limited C API tests on Free Threading in test_cext and test_cppext:
+test the :c:macro:`Py_TARGET_ABI3T` macro. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-08-18-19-40-22
+.. gh-issue: 75876
+.. nonce: IOiCcK
+.. section: Tests
+
+In verbose mode, a test decorated with :func:`~test.support.bigmemtest` now
+reports how much memory it really used, and the number of major page faults
+it took, if any.
+
+..
+
+.. date: 2026-08-18-10-16-44
+.. gh-issue: 75876
+.. nonce: PEZplM
+.. section: Tests
+
+A test decorated with :func:`~test.support.bigmemtest` now runs in a
+subprocess if it really allocates the memory it asks for (that is, if the
+``-M`` option is used), so that the memory it uses and the address space it
+fragments are released when it ends. A dummy run stays in the process. The
+separate memory watchdog process is no longer needed: the parent process
+watches the memory usage of the subprocess.
+
+..
+
+.. date: 2026-08-12-20-52-16
+.. gh-issue: 109817
+.. nonce: GZHUNg
+.. section: Tests
+
+Add the ``--single-process-per-case`` option to libregrtest to run every
+test case in a separate process. Test cases from the same test module are
+run sequentially. This helps to detect order dependencies and environment
+leaks between test cases.
+
+..
+
+.. date: 2026-08-09-14-00-00
+.. gh-issue: 155411
+.. nonce: Qw8Lm2
+.. section: Tests
+
+Fix :func:`!test.support.subTests` for asynchronous test methods. They were
+wrapped in a synchronous function, which discarded the coroutine without
+awaiting it, so the test silently did not run at all.
+
+..
+
+.. date: 2026-08-08-09-15-08
+.. gh-issue: 108885
+.. nonce: Qm3vLp
+.. section: Tests
+
+Running the Python test suite with ``-vv`` now reports every example of a
+doctest. A single ``-v`` reports the test names, as before.
+
+..
+
+.. date: 2026-08-06-18-20-00
+.. gh-issue: 132581
+.. nonce: envchg
+.. section: Tests
+
+The list of tests which altered the execution environment now includes the
+reasons why the environment was considered altered, for example an
+unraisable exception or a modified :data:`sys.path`. The final result no
+longer repeats the same state twice (like ``ENV CHANGED then ENV CHANGED``).
+
+..
+
+.. date: 2026-08-03-20-15-00
+.. gh-issue: 155109
+.. nonce: limstack
+.. section: Tests
+
+Add ``test.support.run_with_limited_c_stack()`` and use it in tests that
+exhaust the C stack with a fixed number of recursive calls, so that their
+outcome no longer depends on the C stack size.
+
+..
+
+.. date: 2026-07-24-12-00-00
+.. gh-issue: 76595
+.. nonce: KfF5xR
+.. section: Tests
+
+Add C API tests for :c:func:`PyCapsule_Import`.
+
+..
+
+.. date: 2026-07-20-11-30-00
+.. gh-issue: 154211
+.. nonce: hugestack
+.. section: Tests
+
+Add ``test.support.skip_if_huge_c_stack()`` and use it to skip tests that
+exhaust the C stack if the stack limit is very large (e.g. on DragonFly BSD
+or with ``ulimit -s unlimited``).
+
+..
+
+.. date: 2026-07-19-20-15-00
+.. gh-issue: 154167
+.. nonce: sigint
+.. section: Tests
+
+The test runner (regrtest) now restores the default SIGINT handler if it was
+inherited as ignored, so the test suite no longer hangs when run as a shell
+background job.
+
+..
+
+.. date: 2026-07-19-18-20-00
+.. gh-issue: 154144
+.. nonce: tcbool
+.. section: Tests
+
+Fix building the :mod:`!_testcapi` module on NetBSD.
+
+..
+
+.. date: 2026-07-19-15-59-41
+.. gh-issue: 154137
+.. nonce: N689bE
+.. section: Tests
+
+Check for Windows handle leaks in regrtest. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-06-29-10-14-09
+.. gh-issue: 152548
+.. nonce: Khw9J7
+.. section: Tests
+
+Add the :func:`test.support.isolation.runInSubprocess` decorator to run a
+test method or ``TestCase`` subclass in a fresh interpreter subprocess,
+isolated from the rest of the test run.
+
+..
+
+.. date: 2026-06-22-19-45-00
+.. gh-issue: 151626
+.. nonce: K9pZ2x
+.. section: Tests
+
+Fix several tests in ``test.test_inspect``, ``test.test_import``,
+``test.test_importlib``, ``test.test_py_compile`` and
+``test.test_compileall`` that failed when the test suite was run with
+:envvar:`PYTHONPYCACHEPREFIX` set. These tests now neutralize the pycache
+prefix where they assume the default ``__pycache__`` bytecode layout.
+
+..
+
+.. date: 2026-06-16-05-11-38
+.. gh-issue: 151096
+.. nonce: Kq3Lp9
+.. section: Tests
+
+Fix ``test_embed`` failing when CPython is configured with a split exec
+prefix (``--exec-prefix`` differing from ``--prefix``).
+
+..
+
+.. date: 2026-06-09-11-52-52
+.. gh-issue: 151130
+.. nonce: 1vslPH
+.. section: Tests
+
+Add more tests for ``PyWeakref_*`` C API.
+
+..
+
+.. date: 2026-06-06-16-22-00
+.. gh-issue: 150966
+.. nonce: 7N9x5Q
+.. section: Tests
+
+Avoid prematurely terminating failing live sampling profiler test targets,
+which made stderr assertions flaky on ASAN buildbots.
+
+..
+
+.. date: 2026-05-25-15-39-53
+.. gh-issue: 150387
+.. nonce: yzZ7jq
+.. section: Tests
+
+Fix hang in
+``test.test_profiling.test_sampling_profiler.test_live_collector_ui.TestLiveModeErrors.test_run_failed_script_live``
+on slow buildbots. The test now always queues a final ``q`` keystroke so the
+live TUI loop exits even when the profiler collects enough samples to enter
+the post-finished input loop.
+
+..
+
+.. date: 2026-05-22-16-41-45
+.. gh-issue: 150114
+.. nonce: UdMikH
+.. section: Tests
+
+On Linux, regrtest now logs the total memory usage of all Python processes.
+Read the private memory in ``/proc/pid/smaps``. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-05-13-14-53-23
+.. gh-issue: 149776
+.. nonce: orqgsn
+.. section: Tests
+
+Fix test_socket on Linux kernel 7.1 and newer: skip UDP Lite tests if it's
+not supported. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-04-24-01-38-56
+.. gh-issue: 148853
+.. nonce: _uM4_Q
+.. section: Tests
+
+Fix tests failing on FreeBSD in test.support's
+in_systemd_nspawn_sync_suppressed() due to unreadable /run directory.
+
+..
+
+.. date: 2026-01-21-02-03-31
+.. gh-issue: 142414
+.. nonce: CfcgiR
+.. section: Tests
+
+Isolate reloading modules in test_interpreters to avoid having broken
+references.
+
+..
+
+.. date: 2026-10-05-12-15-57
+.. gh-issue: 158878
+.. nonce: KWLqLy
+.. section: Build
+
+Stop creating an empty Modules/Setup.local file as it no longer seems to be
+required to statically link the extension modules.
+
+..
+
+.. date: 2026-10-03-23-23-12
+.. gh-issue: 158683
+.. nonce: eMlp60
+.. section: Build
+
+Fix the :file:`Modules/Setup` entry for the :mod:`!_zstd` module by adding
+missing source files.
+
+..
+
+.. date: 2026-10-02-12-18-20
+.. gh-issue: 129040
+.. nonce: 6wJPY6
+.. section: Build
+
+Added support for function call adaptor trampolines for wasi to prevent
+traps when C handlers take the wrong number of arguments. Dropped Emscripten
+function call adaptors support for JS runtimes that don't support wasm-gc.
+
+..
+
+.. date: 2026-09-29-09-40-25
+.. gh-issue: 158010
+.. nonce: H4Top_
+.. section: Build
+
+Update Android and iOS build scripts to use OpenSSL 3.5.9.
+
+..
+
+.. date: 2026-09-21-19-20-42
+.. gh-issue: 136872
+.. nonce: a2tSc_
+.. section: Build
+
+Python built with :option:`--with-address-sanitizer` or
+:option:`--with-memory-sanitizer` now includes pymalloc, but uses ``malloc``
+as the default memory allocator. Set :envvar:`PYTHONMALLOC=pymalloc
+` to use pymalloc.
+
+..
+
+.. date: 2026-09-21-10-50-31
+.. gh-issue: 157923
+.. nonce: OffPYn
+.. section: Build
+
+Support WASI SDK 34.
+
+..
+
+.. date: 2026-09-19-16-54-58
+.. gh-issue: 157549
+.. nonce: uk6QNH
+.. section: Build
+
+Use ``sysconf(_SC_PAGESIZE)`` instead of ``getpagesize()`` in
+``remote_debug.h`` so ``_remote_debugging`` builds on Darwin with
+``-Werror=implicit-function-declaration``.
+
+..
+
+.. date: 2026-09-07-23-40-00
+.. gh-issue: 157142
+.. nonce: gpnoop
+.. section: Build
+
+Fix the link of ``Programs/_freeze_module`` when extension modules are built
+in (``MODULE_BUILDTYPE=static``) and the test modules are enabled:
+``Modules/getpath_noop.c`` now defines ``_Py_Get_Getpath_CodeObject()``,
+which ``_testinternalcapi`` uses.
+
+..
+
+.. date: 2026-09-07-15-13-19
+.. gh-issue: 155292
+.. nonce: _WNxL7
+.. section: Build
+
+In ``makeunicodedata.py``, the script for updating Unicode data, skip
+generating ``stringprep.py`` if the current interpreter's Unicode data
+version does not match the target version.
+
+..
+
+.. date: 2026-08-31-15-50-04
+.. gh-issue: 156049
+.. nonce: FCf6hP
+.. section: Build
+
+Add :option:`--with-hwaddress-sanitizer` to build with `HWAddressSanitizer
+`_.
+
+..
+
+.. date: 2026-08-29-15-14-45
+.. gh-issue: 156554
+.. nonce: 64SZb1
+.. section: Build
+
+Update ``PY_SUPPORT_TIER`` according to :pep:`11` for these target triples:
+``aarch64-*-linux-gnu/gcc``, ``aarch64-pc-windows-msvc/msvc``,
+``x86_64-apple-darwin*/clang``, and ``powerpc64le-*-linux-gnu/gcc``.
+
+..
+
+.. date: 2026-08-23-12-10-45
+.. gh-issue: 156244
+.. nonce: Rv6qXt
+.. section: Build
+
+Update :program:`configure` to reflect that the
+``riscv64-unknown-linux-gnu`` target triple is now a :pep:`11` tier 3
+supported platform.
+
+..
+
+.. date: 2026-08-20-17-41-11
+.. gh-issue: 155911
+.. nonce: yL3z8q
+.. section: Build
+
+Fix curses detection with libraries in ``LIBS`` and
+:option:`--without-curses`. Patch by Shamil Abdulaev.
+
+..
+
+.. date: 2026-08-20-14-02-33
+.. gh-issue: 156115
+.. nonce: KXr8wU
+.. section: Build
+
+iOS simulator builds are now configured with ``-mios-simulator-version-min``
+instead of the device's ``-mios-version-min``. The device flag made the
+linker reject libraries resolved from the simulator SDK, so library
+detection silently failed.
+
+..
+
+.. date: 2026-08-20-13-32-54
+.. gh-issue: 156109
+.. nonce: ZTJHi9
+.. section: Build
+
+iOS builds may now be configured without a framework, producing a static
+``libpython`` for embedding in an app binary. Such a build cannot load
+extension modules at runtime, and requires ``MODULE_BUILDTYPE=static`` and
+``--disable-test-modules`` to be requested explicitly. A shared iOS build
+must still be a framework build.
+
+..
+
+.. date: 2026-08-14-20-16-55
+.. gh-issue: 153400
+.. nonce: 9Oxi-N
+.. section: Build
+
+Support os.getrandom() when building Python with old glibc versions and
+recent Linux kernel (glibc 2.25 or older and Linux kernel 3.17 or newer).
+Get the syscall number from kernel headers, rather than glibc headers.
+
+..
+
+.. date: 2026-08-10-12-00-00
+.. gh-issue: 90604
+.. nonce: Kx7pQn
+.. section: Build
+
+``configure`` no longer sets ``MULTIARCH`` on OpenBSD platforms.
+
+..
+
+.. date: 2026-08-02-12-00-01
+.. gh-issue: 152023
+.. nonce: pT7dKb
+.. section: Build
+
+Update Android builds to SQLite 3.53.4. Additionally, enable the
+``median()`` and ``percentile()`` functions.
+
+..
+
+.. date: 2026-07-20-20-30-00
+.. gh-issue: 154271
+.. nonce: solxopen
+.. section: Build
+
+Define ``_XOPEN_SOURCE=600`` on Solaris and illumos, so that on illumos the
+socket module is built with :meth:`~socket.socket.sendmsg`,
+:meth:`~socket.socket.recvmsg` and the ``CMSG_*`` helpers. This also
+enables the ``forkserver`` :mod:`multiprocessing` start method.
+
+..
+
+.. date: 2026-07-19-16-45-00
+.. gh-issue: 154136
+.. nonce: mathpi
+.. section: Build
+
+Fix building the :mod:`math` module on FreeBSD. Define ``_ISOC23_SOURCE`` to
+make the C23 library declarations (such as ``sinpi()`` in ``math.h``)
+visible.
+
+..
+
+.. date: 2026-07-19-12-16-31
+.. gh-issue: 154070
+.. nonce: f5da07
+.. section: Build
+
+Build the :mod:`curses` module against a wide-character capable ncurses even
+when it is not named ``ncursesw`` -- for example the pkgsrc ncurses on
+NetBSD and illumos, or the system ncurses on macOS. Such a library
+previously produced a narrow build.
+
+..
+
+.. date: 2026-07-19-12-06-45
+.. gh-issue: 152902
+.. nonce: 0BXdab
+.. section: Build
+
+Added Intel ``icx`` compiler support to ``configure.ac``. Contributed by
+High Performance Kernels LLC.
+
+..
+
+.. date: 2026-07-19-07-48-43
+.. gh-issue: 154055
+.. nonce: FemUJU
+.. section: Build
+
+The :mod:`curses` and :mod:`curses.panel` modules can now be built against a
+curses library that lacks the X/Open ``attr_t`` and soft-label attribute
+functions, ``scr_set()`` or ``resizeterm()`` -- such as the native SVr4
+curses of illumos and Solaris. These functions are probed and used only
+when present.
+
+..
+
+.. date: 2026-07-18-14-30-12
+.. gh-issue: 136687
+.. nonce: teaPCG
+.. section: Build
+
+Add the :option:`--with-curses` option to :program:`configure` to select the
+curses backend (``ncursesw``, ``ncurses`` or the system's native ``curses``)
+or, as :option:`--without-curses`, to exclude the :mod:`curses` and
+:mod:`curses.panel` modules from the build.
+
+..
+
+.. date: 2026-07-11-07-26-16
+.. gh-issue: 126877
+.. nonce: Zt7Kq2
+.. section: Build
+
+Fix the :program:`configure` check for Tcl/Tk which could wrongly succeed
+with optimizing compilers when the libraries are missing.
+
+..
+
+.. date: 2026-07-10-13-25-55
+.. gh-issue: 153511
+.. nonce: dCPBwU
+.. section: Build
+
+Removes the legacy MSI and Nuget build scripts, the legacy ``py.exe``
+launcher (now replaced by the Python install manager), and adds a
+``PC/layout`` readme.
+
+..
+
+.. date: 2026-07-09-22-45-00
+.. gh-issue: 153438
+.. nonce: Qr7N2p
+.. section: Build
+
+Update Windows build and installer tooling and documentation to use the
+current download URL for ``nuget.exe``.
+
+..
+
+.. date: 2026-07-02-16-25-13
+.. gh-issue: 152870
+.. nonce: oh9eD1
+.. section: Build
+
+Fix a compilation error in the :mod:`decimal` C extension (``_decimal``)
+when it is built with ``EXTRA_FUNCTIONALITY``. ``Context.apply()`` called
+the internal ``_apply`` helper using its pre-Argument-Clinic signature; the
+call is now made through the generated ``_impl`` function.
+
+..
+
+.. date: 2026-07-01-17-53-00
+.. gh-issue: 152769
+.. nonce: Kp7mQ2
+.. section: Build
+
+Enable the :ref:`perf profiler ` trampoline on Alpine Linux
+with the musl C library on ``x86_64`` and ``aarch64``. The trampoline is
+architecture-specific and does not depend on the C library, so the same
+assembly trampoline used for glibc is reused for musl.
+
+..
+
+.. date: 2026-06-28-16-17-55
+.. gh-issue: 152502
+.. nonce: 6SNqMg
+.. section: Build
+
+The :mod:`curses` module now detects its optional functions with
+:program:`configure` capability probes instead of assuming ncurses, so it
+builds against narrow (non-wide) ncurses and other curses implementations
+such as NetBSD curses, exposing exactly the functions they provide.
+
+..
+
+.. date: 2026-06-26-16-30-00
+.. gh-issue: 152240
+.. nonce: loongarch
+.. section: Build
+
+Fix C stack unwinding tests on Linux LoongArch builds by teaching the manual
+frame pointer unwinder to recognize the LoongArch frame layout.
+
+..
+
+.. date: 2026-06-09-11-54-13
+.. gh-issue: 151163
+.. nonce: vFAtjv
+.. section: Build
+
+Updated Android build to include SQLite version 3.53.2.
+
+..
+
+.. date: 2026-05-27-14-28-36
+.. gh-issue: 115119
+.. nonce: wotFWh
+.. section: Build
+
+Fix the detection of libmpdec header when no .pc files are available.
+
+..
+
+.. date: 2026-05-21-15-14-59
+.. gh-issue: 148294
+.. nonce: VtFaW4
+.. section: Build
+
+Corrected the use of ``AC_PATH_TOOL`` in ``configure.ac`` to allow a C++
+compiler to be found on :envvar:`!PATH`.
+
+..
+
+.. date: 2026-05-19-12-45-23
+.. gh-issue: 131372
+.. nonce: oJykeB
+.. section: Build
+
+Add a :option:`--with-build-details-suffix` configure flag to allow Linux
+distributions that co-install multiple versions of Python in the same tree
+to avoid ``build-details.json`` clashes.
+
+..
+
+.. date: 2026-05-18-16-00-41
+.. gh-issue: 148260
+.. nonce: UwFiIX
+.. section: Build
+
+On Linux when Python is linked to the musl C library, use a thread stack
+size of at least 1 MiB instead of musl default which is 128 kiB. Patch by
+Victor Stinner.
+
+..
+
+.. date: 2026-04-21-17-27-52
+.. gh-issue: 148832
+.. nonce: Kx9aQ1
+.. section: Build
+
+Fix :option:`--enable-bolt` build by switching the default BOLT flag from
+``-icf=1`` to ``-icf=0``. ``-icf=1`` folds address-taken functions and
+breaks type-slot dispatch, crashing on :mod:`list` and :mod:`tuple`
+concatenation. Patched by Shamil Abdulaev.
+
+..
+
+.. date: 2026-03-11-17-23-39
+.. gh-issue: 144712
+.. nonce: fix-jit-entry
+.. section: Build
+
+Fix ``_testinternalcapi`` import failure due to missing ``_Py_jit_entry``
+symbol when built with :option:`--enable-experimental-jit`. Patch by Shamil
+Abdulaev.
+
+..
+
+.. date: 2026-03-07-02-09-57
+.. gh-issue: 138800
+.. nonce: VD8qbz
+.. section: Build
+
+Fix library name in python3.pc on Android.
+
+..
+
+.. date: 2025-09-25-01-33-12
+.. gh-issue: 139314
+.. nonce: _m9BUl
+.. section: Build
+
+Add the :option:`--with-zlib` and :option:`--with-bzip2`
+:program:`configure` options to select the zlib and bzip2 implementations
+used to build the :mod:`zlib` and :mod:`bz2` modules. In addition to the
+default system libraries, they can build against `zlib-rs
+`__ and `libbzip2-rs
+`__, and
+``--with-zlib=zlib-ng`` verifies that the detected zlib is `zlib-ng
+`__. :option:`--without-zlib` and
+:option:`--without-bzip2` exclude the modules from the build.
+
+..
+
+.. date: 2025-05-13-12-38-26
+.. gh-issue: 115119
+.. nonce: 7n0nx3
+.. section: Build
+
+Removed bundled copy of the libmpdec, use system library if it's available.
+Patch by Sergey B Kirpichev.
+
+..
+
+.. date: 2026-09-29-09-56-14
+.. gh-issue: 158010
+.. nonce: MPQX4w
+.. section: Windows
+
+Updated Windows builds to use OpenSSL 3.5.9.
+
+..
+
+.. date: 2026-09-21-20-54-37
+.. gh-issue: 157906
+.. nonce: RlyLkY
+.. section: Windows
+
+Fix an incorrect architecture macro check that prevented CPU prefetching in
+the free-threaded garbage collector on 32-bit Windows builds.
+
+..
+
+.. date: 2026-09-19-13-18-48
+.. gh-issue: 157789
+.. nonce: o6-rmo
+.. section: Windows
+
+Use compiler option ``-Og`` in case of clang-cl debug builds on Windows to
+reduce stack usage. Patch by Chris Eibl.
+
+..
+
+.. date: 2026-09-12-18-59-21
+.. gh-issue: 157368
+.. nonce: 2DirHP
+.. section: Windows
+
+Fix truncated :data:`sys.version` in the case of clang-cl versions 22 or
+newer on Windows. Also fixes the Windows on Arm case, where the Microsoft
+compiler was reported instead of clang. Patch by Chris Eibl.
+
+..
+
+.. date: 2026-09-10-02-00-00
+.. gh-issue: 157212
+.. nonce: x18TEB
+.. section: Windows
+
+Fix ``_Py_ThreadId()`` compilation on Windows ARM64 with MinGW toolchains,
+where ``__getReg()`` is unavailable. The TEB address is now read directly
+from ``x18``. Patch by Christian Aurich.
+
+..
+
+.. date: 2026-09-05-10-14-50
+.. gh-issue: 152433
+.. nonce: _LtjIg
+.. section: Windows
+
+Allow build :mod:`socket` module for Universal Windows Platform.
+
+..
+
+.. date: 2026-08-09-17-30-00
+.. gh-issue: 68048
+.. nonce: Mq8Vd4
+.. section: Windows
+
+Creating a :class:`mmap.mmap` object on Windows no longer resets the
+position of the underlying file to zero, as on other platforms.
+
+..
+
+.. date: 2026-08-09-15-40-00
+.. gh-issue: 85470
+.. nonce: Lm4Xt9
+.. section: Windows
+
+Importing :mod:`ctypes` on Windows no longer loads ``user32.dll``, which
+made the system treat the process as a GUI process and stop sending logoff
+and shutdown console control events to it. ``ole32.dll``, which pulled
+``user32.dll`` in, is now delay loaded.
+
+..
+
+.. date: 2026-08-09-14-20-00
+.. gh-issue: 72353
+.. nonce: Vw7Kq2
+.. section: Windows
+
+Reading from the console on Windows now continues if the read was cancelled
+by Ctrl+C, but the :const:`~signal.SIGINT` handler did not raise an
+exception. Previously the read ended as if at end of file.
+
+..
+
+.. date: 2026-08-09-05-30-00
+.. gh-issue: 86427
+.. nonce: legacystdio
+.. section: Windows
+
+Fix the encoding of the standard streams in the legacy Windows stdio mode
+(:envvar:`PYTHONLEGACYWINDOWSSTDIO`). It is now the encoding of the device
+the stream is connected to, as in Python 3.7, not the ANSI code page.
+
+..
+
+.. date: 2026-08-09-04-00-00
+.. gh-issue: 87587
+.. nonce: devenc
+.. section: Windows
+
+:func:`os.device_encoding` on Windows now returns the code page of any
+console file descriptor, not only 0, 1 and 2, and returns ``None`` for other
+character devices like ``NUL``. The UTF-8 code page is now reported as
+``"utf-8"`` instead of ``"cp65001"``.
+
+..
+
+.. date: 2026-08-02-12-00-00
+.. gh-issue: 152023
+.. nonce: wXn4Qs
+.. section: Windows
+
+Update Windows builds to SQLite 3.53.4. Additionally, enable the
+``median()`` and ``percentile()`` functions.
+
+..
+
+.. date: 2026-07-31-18-40-43
+.. gh-issue: 152433
+.. nonce: Pq3-U-
+.. section: Windows
+
+Changed :mod:`!winreg` to conditional import for Universal Windows Platform
+compatibility.
+
+..
+
+.. date: 2026-07-21-10-42-18
+.. gh-issue: 69573
+.. nonce: Kv7QpX
+.. section: Windows
+
+:func:`msvcrt.putch` and :func:`msvcrt.putwch` now check the return value of
+the underlying ``_putch()`` and ``_putwch()`` C functions and raise
+:exc:`OSError` on failure, for example when the process has no console
+attached, instead of silently ignoring the error.
+
+..
+
+.. date: 2026-07-18-11-56-53
+.. gh-issue: 124111
+.. nonce: m4OBX8
+.. section: Windows
+
+Updated Windows builds to use Tcl/Tk 9.0.4.
+
+..
+
+.. date: 2026-07-17-16-21-17
+.. gh-issue: 152433
+.. nonce: 45rR2A
+.. section: Windows
+
+Modernize fileutils removing GetFileInformationByHandle API calls and allow
+build for Universal Windows Platform.
+
+..
+
+.. date: 2026-07-04-20-12-24
+.. gh-issue: 152433
+.. nonce: NtWEoL
+.. section: Windows
+
+Allow build ``ceval.c`` for Windows UWP.
+
+..
+
+.. date: 2026-07-04-18-57-47
+.. gh-issue: 152433
+.. nonce: tO5k5t
+.. section: Windows
+
+Allow build :mod:`!_overlapped` module for Universal Windows Platform.
+
+..
+
+.. date: 2026-07-03-17-07-40
+.. gh-issue: 152433
+.. nonce: Lc6HmG
+.. section: Windows
+
+``_winapi`` module: improve UWP compatibility
+
+..
+
+.. date: 2026-07-01-17-31-05
+.. gh-issue: 152433
+.. nonce: dod-DF
+.. section: Windows
+
+make ``dynload_win.c`` UWP compatible.
+
+..
+
+.. date: 2026-07-01-17-00-52
+.. gh-issue: 152433
+.. nonce: kSd1bW
+.. section: Windows
+
+Allow build :mod:`!_ctypes` for Universal Windows Platform.
+
+..
+
+.. date: 2026-07-01-16-38-24
+.. gh-issue: 152433
+.. nonce: jvEiHh
+.. section: Windows
+
+:mod:`ssl`: improve UWP build compatibility.
+
+..
+
+.. date: 2026-06-30-16-40-00
+.. gh-issue: 152433
+.. nonce: VaeEwR
+.. section: Windows
+
+``_winapi``: implement ``GetVersion()`` UWP alternative.
+
+..
+
+.. date: 2026-06-29-17-17-10
+.. gh-issue: 152433
+.. nonce: AhW--j
+.. section: Windows
+
+Fix errors in :func:`sys.getwindowsversion` for Universal Windows Platform
+build.
+
+..
+
+.. date: 2026-06-29-16-29-50
+.. gh-issue: 152433
+.. nonce: _nhCjt
+.. section: Windows
+
+Restores the ``mmap`` module when CPython is built from source for specific
+Windows API sets.
+
+..
+
+.. date: 2026-06-28-13-03-57
+.. gh-issue: 152433
+.. nonce: jUXFwC
+.. section: Windows
+
+Use the Windows API ``GetFileSizeEx()`` for memory mapped files, rather than
+the older ``GetFileSize()``.
+
+..
+
+.. date: 2026-06-28-12-37-08
+.. gh-issue: 152433
+.. nonce: FTMgqF
+.. section: Windows
+
+Implement :func:`os.cpu_count` for Universal Windows Platform.
+
+..
+
+.. date: 2026-06-09-11-55-41
+.. gh-issue: 151163
+.. nonce: oizZYV
+.. section: Windows
+
+Updated Windows builds to include SQLite version 3.53.2.
+
+..
+
+.. date: 2026-06-04-18-53-18
+.. gh-issue: 150836
+.. nonce: Wci7bZ
+.. section: Windows
+
+Make installed tkinter work with Tcl/Tk 9 builds that embed the Tk script
+library in the Tk DLL on Windows.
+
+..
+
+.. date: 2026-05-14-22-09-46
+.. gh-issue: 149786
+.. nonce: UI-HZM
+.. section: Windows
+
+Fixes virtual environment launchers on Windows free-threaded builds.
+
+..
+
+.. date: 2026-04-29-14-44-51
+.. gh-issue: 138489
+.. nonce: 234aj6
+.. section: Windows
+
+Windows distributions now include a :file:`build-details.json` file (see
+:pep:`739`). The legacy installer does not install it, but all other
+distributions from python.org and all preset configurations in the
+``PC\layout`` script will include one.
+
+..
+
+.. date: 2026-04-21-16-07-11
+.. gh-issue: 140146
+.. nonce: TAcUHA
+.. section: Windows
+
+Prevent :mod:`tkinter` from hanging on Windows if stdin is redirected to a
+pipe in an interactive session. This is helpful for testing interactive
+usage of tkinter from a script, for example as part of the cpython test
+suite.
+
+..
+
+.. date: 2025-04-29-17-55-55
+.. gh-issue: 86768
+.. nonce: uIDTHc
+.. section: Windows
+
+:func:`os.lseek` and :meth:`~io.IOBase.seek` of file objects now raise
+:exc:`OSError` for pipes on Windows, and :meth:`~io.IOBase.seekable` now
+returns ``False`` for them. Previously seeking a pipe silently appeared to
+succeed. As a consequence, opening a pipe in a read-write binary mode
+(``'r+b'`` or ``'w+b'``) now raises :exc:`io.UnsupportedOperation` unless
+buffering is disabled.
+
+..
+
+.. bpo: 40851
+.. date: 2020-06-19-00-14-52
+.. nonce: 0-3EJP
+.. section: Windows
+
+:class:`subprocess.Popen` with ``shell=True`` on Windows now honors
+``wShowWindow`` of the *startupinfo* argument, so the console window of the
+started program can be shown. Previously it was always hidden.
+
+..
+
+.. date: 2026-09-29-09-29-17
+.. gh-issue: 158010
+.. nonce: 2zJnoj
+.. section: macOS
+
+Update macOS installer to use OpenSSL 3.5.9.
+
+..
+
+.. date: 2026-08-27-04-10-12
+.. gh-issue: 152023
+.. nonce: RNIecw
+.. section: macOS
+
+Update macOS installer builds to SQLite 3.53.4.
+
+..
+
+.. date: 2026-07-17-23-35-36
+.. gh-issue: 124111
+.. nonce: dmM4lk
+.. section: macOS
+
+Update macOS installer to use Tcl/Tk 9.0.4.
+
+..
+
+.. date: 2026-07-17-23-20-27
+.. gh-issue: 152023
+.. nonce: QAAgdj
+.. section: macOS
+
+Update macOS installer builds to SQLite 3.53.3. Enable median() and
+percentile() functions.
+
+..
+
+.. date: 2026-06-09-11-52-35
+.. gh-issue: 151163
+.. nonce: RlPXHq
+.. section: macOS
+
+Updated macOS installer to include SQLite version 3.53.2.
+
+..
+
+.. date: 2026-05-31-10-40-00
+.. gh-issue: 150644
+.. nonce: zLWyjj
+.. section: macOS
+
+When system logging is enabled (with ``config.use_system_logger``, messages
+are now tagged as public. This allows the macOS 26 system logger to view
+messages without special configuration.
+
+..
+
+.. date: 2026-09-24-12-00-00
+.. gh-issue: 158067
+.. nonce: opnPy1
+.. section: IDLE
+
+Fix the IDLE File Open dialog listing text files before Python files when
+opened from the Shell or an Output window.
+
+..
+
+.. date: 2026-09-17-23-00-00
+.. gh-issue: 56596
+.. nonce: capslock
+.. section: IDLE
+
+Make IDLE keyboard shortcuts with ascii letters work when Caps Lock is on
+even when only one of the upper and lowercase versions are defined.
+
+..
+
+.. date: 2026-09-17-22-00-00
+.. gh-issue: 75512
+.. nonce: asyncout
+.. section: IDLE
+
+Output from a thread printed in the IDLE Shell while a statement is being
+entered no longer takes over the prompt of the statement.
+
+..
+
+.. date: 2026-09-17-21-00-00
+.. gh-issue: 64007
+.. nonce: inputcolor
+.. section: IDLE
+
+IDLE no longer applies syntax coloring to the text entered for :func:`input`
+in the Shell.
+
+..
+
+.. date: 2026-09-17-18-00-00
+.. gh-issue: 85560
+.. nonce: elseexpr
+.. section: IDLE
+
+Fix IDLE failing to find the opening parenthesis when a continuation line
+inside the parentheses starts with ``else`` of a conditional expression or
+with ``yield``.
+
+..
+
+.. date: 2026-09-17-17-00-00
+.. gh-issue: 75487
+.. nonce: blankint
+.. section: IDLE
+
+Fix saving a truncated number when an integer entry in the IDLE Settings
+dialog is blanked with the Backspace key.
+
+..
+
+.. date: 2026-09-17-12-00-00
+.. gh-issue: 74112
+.. nonce: sigint
+.. section: IDLE
+
+Ctrl-C in the IDLE Shell now interrupts blocking calls such as
+:func:`time.sleep` and :meth:`socket.recv `.
+
+..
+
+.. date: 2026-09-17-08-53-12
+.. gh-issue: 151471
+.. nonce: -yvE03
+.. section: IDLE
+
+Colorize the soft keyword ``type`` in IDLE.
+
+..
+
+.. date: 2026-09-17-02-00-00
+.. gh-issue: 103089
+.. nonce: longline
+.. section: IDLE
+
+IDLE no longer hangs when opening a file with very long lines. Only the
+first 2,000 characters of a line are colorized.
+
+..
+
+.. date: 2026-09-17-01-00-00
+.. gh-issue: 89544
+.. nonce: rstbuf
+.. section: IDLE
+
+Fix IDLE hanging after Restart Shell while receiving a large output from the
+user process.
+
+..
+
+.. date: 2026-09-16-22-00-00
+.. gh-issue: 70331
+.. nonce: shadow
+.. section: IDLE
+
+IDLE no longer fails to start with ``python -m idlelib``, and its user
+process no longer fails to start, when the current directory contains user
+files with the same names as standard library modules that IDLE imports,
+such as ``random.py`` or ``tkinter.py``.
+
+..
+
+.. date: 2026-09-16-20-00-00
+.. gh-issue: 93016
+.. nonce: cliarg
+.. section: IDLE
+
+Fix parsing of command line arguments in the IDLE "Run... Customized" dialog
+on Windows: backslashes are no longer treated as escape characters. Fix also
+display of the previous arguments in the dialog.
+
+..
+
+.. date: 2026-09-16-18-00-00
+.. gh-issue: 59568
+.. nonce: tilde1
+.. section: IDLE
+
+Fix "Save As" and "Open" dialogs in IDLE for a file whose name starts with
+``~`` on Windows and X11 with Tcl/Tk older than 9.
+
+..
+
+.. date: 2026-09-15-23-27-38
+.. gh-issue: 69004
+.. nonce: Z7Ym9G
+.. section: IDLE
+
+The Debugger item of the IDLE Debug menu is now disabled while user code
+runs, like Stack Viewer.
+
+..
+
+.. date: 2026-09-15-22-34-33
+.. gh-issue: 69365
+.. nonce: KehjZN
+.. section: IDLE
+
+The IDLE search dialogs now show a regular expression error below the entry
+instead of in a message box.
+
+..
+
+.. date: 2026-09-15-22-10-17
+.. gh-issue: 93966
+.. nonce: ch4fTB
+.. section: IDLE
+
+The highlighting of a syntax error in the IDLE Shell is now removed when the
+next statement is entered, not only when the next syntax error occurs.
+
+..
+
+.. date: 2026-09-15-21-54-04
+.. gh-issue: 105689
+.. nonce: ASoU37
+.. section: IDLE
+
+Fix calltips, parenthesis matching and auto-indent in the IDLE Shell after
+output containing unbalanced quotes or parentheses.
+
+..
+
+.. date: 2026-09-15-21-44-35
+.. gh-issue: 60402
+.. nonce: iFz6X6
+.. section: IDLE
+
+In IDLE, Tab in a string that is not the start of a file name inserts a tab
+instead of opening the completion list.
+
+..
+
+.. date: 2026-09-15-21-20-04
+.. gh-issue: 68453
+.. nonce: hlxbog
+.. section: IDLE
+
+Fix running IDLE with the -s option together with -c, -r or -: the command
+or script now runs after the startup file, without an error dialog and
+without restarting the shell.
+
+..
+
+.. date: 2026-09-15-20-14-08
+.. gh-issue: 75234
+.. nonce: O8ZNFV
+.. section: IDLE
+
+Fix editing help sources and key bindings in the IDLE Settings dialog after
+selecting them with the keyboard.
+
+..
+
+.. date: 2026-09-15-16-37-19
+.. gh-issue: 69919
+.. nonce: f6AamT
+.. section: IDLE
+
+IDLE now reports any exception raised by compiling the source, such as
+:exc:`MemoryError` for too deeply nested source, instead of hanging the
+Shell.
+
+..
+
+.. date: 2026-09-15-16-19-25
+.. gh-issue: 91398
+.. nonce: PBdiDB
+.. section: IDLE
+
+Remove the border around the IDLE Shell sidebar, which was drawn in the
+window background color and stood out with dark themes.
+
+..
+
+.. date: 2026-09-15-15-46-35
+.. gh-issue: 71136
+.. nonce: vwGO0v
+.. section: IDLE
+
+Fix a hang of the IDLE Shell when code run under the debugger raises
+:exc:`KeyboardInterrupt`.
+
+..
+
+.. date: 2026-09-05-16-00-00
+.. gh-issue: 154511
+.. nonce: hV2wQn
+.. section: IDLE
+
+Consolidate IDLE's mouse wheel handling in ``idlelib.util``. ``wheel_event``
+moves there from ``idlelib.tree`` and joins ``x11_buttons``, which tells
+whether Tk reports wheel rotations to a widget as
+````/```` events, and ``bind_wheel``, which binds
+whichever events Tk sends.
+
+..
+
+.. date: 2026-09-03-17-16-26
+.. gh-issue: 156896
+.. nonce: XTQJlq
+.. section: IDLE
+
+Stop deleting tkinter submodules when idlelib.run is imported.
+
+..
+
+.. date: 2026-07-10-19-41-00
+.. gh-issue: 153480
+.. nonce: EdMt1x
+.. section: IDLE
+
+Fix IDLE failing to start when opening a file which does not exist yet. Fix
+a traceback when a file open in the IDLE editor is deleted by another
+program; IDLE now asks whether to close the window, save the file elsewhere,
+or ignore it.
+
+..
+
+.. date: 2026-07-01-21-00-00
+.. gh-issue: 55646
+.. nonce: kBind9
+.. section: IDLE
+
+Fix IDLE crash at startup when the user configuration contains an invalid
+key binding, such as ```` instead of ````. The
+invalid binding is now ignored with a warning.
+
+..
+
+.. date: 2026-07-01-19-00-00
+.. gh-issue: 82183
+.. nonce: rNsTrt
+.. section: IDLE
+
+When the shell is busy running code, using "Run... Customized" with "Restart
+shell" unchecked now reports that the shell is executing instead of
+restarting it anyway.
+
+..
+
+.. date: 2026-07-01-18-00-00
+.. gh-issue: 83653
+.. nonce: cFgInt
+.. section: IDLE
+
+Blanking an integer entry in IDLE's Settings dialog, such as "Auto squeeze
+min lines", no longer saves an empty string as an invalid configuration
+value.
+
+..
+
+.. date: 2026-07-01-17-00-00
+.. gh-issue: 65339
+.. nonce: oUtTxt
+.. section: IDLE
+
+Saving the IDLE Shell or an Output window now defaults to a ``.txt``
+extension and lists text files before Python files, since their content is
+not Python source.
+
+..
+
+.. date: 2026-07-01-16-00-00
+.. gh-issue: 80504
+.. nonce: gReP
+.. section: IDLE
+
+The "In files:" field of IDLE's Find in Files dialog now always contains a
+full directory path, even for an unsaved editor or the Shell. This shows in
+the grep output which directory was searched.
+
+..
+
+.. date: 2026-07-01-15-00-00
+.. gh-issue: 134300
+.. nonce: iDlPaT
+.. section: IDLE
+
+Do not add the ``idlelib`` directory to the path of the IDLE user process.
+User code run in IDLE can no longer import ``idlelib`` submodules as
+top-level modules, such as ``import help``.
+
+..
+
+.. date: 2026-07-01-14-00-00
+.. gh-issue: 89360
+.. nonce: mUlTiC
+.. section: IDLE
+
+Fix a rare crash in the IDLE editor when the completion window is closed:
+deleting a key binding for a sequence that is not bound to the virtual event
+is now ignored instead of raising a ``ValueError``.
+
+..
+
+.. date: 2026-07-01-13-30-00
+.. gh-issue: 66172
+.. nonce: Qm4xR7
+.. section: IDLE
+
+IDLE no longer fails to start when a user configuration file is corrupt. The
+unparsable file is renamed with a ".bad" suffix, default settings are used
+instead, and a warning lists the affected files.
+
+..
+
+.. date: 2026-07-01-12-00-00
+.. gh-issue: 71956
+.. nonce: rPlAlL
+.. section: IDLE
+
+Fix Replace All in the IDLE editor's Replace dialog when the search
+direction is "Up" and "Wrap around" is off: it now replaces all matches
+above the current position instead of only the first one.
+
+..
+
+.. date: 2026-07-01-00-15-58
+.. gh-issue: 152728
+.. nonce: yxIhMN
+.. section: IDLE
+
+Move functions run.fix_scaling, editor.fixwordbreaks (as fix_word_breaks)
+and pyshell.fix_x11_paste to idlelib.util.
+
+..
+
+.. date: 2026-07-01-00-00-00
+.. gh-issue: 66331
+.. nonce: wMcLaS
+.. section: IDLE
+
+Set the ``WM_CLASS`` window property of IDLE's windows to ``Idle`` on X11,
+so that window managers group and label them correctly instead of using the
+default ``Toplevel``.
+
+..
+
+.. date: 2026-06-28-06-46-46
+.. gh-issue: 85320
+.. nonce: Hq2vKn
+.. section: IDLE
+
+IDLE now reads and writes its configuration files and the breakpoints file
+using UTF-8 instead of the locale encoding. This keeps non-ASCII data (such
+as non-ASCII paths) from being corrupted and makes the files portable
+between environments.
+
+..
+
+.. date: 2026-06-27-17-27-21
+.. gh-issue: 90304
+.. nonce: 464d22
+.. section: IDLE
+
+Prevent IDLE from failing to start when a font reports a zero width for the
+``'0'`` character. Such a broken font caused a :exc:`ZeroDivisionError`;
+the editor now falls back to the configured width.
+
+..
+
+.. date: 2025-08-08-10-50-59
+.. gh-issue: 135511
+.. nonce: 9Rw5Zg
+.. section: IDLE
+
+Fix display of :exc:`NameError` and :exc:`AttributeError` with multi-line
+message.
+
+..
+
+.. bpo: 6699
+.. date: 2019-12-12-03-18-02
+.. nonce: 1CqJFG
+.. section: IDLE
+
+Warn the user if a file will be overwritten when saving.
+
+..
+
+.. date: 2026-09-30-06-55-37
+.. gh-issue: 158451
+.. nonce: pZE56z
+.. section: Tools/Demos
+
+``python-gdb.py`` is now able to format an invalid Unicode string: render
+invalid characters as ``\Uhhhhhhhh`` instead of raising an exception. Patch
+by Victor Stinner.
+
+..
+
+.. date: 2026-08-23-18-10-00
+.. gh-issue: 156261
+.. nonce: Rw8pKd
+.. section: Tools/Demos
+
+Argument Clinic: the ``pid_t``, ``uid_t``, ``gid_t``, ``Py_off_t``,
+``HANDLE``, ``DWORD`` and ``BOOL`` converters, previously defined in
+individual files, are now provided by Argument Clinic itself.
+
+..
+
+.. date: 2026-08-22-11-00-00
+.. gh-issue: 156219
+.. nonce: Wq2nRt
+.. section: Tools/Demos
+
+Fix Argument Clinic generating code which reads an optional positional
+argument which was not passed, if the function has a ``**kwds`` parameter.
+
+..
+
+.. date: 2026-08-14-13-15-35
+.. gh-issue: 113318
+.. nonce: oHjvUR
+.. section: Tools/Demos
+
+The value of a setter generated by Argument Clinic is now a parameter, which
+can use a converter, and a getter can define a return converter. It is
+optional to declare the value of the setter. The accessors of the same
+attribute are now identified by the Python name of that attribute instead of
+the C basename, so they can use different C basenames, and several
+implementations of the same accessor can be defined in different
+preprocessor conditional blocks.
+
+..
+
+.. date: 2026-08-14-12-45-57
+.. gh-issue: 113318
+.. nonce: G1B0oH
+.. section: Tools/Demos
+
+Fix Argument Clinic for ``@getter`` and ``@setter`` in a preprocessor
+conditional block. It failed with an internal error. Argument Clinic now
+also rejects the accessors of the same attribute with different C basenames,
+and the same accessor defined twice, which silently generated invalid or
+duplicated entries of :c:type:`PyGetSetDef`.
+
+..
+
+.. date: 2026-08-08-12-40-00
+.. gh-issue: 155373
+.. nonce: Wq3xTm
+.. section: Tools/Demos
+
+Argument Clinic now generates the inlined code of the converters for
+functions with optional groups, instead of a ``PyArg_ParseTuple()`` call for
+every number of arguments. Every argument is now parsed once, most such
+functions now use the fastcall convention, and the errors for a wrong type
+of an argument are the same as in other functions.
+
+..
+
+.. date: 2026-08-06-11-40-49
+.. gh-issue: 64660
+.. nonce: MswRQB
+.. section: Tools/Demos
+
+Argument Clinic return converters no longer need to hardcode the name of the
+variable returned by the parsing function. It is now available as
+``data.parser_retval``.
+
+..
+
+.. date: 2026-08-06-10-54-12
+.. gh-issue: 155266
+.. nonce: NEngp9
+.. section: Tools/Demos
+
+Fix Argument Clinic for a function whose only parameter is in an optional
+group. It generated ``METH_O``, which made the argument mandatory and did
+not pass the flag of the group.
+
+..
+
+.. date: 2026-08-06-09-43-16
+.. gh-issue: 64595
+.. nonce: W75XZK
+.. section: Tools/Demos
+
+Argument Clinic now touches the source file if a file generated from it was
+changed, and keeps the generated files newer than the source file. The build
+system does not know that the source file depends on the files generated
+from it, so it did not recompile the source file if only the generated file
+was changed.
+
+..
+
+.. date: 2026-08-06-08-32-53
+.. gh-issue: 155263
+.. nonce: RCcjtk
+.. section: Tools/Demos
+
+Add the ``--list`` option to Argument Clinic. It prints the modules, classes
+and functions which Argument Clinic defines in the specified files, each
+function with its signature.
+
+..
+
+.. date: 2026-08-05-18-56-17
+.. gh-issue: 107570
+.. nonce: wXxtw2
+.. section: Tools/Demos
+
+Argument Clinic: report errors on the offending line. Errors in a docstring
+were reported on the line which ends the block, and errors detected when
+generating the code were reported without any position.
+
+..
+
+.. date: 2026-08-05-18-16-24
+.. gh-issue: 108270
+.. nonce: kVDJSS
+.. section: Tools/Demos
+
+Argument Clinic: add support for deprecating a parameter with the ``[until
+X.Y]`` marker. Passing such argument emits a :exc:`DeprecationWarning`.
+
+..
+
+.. date: 2026-08-05-18-16-23
+.. gh-issue: 108271
+.. nonce: Yvq2Tv
+.. section: Tools/Demos
+
+Argument Clinic: add support for parameter aliases. A keyword-only parameter
+with a default value which shares the C name of a preceding parameter
+declares an alternative name for it.
+
+..
+
+.. date: 2026-08-05-14-02-55
+.. gh-issue: 155218
+.. nonce: Nq4xZv
+.. section: Tools/Demos
+
+Fix Argument Clinic generating the flags of the optional groups in different
+order on 32-bit and 64-bit platforms.
+
+..
+
+.. date: 2026-08-05-12-40-08
+.. gh-issue: 155212
+.. nonce: Lx8vTm
+.. section: Tools/Demos
+
+The ``--converters`` option of Argument Clinic now accepts file names and
+can be used with ``--make``. It prints the converters and return converters
+which the specified files define, instead of the built-in ones.
+
+..
+
+.. date: 2026-08-05-10-24-17
+.. gh-issue: 155207
+.. nonce: Wv3nKq
+.. section: Tools/Demos
+
+Argument Clinic now supports the ``--dry-run`` and ``--diff`` options. They
+list the files which would be changed, or write a unified diff of the
+changes to the standard output, without modifying any file.
+
+..
+
+.. date: 2026-08-04-19-05-41
+.. gh-issue: 64502
+.. nonce: Rb2wKt
+.. section: Tools/Demos
+
+Argument Clinic now supports several optional groups on the same nesting
+level, like in ``[y, x,] [n,] attr``. Such groups can be omitted
+independently of each other.
+
+..
+
+.. date: 2026-08-04-17-12-33
+.. gh-issue: 64502
+.. nonce: Qv7mLp
+.. section: Tools/Demos
+
+Fix Argument Clinic support of parameters with a default value used together
+with optional groups. Such parameters were always required in the generated
+parsing code.
+
+..
+
+.. date: 2026-07-24-09-30-00
+.. gh-issue: 154580
+.. nonce: Kp3nQ2
+.. section: Tools/Demos
+
+Fix ``python-gdb.py`` raising :exc:`UnicodeEncodeError` when pretty-printing
+a non-ASCII :class:`str` in a locale whose host charset cannot encode it,
+such as any non-ASCII string in the C locale.
+
+..
+
+.. date: 2026-07-19-00-00-00
+.. gh-issue: 154059
+.. nonce: JiBcOM
+.. section: Tools/Demos
+
+Fix the time units in Tachyon flame graph tooltips by accounting for the
+sampling interval when converting samples to milliseconds.
+
+..
+
+.. date: 2026-07-16-11-38-15
+.. gh-issue: 153804
+.. nonce: KSTYg7
+.. section: Tools/Demos
+
+Add ``Tools/inspection/oracle_external_inspection.py``, a harness for
+measuring the accuracy of Tachyon. It reports impossible-stack rates, speed,
+error rates and the statistical distance from the blocking non-cached best
+reference on selected snippets. Patch by Maurycy Pawłowski-Wieroński.
+
+..
+
+.. date: 2026-07-10-14-38-31
+.. gh-issue: 152384
+.. nonce: uaPADM
+.. section: Tools/Demos
+
+The CPython Pixi packages are now all accessible at the same
+``Tools/pixi-packages`` subdirectory, rather than at
+``Tools/pixi-packages/{variant}`` as before. Variants are now selected not
+via subdirectory but via ``flags``; see
+https://pixi.prefix.dev/latest/concepts/package_specifications/#extras-and-flags
+for usage instructions. The ``tsan-freethreading`` variant has been renamed
+to ``tsan_freethreading``, while the ``default``, ``asan``, and
+``freethreading`` variants retain their previous names.
+
+..
+
+.. date: 2026-05-22-18-51-09
+.. gh-issue: 150258
+.. nonce: dh8GVK
+.. section: Tools/Demos
+
+Update the tooltip on the Tachyon flame graph to show both absolute and
+relative percentages.
+
+..
+
+.. date: 2026-02-28-20-35-47
+.. gh-issue: 87613
+.. nonce: Nwzu6U
+.. section: Tools/Demos
+
+Add a ``@vectorcall`` decorator to Argument Clinic to generate
+:ref:`vectorcall` parsing code for :func:`object.__init__` and
+:func:`object.__new__`.
+
+..
+
+.. date: 2025-02-27-19-00-00
+.. gh-issue: 130647
+.. nonce: uwda2h
+.. section: Tools/Demos
+
+Add ``--omit-header`` option to :program:`pygettext`.
+
+..
+
+.. date: 2024-06-17-13-52-04
+.. gh-issue: 111501
+.. nonce: syFLAV
+.. section: Tools/Demos
+
+PS1 is no longer exported by venv activate script
+
+..
+
+.. date: 2026-10-11-06-20-11
+.. gh-issue: 129724
+.. nonce: Wq3nTb
+.. section: C API
+
+Make :c:func:`PyMarshal_WriteObjectToFile` write nothing to the file if the
+object cannot be marshalled, instead of partial data.
+
+..
+
+.. date: 2026-10-05-17-09-35
+.. gh-issue: 149044
+.. nonce: 1HUiag
+.. section: C API
+
+Fix the :c:macro:`PySlot_END` macro for C++: initialize all members to avoid
+compiler warnings. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-10-05-15-24-22
+.. gh-issue: 158842
+.. nonce: g7eLtE
+.. section: C API
+
+Add :c:macro:`Py_SETREF` and :c:macro:`Py_XSETREF` macros to the limited C
+API. Patch by Nathan Goldbaum and Victor Stinner.
+
+..
+
+.. date: 2026-10-05-01-09-32
+.. gh-issue: 158810
+.. nonce: F1p-PK
+.. section: C API
+
+Fix :c:macro:`Py_ARRAY_LENGTH()` macro on C++: do not use
+``__builtin_types_compatible_p()`` on C++. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-09-30-03-19-34
+.. gh-issue: 158451
+.. nonce: pUb2BJ
+.. section: C API
+
+Fix :c:func:`!_PyUnicodeWriter_WriteLatin1String` when the writer buffer
+kind is UCS-2 or UCS-4. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-09-29-19-01-56
+.. gh-issue: 158439
+.. nonce: ybKo_6
+.. section: C API
+
+If :c:func:`PyUnicodeWriter_WriteUTF8` or :c:func:`PyUnicodeWriter_Format`
+fails, :c:func:`PyUnicodeWriter_Finish` now checks if the string uses the
+most efficient storage. Previously, :c:func:`PyUnicodeWriter_Finish` could
+return a string with an inefficient storage. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-09-24-15-27-35
+.. gh-issue: 158080
+.. nonce: YIqypf
+.. section: C API
+
+Deprecate :c:func:`PyInitConfig_GetExitCode`, :c:func:`PyStatus_Exit`, and
+:c:func:`PyStatus_IsExit` functions, and :c:member:`PyStatus.exitcode`
+member. :c:func:`Py_InitializeFromInitConfig` and
+:c:func:`Py_InitializeFromConfig` can no longer return an exit code.
+Instead, if a command line option wants to exit Python, the option is now
+processed in :c:func:`Py_RunMain`. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-09-24-14-14-34
+.. gh-issue: 154757
+.. nonce: -b-Fs7
+.. section: C API
+
+:c:func:`PyModule_GetFilename` is no longer deprecated, but using
+:c:func:`PyModule_GetFilenameObject` instead is still recommended. Patch by
+Victor Stinner.
+
+..
+
+.. date: 2026-09-24-11-47-32
+.. gh-issue: 157649
+.. nonce: 3HSU2h
+.. section: C API
+
+Fix :c:macro:`Py_CLEAR` and :c:macro:`Py_SETREF` macros on C++: implement
+them using ``auto`` instead of ``decltype()``. Using ``decltype()``
+produced invalid code when clearing/setting an array item. Patch by Victor
+Stinner.
+
+..
+
+.. date: 2026-09-23-23-52-55
+.. gh-issue: 154757
+.. nonce: EUVFeZ
+.. section: C API
+
+Remove :c:func:`!PyEval_InitThreads` function which did nothing since Python
+3.7 and was deprecated since Python 3.9. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-09-23-21-45-43
+.. gh-issue: 158001
+.. nonce: R_wX4E
+.. section: C API
+
+Remove :c:func:`!Py_SetProgramName`, :c:func:`!Py_SetPythonHome`,
+:c:func:`!PySys_SetArgv` and :c:func:`!PySys_SetArgvEx` functions,
+deprecated since Python 3.11. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-09-23-19-37-53
+.. gh-issue: 158001
+.. nonce: X_Xamm
+.. section: C API
+
+Remove 21 global configuration variables:
+
+* :c:var:`!Py_BytesWarningFlag`,
+* :c:var:`!Py_DebugFlag`,
+* :c:var:`!Py_DontWriteBytecodeFlag`,
+* :c:var:`!Py_FileSystemDefaultEncodeErrors`,
+* :c:var:`!Py_FileSystemDefaultEncoding`,
+* :c:var:`!Py_FrozenFlag`,
+* :c:var:`!Py_HasFileSystemDefaultEncoding`,
+* :c:var:`!Py_HashRandomizationFlag`,
+* :c:var:`!Py_IgnoreEnvironmentFlag`,
+* :c:var:`!Py_InspectFlag`,
+* :c:var:`!Py_InteractiveFlag`,
+* :c:var:`!Py_IsolatedFlag`,
+* :c:var:`!Py_LegacyWindowsFSEncodingFlag`,
+* :c:var:`!Py_LegacyWindowsStdioFlag`,
+* :c:var:`!Py_NoSiteFlag`,
+* :c:var:`!Py_NoUserSiteDirectory`,
+* :c:var:`!Py_OptimizeFlag`,
+* :c:var:`!Py_QuietFlag`,
+* :c:var:`!Py_UTF8Mode`,
+* :c:var:`!Py_UnbufferedStdioFlag`,
+* :c:var:`!Py_VerboseFlag`.
+
+Patch by Victor Stinner.
+
+..
+
+.. date: 2026-09-22-23-20-53
+.. gh-issue: 148233
+.. nonce: U_2x-F
+.. section: C API
+
+Add :c:func:`Py_HashBuffer` to the limited C API. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-09-18-00-29-49
+.. gh-issue: 157710
+.. nonce: Q_AD8D
+.. section: C API
+
+When Python is built in debug mode, :c:func:`PyUnicodeWriter_Finish` now
+checks if the trailing null byte has been overridden to detect buffer
+overflow. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-09-17-23-18-12
+.. gh-issue: 157710
+.. nonce: 1xKQAH
+.. section: C API
+
+Soft deprecate functions modifying Unicode strings: :c:func:`PyUnicode_New`,
+:c:func:`PyUnicode_CopyCharacters`, :c:func:`PyUnicode_Fill`,
+:c:func:`PyUnicode_Resize`, :c:func:`PyUnicode_WRITE` and
+:c:func:`PyUnicode_WriteChar`. Use the :c:type:`PyUnicodeWriter` API
+instead. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-09-16-21-24-36
+.. gh-issue: 142217
+.. nonce: 44sqt4
+.. section: C API
+
+Add tests on the undocumented and deprecated ``_Py_Identifier`` C API. Patch
+by Victor Stinner.
+
+..
+
+.. date: 2026-09-14-18-07-43
+.. gh-issue: 140550
+.. nonce: fLVOGn
+.. section: C API
+
+Fix the :c:macro:`PyABIInfo_VAR` macro: remove redundant ``;``. Before,
+``PyABIInfo_VAR(abi_info);`` code added two ``;;`` which is illegal in
+C++03. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-09-14-16-10-23
+.. gh-issue: 157495
+.. nonce: LzMLtE
+.. section: C API
+
+If ``typeof()`` is available, implement :c:macro:`Py_MIN`, :c:macro:`Py_MAX`
+and :c:macro:`Py_ABS` using ``typeof()`` and statement expression to only
+evaluate each argument once. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-09-12-18-37-22
+.. gh-issue: 157384
+.. nonce: LGsy8K
+.. section: C API
+
+:c:func:`PyImport_CreateModuleFromInitfunc` now sets the package context
+while calling *initfunc*, so that a single-phase init submodule created with
+only the last component of its name gets the full name from the spec.
+
+..
+
+.. date: 2026-09-10-15-19-16
+.. gh-issue: 155526
+.. nonce: kMKhyp
+.. section: C API
+
+:c:func:`_Py_c_abs` no longer sets :c:data:`errno` to zero on success, but
+rather leaves it unchanged. Patch by Sergey B Kirpichev.
+
+..
+
+.. date: 2026-09-10-02-51-26
+.. gh-issue: 157242
+.. nonce: tfXIsf
+.. section: C API
+
+Fix :c:func:`PyBytesWriter_Resize` to handle properly memory allocation
+failure. Leave the writer unchanged on error, instead of leaving it in an
+inconsistent state. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-09-04-16-41-07
+.. gh-issue: 156939
+.. nonce: bKaQuE
+.. section: C API
+
+When Python is built in debug mode, :c:type:`PyBytesWriter` now detects
+buffer overflow. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-08-31-19-14-15
+.. gh-issue: 156101
+.. nonce: d4PSIF
+.. section: C API
+
+Don't set the result in error in :c:func:`PyLong_AsInt32`,
+:c:func:`PyLong_AsUInt32`, :c:func:`PyLong_AsInt64` and
+:c:func:`PyLong_AsUInt64`. Leave the result unchanged in this case. Patch by
+Victor Stinner.
+
+..
+
+.. date: 2026-08-25-12-00-00
+.. gh-issue: 131740
+.. nonce: Ft7Rz2
+.. section: C API
+
+On the free-threaded build, :c:func:`PyUnstable_GC_VisitObjects` now also
+visits frozen objects (objects moved to the permanent generation by
+:func:`gc.freeze`), matching the behavior of the default build.
+
+..
+
+.. date: 2026-08-16-20-48-08
+.. gh-issue: 155907
+.. nonce: Vb3xTn
+.. section: C API
+
+:c:func:`PyMarshal_ReadObjectFromFile` and other functions reading
+marshalled data from a :c:expr:`FILE*` now raise :exc:`OSError` for I/O
+errors and :exc:`KeyboardInterrupt` for interrupted reading, instead of
+:exc:`EOFError`. :c:func:`PyMarshal_WriteObjectToFile` and
+:c:func:`PyMarshal_WriteLongToFile` now detect I/O errors and interrupted
+writing instead of ignoring them. :c:func:`PyMarshal_WriteObjectToFile` now
+also sets the error indicator if the value cannot be marshalled.
+
+..
+
+.. date: 2026-08-14-14-47-08
+.. gh-issue: 155742
+.. nonce: UGI3Pn
+.. section: C API
+
+:c:func:`PyBytesWriter_FinishWithSize` now returns single byte singletons if
+*size* equals to ``1``. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-07-30-16-58-36
+.. gh-issue: 152105
+.. nonce: 1Jz1YH
+.. section: C API
+
+Remove the :c:var:`!PyUnstable_ExecutableKinds` array, as well as the macros
+:c:macro:`!PyUnstable_EXECUTABLE_KIND_SKIP`,
+:c:macro:`!PyUnstable_EXECUTABLE_KIND_PY_FUNCTION`,
+:c:macro:`!PyUnstable_EXECUTABLE_KIND_BUILTIN_FUNCTION`,
+:c:macro:`!PyUnstable_EXECUTABLE_KIND_METHOD_DESCRIPTOR` and
+:c:macro:`!PyUnstable_EXECUTABLE_KINDS`, from the C API.
+
+..
+
+.. date: 2026-07-28-04-29-52
+.. gh-issue: 153740
+.. nonce: 7_LMSA
+.. section: C API
+
+If available on the platform, use native :c:type:`_Float16` in
+:c:func:`PyFloat_Pack2` and :c:func:`PyFloat_Unpack2` functions. Patch by
+Sergey B Kirpichev.
+
+..
+
+.. date: 2026-07-09-17-33-29
+.. gh-issue: 152132
+.. nonce: Ma8MJZ
+.. section: C API
+
+Fix :c:func:`Py_RunMain` to return an exit code, rather than calling
+:c:func:`Py_Exit`, when running a script, a command, or the REPL. Patch by
+Victor Stinner.
+
+..
+
+.. date: 2026-07-09-16-46-30
+.. gh-issue: 145633
+.. nonce: jyNwAs
+.. section: C API
+
+:c:func:`PyFloat_Pack8` and ``PyFloat_Unpack*`` functions are no longer
+guaranteed to always succeed on CPython.
+
+..
+
+.. date: 2026-07-08-00-38-32
+.. gh-issue: 153300
+.. nonce: lVoWyR
+.. section: C API
+
+:c:func:`PyConfig_Set()` now also set global configuration variables. For
+example, ``PyConfig_Set("inspect", value)`` now also sets
+:c:var:`!Py_InspectFlag`. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-06-18-18-24-11
+.. gh-issue: 141510
+.. nonce: -EOHJ1
+.. section: C API
+
+Add :class:`frozendict` to the fast paths of
+:c:func:`PyMapping_GetOptionalItem`, :c:func:`PyMapping_Keys`,
+:c:func:`PyMapping_Values`, and :c:func:`PyMapping_Items`.
+
+..
+
+.. date: 2026-06-10-16-43-37
+.. gh-issue: 123619
+.. nonce: dV82r6
+.. section: C API
+
+:c:func:`PyUnstable_Object_EnableDeferredRefcount` now returns ``0`` if the
+object is not tracked by the garbage collector: if :func:`gc.is_tracked` is
+false. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-06-10-15-22-44
+.. gh-issue: 149044
+.. nonce: O7KEcs
+.. section: C API
+
+Improved error message when specifying non-type base classes in
+:c:macro:`Py_tp_bases`, :c:macro:`Py_tp_base`, and *bases* argument to
+:c:func:`PyType_FromMetaclass` and other ``PyType_From*`` functions.
+
+..
+
+.. date: 2026-06-09-14-50-35
+.. gh-issue: 80384
+.. nonce: UEGyvB
+.. section: C API
+
+:c:func:`PyWeakref_NewRef` and :c:func:`PyWeakref_NewProxy` now raise
+:exc:`TypeError` if the *callback* argument is not callable, ``None``, or
+``NULL``.
+
+..
+
+.. date: 2026-06-04-14-26-17
+.. gh-issue: 150907
+.. nonce: CA91_B
+.. section: C API
+
+Fix ``dynamic_annotations.h`` header file when built with C++ and Valgrind:
+add ``extern "C++" scope`` for the C++ template. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-05-31-15-39-58
+.. gh-issue: 150671
+.. nonce: bTkDVC
+.. section: C API
+
+Deprecate these C-API functions: :c:func:`PyGen_New`,
+:c:func:`PyGen_NewWithQualName`, :c:func:`PyCoro_New`, and
+:c:func:`PyAsyncGen_New`. Schedule them for removal in 3.18
+
+..
+
+.. date: 2026-05-12-16-47-21
+.. gh-issue: 149725
+.. nonce: HZLBTZ
+.. section: C API
+
+Add :c:func:`PySentinel_CheckExact` for exact :class:`sentinel` type tests
+to accompany the existing :c:func:`PySentinel_Check`.
+
+..
+
+.. date: 2026-02-25-13-37-10
+.. gh-issue: 145235
+.. nonce: -1ySNR
+.. section: C API
+
+Made :c:func:`PyDict_AddWatcher`, :c:func:`PyDict_ClearWatcher`,
+:c:func:`PyDict_Watch`, and :c:func:`PyDict_Unwatch` thread-safe on the
+:term:`free threaded ` build.
+
+..
+
+.. date: 2024-08-12-09-48-04
+.. gh-issue: 122931
+.. nonce: x435Mb
+.. section: C API
+
+Allow importing stable ABI C extensions that include a multiarch tuple in
+their filename, e.g. ``foo.abi3-x86-64-linux-gnu.so``.
+
+..
+
+.. bpo: 32414
+.. date: 2018-05-16-13-47-18
+.. nonce: NODPbj
+.. section: C API
+
+:c:func:`PyCapsule_Import` now imports submodules if needed. Previously
+names like ``package.module.attribute`` worked only if ``package.module``
+was already imported.
diff --git a/Misc/NEWS.d/3.16.0a2.rst b/Misc/NEWS.d/3.16.0a2.rst
new file mode 100644
index 000000000000000..629953ebd574298
--- /dev/null
+++ b/Misc/NEWS.d/3.16.0a2.rst
@@ -0,0 +1,4357 @@
+.. cve: CVE-2026-115791
+.. date: 2026-11-07-15-56-47
+.. gh-issue: 161705
+.. nonce: OjDK2d
+.. release date: 2026-11-10
+.. section: Security
+
+Remove ``sys.path[0]`` in :mod:`gzip`, :mod:`tarfile` and :mod:`zipfile`
+command line interface to prevent shadowing standard library modules from
+extracted files. Issue reported by Jelle Zijlstra, patch by Gregory P. Smith
+and Victor Stinner.
+
+..
+
+.. cve: CVE-2026-124249
+.. date: 2026-11-07-01-43-49
+.. gh-issue: 161569
+.. nonce: cookiej
+.. section: Security
+
+Fix :class:`http.cookiejar.CookieJar` deleting a stored cookie when a
+response from an unrelated host sets an already expired cookie with a
+``Domain`` or ``Path`` attribute pointing at that cookie. The cookie policy
+is now consulted before an expired cookie is allowed to delete an existing
+one.
+
+..
+
+.. cve: CVE-2026-19552
+.. date: 2026-11-06-16-22-47
+.. gh-issue: 161503
+.. nonce: FkIl87
+.. section: Security
+
+:func:`ssl.get_server_certificate` now verifies that the server hostname
+matches its certificate when the caller specifies *ca_certs*.
+
+..
+
+.. date: 2026-11-02-18-30-09
+.. gh-issue: 161192
+.. nonce: 2ScSRO
+.. section: Security
+
+Update bundled `libexpat `_ to version 2.10.0
+for the fixes to :cve:`2026-113351`, :cve:`2026-115506`, :cve:`2026-117610`
+and :cve:`2026-118370`.
+
+..
+
+.. cve: CVE-2026-116566
+.. date: 2026-10-27-16-25-40
+.. gh-issue: 160898
+.. nonce: epi53X
+.. section: Security
+
+:func:`socket.getaddrinfo` now rejects null bytes within *host* and *port*
+parameters as this previously caused the values to be silently truncated.
+
+..
+
+.. cve: CVE-2026-115559
+.. date: 2026-10-22-21-59-39
+.. gh-issue: 160369
+.. nonce: imapTLS
+.. section: Security
+
+:meth:`imaplib.IMAP4.starttls` now rejects unexpected plaintext buffered
+after the STARTTLS response, preventing it from being processed as
+TLS-protected data.
+
+..
+
+.. date: 2026-10-22-11-09-30
+.. gh-issue: 160279
+.. nonce: 9BtxeF
+.. section: Security
+
+Prevent :mod:`venv` from importing modules from the root of an existing
+virtual environment when installing or upgrading pip.
+
+..
+
+.. date: 2026-10-22-08-08-57
+.. gh-issue: 160499
+.. nonce: pf9H9g
+.. section: Security
+
+Fix unbounded memory growth in :mod:`asyncio` TLS connections when a peer
+stops reading but keeps sending records that make OpenSSL generate its own
+replies (such as TLS 1.2 renegotiation alerts). Reading from the peer is
+now paused when this output accumulates, instead of only when application
+data does.
+
+..
+
+.. date: 2026-10-22-08-08-23
+.. gh-issue: 160506
+.. nonce: rN4dLq
+.. section: Security
+
+Fix :func:`os.path.realpath` on Windows returning the wrong path for a
+broken relative symbolic link reached through a symbolic link to a
+directory. This allowed :mod:`tarfile` extraction with the ``'data'`` or
+``'tar'`` filter to create a file outside the destination directory.
+
+..
+
+.. date: 2026-10-22-08-07-52
+.. gh-issue: 161323
+.. nonce: q7Drv2
+.. section: Security
+
+On Windows, the ``'tar'`` and ``'data'`` :mod:`tarfile` extraction filters
+now refuse member names and link targets that have a drive but are not
+absolute, such as ``C:foo``, with :exc:`~tarfile.AbsolutePathError` or
+:exc:`~tarfile.AbsoluteLinkError`. Such members could be extracted outside
+the destination directory. Fixes :cve:`2026-107784`.
+
+..
+
+.. date: 2026-10-22-08-05-32
+.. gh-issue: 160420
+.. nonce: tZ9dRv
+.. section: Security
+
+Fix :class:`zoneinfo.ZoneInfo` on Windows accepting keys in which a
+component after a ``/`` starts with a drive letter, such as
+``America/C:\file``. Such a key could open a file outside the ``tzdata``
+package; it now raises :exc:`ValueError`.
+
+..
+
+.. date: 2026-10-22-08-04-33
+.. gh-issue: 160300
+.. nonce: q7Zk2B
+.. section: Security
+
+Fix :class:`http.cookiejar.DefaultCookiePolicy` accepting and returning
+cookies with a negative ``Version`` attribute without checking their domain
+against the request host. Such cookies are now ignored.
+
+..
+
+.. cve: CVE-2026-114583
+.. date: 2026-10-21-19-58-53
+.. gh-issue: 160097
+.. nonce: -opfAL
+.. section: Security
+
+:func:`tarfile.tar_filter` now rejects link members whose path resolves to
+the destination directory itself, as :func:`tarfile.data_filter` already
+did.
+
+..
+
+.. cve: CVE-2026-115557
+.. date: 2026-10-21-16-55-07
+.. gh-issue: 160040
+.. nonce: 9PjFjC
+.. section: Security
+
+:mod:`ssl` now rejects TLS certificate chains that contain any of a set of
+compromised eMudhra intermediate CA keys. This is an extraordinary measure
+and a last line of defense: removing trust is primarily the job of the
+platform root store, and the built-in denylist only blocks connections while
+that update has not yet reached the OS, a container image, or a bundled
+trust store in various Python packages. Entries are added to the denylist
+only under a very high threshold. The denylist matches on the public key
+(the SHA-256 digest of the :rfc:`5280` ``SubjectPublicKeyInfo``), so it also
+covers the cross-signed certificates that reuse one of the distrusted keys.
+
+..
+
+.. date: 2026-10-20-13-15-00
+.. gh-issue: 159894
+.. nonce: 8Kp4mN
+.. section: Security
+
+Bump the version of :pypi:`pip` bundled in :mod:`ensurepip` to version
+26.2.2.
+
+..
+
+.. date: 2026-10-15-03-47-08
+.. gh-issue: 159428
+.. nonce: XHRKwY
+.. section: Security
+
+:mod:`mimetypes` no longer reads the files listed in
+:data:`mimetypes.knownfiles` by default on Windows, and uses only the
+registry.
+
+..
+
+.. date: 2026-10-06-12-30-00
+.. gh-issue: 158928
+.. nonce: Zd9Ybv
+.. section: Security
+
+Fix a buffer overflow when initializing a :class:`bytearray` from an
+iterator.
+
+..
+
+.. date: 2026-08-31-16-47-33
+.. gh-issue: 157953
+.. nonce: KxCFSN
+.. section: Security
+
+Update bundled `libexpat `_ to version 2.9.0.
+
+..
+
+.. date: 2026-11-09-14-30-00
+.. gh-issue: 160267
+.. nonce: sTfrEe
+.. section: Core and Builtins
+
+Fix a crash when :mod:`profiling.sampling` profiles a process that creates
+and destroys threads or subinterpreters quickly. Memory of deleted thread
+and interpreter states is now reused for new states instead of being freed
+until the runtime is finalized.
+
+..
+
+.. date: 2026-11-07-09-30-00
+.. gh-issue: 161420
+.. nonce: mIdFre
+.. section: Core and Builtins
+
+Restore ``mimalloc``'s previous behavior of processing delayed frees from
+other threads on every generic malloc call, reverting the change introduced
+in v2.2.2.
+
+..
+
+.. date: 2026-11-06-21-21-04
+.. gh-issue: 161242
+.. nonce: d4vNgC
+.. section: Core and Builtins
+
+Speed up :exc:`AttributeError`, :exc:`ImportError` and :exc:`NameError` by
+enabling :ref:`vectorcall`. Unexpected keyword arguments are now reported by
+name.
+
+..
+
+.. date: 2026-11-06-15-15-00
+.. gh-issue: 161433
+.. nonce: A9b3Kq
+.. section: Core and Builtins
+
+Add context notes to :exc:`TypeError` raised while hashing a :class:`tuple`,
+identifying the index of the item whose hash failed.
+
+..
+
+.. date: 2026-11-06-02-30-00
+.. gh-issue: 129724
+.. nonce: Mn8sLq
+.. section: Core and Builtins
+
+Fix the :mod:`marshal` output of compiled code, and so ``.pyc`` files,
+differing for the same source depending on what ran before in the process.
+This affected private names in classes with non-ASCII names, and
+:func:`compile` of an AST with names not created by :func:`ast.parse`.
+
+..
+
+.. date: 2026-11-05-21-00-57
+.. gh-issue: 161366
+.. nonce: ouxAvv
+.. section: Core and Builtins
+
+Fix a deadlock in the garbage collector of the :term:`free-threaded build`
+when :data:`gc.DEBUG_COLLECTABLE` is set and another thread is writing to
+:data:`sys.stderr`. The debug output is now written after the other threads
+are resumed.
+
+..
+
+.. date: 2026-11-05-10-19-48
+.. gh-issue: 161419
+.. nonce: wc4DV0
+.. section: Core and Builtins
+
+Fix a crash in the :term:`free-threaded build` where a weak reference could
+revive an object whose finalizer had already run during deallocation,
+causing it to be deallocated twice.
+
+..
+
+.. date: 2026-11-03-20-28-15
+.. gh-issue: 161288
+.. nonce: LikC_U
+.. section: Core and Builtins
+
+Fix a crash in the perf trampoline (:option:`-X perf <-X>`) on builds with
+clang's ``-fsanitize=function``, which ``-fsanitize=undefined`` enables
+since clang 17.
+
+..
+
+.. date: 2026-11-03-13-44-26
+.. gh-issue: 159184
+.. nonce: X_sOdY
+.. section: Core and Builtins
+
+Fix a leak of NaN constants in code objects created by :func:`marshal.loads`
+on the free-threaded build.
+
+..
+
+.. date: 2026-11-03-05-52-49
+.. gh-issue: 161229
+.. nonce: 8pOPOI
+.. section: Core and Builtins
+
+:func:`!__lazy_import__` now treats ``None`` for *globals* and *locals* the
+same as omitting them, matching its signature.
+
+..
+
+.. date: 2026-11-02-05-50-35
+.. gh-issue: 160872
+.. nonce: x8NvzN
+.. section: Core and Builtins
+
+Optimize division and remainder operations on large :class:`int` values.
+
+..
+
+.. date: 2026-10-28-13-47-43
+.. gh-issue: 160773
+.. nonce: 7VFxkA
+.. section: Core and Builtins
+
+Fix a crash in :func:`str` of an :exc:`OSError` when formatting one of its
+attributes modifies the others.
+
+..
+
+.. date: 2026-10-26-12-00-00
+.. gh-issue: 160682
+.. nonce: Q7mK2x
+.. section: Core and Builtins
+
+Fix a bug in the :term:`free-threaded build` where garbage collection could
+prematurely collect the function object of a running method.
+
+..
+
+.. date: 2026-10-24-19-07-34
+.. gh-issue: 153568
+.. nonce: 6sVdqs
+.. section: Core and Builtins
+
+Speed up :func:`ast.parse` by ~15.8% and reduce the memory used by ~51.6% by
+storing node attributes as inline values instead of in a per-node
+dictionary.
+
+..
+
+.. date: 2026-10-23-20-15-24
+.. gh-issue: 160491
+.. nonce: yIQ_Vf
+.. section: Core and Builtins
+
+Fix the location reported for invalid escape sequences in f-strings and
+t-strings. The :exc:`SyntaxError` now points at the literal part that
+contains the escape, instead of at the closing quote.
+
+..
+
+.. date: 2026-10-23-19-37-00
+.. gh-issue: 160050
+.. nonce: aB3x9Q
+.. section: Core and Builtins
+
+Use asymptotically faster :func:`divmod` implementation for integer modulo
+of large integers.
+
+..
+
+.. date: 2026-10-22-17-37-27
+.. gh-issue: 160268
+.. nonce: gJ2iDx
+.. section: Core and Builtins
+
+Fix a crash in :mod:`tokenize` when a mismatched closing bracket follows the
+opening brace of an f-string or t-string replacement field, as in
+``f'{]a'``. It now raises the same "unmatched" error as the parser.
+
+..
+
+.. date: 2026-10-22-14-45-00
+.. gh-issue: 160245
+.. nonce: mEmO24
+.. section: Core and Builtins
+
+Reduce the size of parser memo entries on 64-bit platforms by reordering
+fields to remove padding. Patch by Shamil Abdulaev.
+
+..
+
+.. date: 2026-10-22-12-30-11
+.. gh-issue: 106045
+.. nonce: fkMW34
+.. section: Core and Builtins
+
+Fix :mod:`venv` path discovery when the base executable resolves to a
+location outside the installation pointed to by the ``home`` key in
+``pyvenv.cfg``. The standard library is now found from ``home``, and
+extension modules from the resolved executable's installation, instead of
+falling back to the compiled-in prefix.
+
+..
+
+.. date: 2026-10-22-00-30-21
+.. gh-issue: 160162
+.. nonce: lShf32
+.. section: Core and Builtins
+
+Fix a crash on 32-bit platforms when left shifting an :class:`int` by a
+count close to ``sys.maxsize * sys.int_info.bits_per_digit``.
+:exc:`OverflowError` is now raised, as for other too large counts.
+
+..
+
+.. date: 2026-10-22-00-30-02
+.. gh-issue: 160179
+.. nonce: dQ2e7m
+.. section: Core and Builtins
+
+Fix :meth:`!bytearray.__init__` leaving uninitialized memory in the object
+when it fails on a :class:`list` or :class:`tuple` containing an integer not
+in ``range(256)``. The object is now empty after the failed call.
+
+..
+
+.. date: 2026-10-21-23-18-38
+.. gh-issue: 160132
+.. nonce: Nj4rQa
+.. section: Core and Builtins
+
+Reduce memory usage during compilation by reordering the fields of the
+internal basic block structure to reduce padding. Patch by Shamil Abdulaev.
+
+..
+
+.. date: 2026-10-21-21-26-10
+.. gh-issue: 159739
+.. nonce: Zw43uX
+.. section: Core and Builtins
+
+Raise :exc:`MemoryError` instead of returning an incorrect result if
+:func:`round` runs out of memory while rounding a float.
+
+..
+
+.. date: 2026-10-21-21-26-10
+.. gh-issue: 159739
+.. nonce: CbTE4N
+.. section: Core and Builtins
+
+Fix a possible crash when assigning metadata to :class:`classmethod` or
+:class:`staticmethod` objects.
+
+..
+
+.. date: 2026-10-21-21-26-10
+.. gh-issue: 159739
+.. nonce: Aw61LR
+.. section: Core and Builtins
+
+Fix a race in ``list.__sizeof__()`` when a list is concurrently resized on a
+free-threaded build.
+
+..
+
+.. date: 2026-10-21-19-55-00
+.. gh-issue: 159739
+.. nonce: tali01
+.. section: Core and Builtins
+
+Fix a reference leak when the value of a type alias is evaluated recursively
+or concurrently.
+
+..
+
+.. date: 2026-10-21-19-55-00
+.. gh-issue: 159739
+.. nonce: codc01
+.. section: Core and Builtins
+
+Fix a crash in free-threaded builds when :func:`codecs.unregister` is called
+concurrently.
+
+..
+
+.. date: 2026-10-21-18-00-00
+.. gh-issue: 160368
+.. nonce: sem-clockwait
+.. section: Core and Builtins
+
+On Linux, allow timed semaphore waits to use the monotonic clock when
+``sem_clockwait`` is available at runtime, even if Python was built with
+older libc headers.
+
+..
+
+.. date: 2026-10-21-14-00-00
+.. gh-issue: 159493
+.. nonce: sfLf1b
+.. section: Core and Builtins
+
+Superinstructions are now formed after the compiler decides which
+:opcode:`LOAD_FAST` instructions can borrow their reference. This fixes
+reference count contention slowdown on the free-threaded build for
+single-line loops and comprehensions.
+
+..
+
+.. date: 2026-10-20-22-00-00
+.. gh-issue: 159963
+.. nonce: pLkHld
+.. section: Core and Builtins
+
+Fix a regression in Python 3.15.0 where threads importing submodules of
+packages for the first time could raise ``_DeadlockError`` or a spurious
+"partially initialized module" :exc:`ImportError`, or block one another,
+with no circular import involved. :func:`importlib.import_module` now
+returns the partially initialized module in a cross-thread circular import,
+as the :keyword:`import` statement does, instead of raising
+``_DeadlockError``.
+
+..
+
+.. date: 2026-10-20-20-38-38
+.. gh-issue: 159101
+.. nonce: vFwrZY
+.. section: Core and Builtins
+
+Fix use-after-free when :meth:`~object.__del__` changes the base class.
+Patch by Sergey Miryanov.
+
+..
+
+.. date: 2026-10-20-10-00-00
+.. gh-issue: 158195
+.. nonce: UnpinTL
+.. section: Core and Builtins
+
+Fix a deadlock in the free-threaded build between a thread that stops the
+world while running Python code under the type lock (for example a custom
+metaclass ``mro()`` or the ``__eq__`` of a :class:`str` subclass used as a
+class ``__dict__`` key) and a thread that assigns to a special method or to
+``__bases__`` of a class. The type lock is no longer held while waiting for
+a stop-the-world; the prepared slot, MRO and bases updates are validated
+with the world stopped and recomputed if they went stale.
+
+..
+
+.. date: 2026-10-20-00-00-00
+.. gh-issue: 159739
+.. nonce: da0f04
+.. section: Core and Builtins
+
+Fix reference leaks when free-threaded garbage collection aborts early
+because of an allocation error.
+
+..
+
+.. date: 2026-10-20-00-00-00
+.. gh-issue: 159739
+.. nonce: d76e6d
+.. section: Core and Builtins
+
+Prevent free-threaded builds from interning and immortalizing complex
+subclasses in code object constants.
+
+..
+
+.. date: 2026-10-20-00-00-00
+.. gh-issue: 159739
+.. nonce: bf569b
+.. section: Core and Builtins
+
+Fix a reference leak in binary, ternary, and comparison operations on weak
+reference proxies when another operand is a dead proxy.
+
+..
+
+.. date: 2026-10-20-00-00-00
+.. gh-issue: 159739
+.. nonce: a3cc5d
+.. section: Core and Builtins
+
+Fix a crash when constructing an error for invalid generic alias arguments.
+
+..
+
+.. date: 2026-10-20-00-00-00
+.. gh-issue: 159739
+.. nonce: 848b18
+.. section: Core and Builtins
+
+Allow the garbage collector to break reference cycles involving property
+accessors or names.
+
+..
+
+.. date: 2026-10-19-21-30-00
+.. gh-issue: 159860
+.. nonce: qsbr128
+.. section: Core and Builtins
+
+Fix false sharing between the per-thread QSBR states in the
+:term:`free-threaded build` on AArch64 CPUs with 128-byte cache lines, such
+as Apple Silicon. CPU-bound threads that share no objects now scale like
+processes there.
+
+..
+
+.. date: 2026-10-19-20-38-17
+.. gh-issue: 159739
+.. nonce: fc0ed2
+.. section: Core and Builtins
+
+Avoid a crash if allocation fails while creating a
+:class:`string.templatelib.Template` iterator.
+
+..
+
+.. date: 2026-10-19-20-38-17
+.. gh-issue: 159739
+.. nonce: b62fc9
+.. section: Core and Builtins
+
+Propagate errors during generic class construction and avoid a crash after
+failed generic alias substitution.
+
+..
+
+.. date: 2026-10-19-20-38-17
+.. gh-issue: 159739
+.. nonce: 78e530
+.. section: Core and Builtins
+
+Raise :exc:`OverflowError` when the absolute value of a dynamic printf-style
+formatting width is too large.
+
+..
+
+.. date: 2026-10-19-20-38-17
+.. gh-issue: 159739
+.. nonce: 55fd08
+.. section: Core and Builtins
+
+Fix a reference leak in :func:`gc.get_objects` and :func:`gc.get_referrers`
+when an internal allocation fails in the free-threaded build.
+
+..
+
+.. date: 2026-10-19-19-33-35
+.. gh-issue: 159739
+.. nonce: f81734
+.. section: Core and Builtins
+
+Fix a crash in :func:`warnings.warn` when ``skip_file_prefixes`` is an empty
+tuple subclass. Propagate allocation errors when creating the fallback
+filename.
+
+..
+
+.. date: 2026-10-19-19-33-35
+.. gh-issue: 159739
+.. nonce: c25c27
+.. section: Core and Builtins
+
+Fix memory leaks during interpreter startup when a path configuration file
+is empty or too large, or when an audit hook rejects a command.
+
+..
+
+.. date: 2026-10-19-19-33-35
+.. gh-issue: 159739
+.. nonce: a8775b
+.. section: Core and Builtins
+
+Avoid a crash when an interpreter configuration string cannot be encoded as
+UTF-8.
+
+..
+
+.. date: 2026-10-19-19-33-35
+.. gh-issue: 159739
+.. nonce: 1fc3af
+.. section: Core and Builtins
+
+Preserve the original :exc:`SyntaxError` if allocating optional error
+metadata fails.
+
+..
+
+.. date: 2026-10-19-19-33-35
+.. gh-issue: 159739
+.. nonce: 173d49
+.. section: Core and Builtins
+
+Avoid a crash if formatting an integer with the ``c`` presentation type runs
+out of memory.
+
+..
+
+.. date: 2026-10-19-19-33-35
+.. gh-issue: 159739
+.. nonce: 09590b
+.. section: Core and Builtins
+
+Avoid a crash when a module filename cannot be encoded as UTF-8.
+
+..
+
+.. date: 2026-10-19-16-38-39
+.. gh-issue: 159813
+.. nonce: wHfSOc
+.. section: Core and Builtins
+
+Add a fast path for :const:`None` in :c:func:`PyUnicodeWriter_WriteRepr`.
+Patch by Donghee Na.
+
+..
+
+.. date: 2026-10-18-00-30-00
+.. gh-issue: 159652
+.. nonce: Qk3vLm
+.. section: Core and Builtins
+
+Fix a hang when an import fails with :exc:`RecursionError` because the C
+stack is nearly exhausted: releasing the import locks could itself fail and
+leave the global import lock or a module lock held forever, so that later
+imports in other threads blocked indefinitely. The import system now raises
+:exc:`RecursionError` before taking an import lock when there is not enough
+stack left to release it.
+
+..
+
+.. date: 2026-10-17-02-47-26
+.. gh-issue: 159603
+.. nonce: OFagJz
+.. section: Core and Builtins
+
+On FreeBSD, call ``pthread_attr_get_np()`` to get the stack size (and guard
+size) of the current thread. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-10-16-18-25-48
+.. gh-issue: 159564
+.. nonce: WMRRFA
+.. section: Core and Builtins
+
+Improve the performance and thread scaling of dereferencing weak references
+in the :term:`free-threaded build`. Dereferencing a weak reference no
+longer takes a lock.
+
+..
+
+.. date: 2026-10-15-12-40-00
+.. gh-issue: 87613
+.. nonce: Sl1ceV
+.. section: Core and Builtins
+
+Speed up calling :class:`slice` by adding a vectorcall implementation of the
+constructor generated by Argument Clinic. Patch by Pieter Eendebak.
+
+..
+
+.. date: 2026-10-15-12-36-09
+.. gh-issue: 130279
+.. nonce: N9N-sw
+.. section: Core and Builtins
+
+Fix bug where compiler did not set the right exception handler for some jump
+instructions.
+
+..
+
+.. date: 2026-10-15-12-10-00
+.. gh-issue: 87613
+.. nonce: Wr4fvc
+.. section: Core and Builtins
+
+Speed up creating :class:`weakref.ref` objects by adding a vectorcall
+implementation of the constructor generated by Argument Clinic. Patch by
+Pieter Eendebak.
+
+..
+
+.. date: 2026-10-15-10-15-27
+.. gh-issue: 159449
+.. nonce: xsdzFf
+.. section: Core and Builtins
+
+Fix a free-threaded asyncio race leading to segfaults.
+
+..
+
+.. date: 2026-10-14-23-05-00
+.. gh-issue: 132042
+.. nonce: k7Qs2w
+.. section: Core and Builtins
+
+Speed up class creation by resolving the special method slots of a new class
+with one pass over each class dict along the MRO instead of one lookup per
+slot name and per class.
+
+..
+
+.. date: 2026-10-14-19-16-53
+.. gh-issue: 159434
+.. nonce: T4AsrQ
+.. section: Core and Builtins
+
+Fix reading a function's :attr:`~function.__annotations__` using borrowed
+references to :attr:`~function.__annotate__` and the internal annotations
+tuple while running code that can replace them. If ``__annotations__`` is
+set while ``__annotate__`` runs, the newly set value is now kept.
+
+..
+
+.. date: 2026-10-14-18-45-35
+.. gh-issue: 159431
+.. nonce: mVTMsA
+.. section: Core and Builtins
+
+Fix an assertion failure, or an immortal object becoming mortal, on the
+:term:`free threaded ` build when an object passed to the
+internal delayed decref mechanism is immortal or becomes immortal before the
+delayed decref is processed by the garbage collector.
+
+..
+
+.. date: 2026-10-14-11-40-06
+.. gh-issue: 159430
+.. nonce: OWpyPm
+.. section: Core and Builtins
+
+Report the correct exception if looking up :meth:`~object.__bytes__` raises
+an exception while performing %-formatting of :class:`bytes`.
+
+..
+
+.. date: 2026-10-14-07-36-44
+.. gh-issue: 159399
+.. nonce: cjuE0N
+.. section: Core and Builtins
+
+Fix a crash in :func:`codecs.encode` and :func:`codecs.decode` in the
+:term:`free-threaded build` when another thread concurrently unregisters a
+codec search function. Patch by Christian Aurich Zanettini Martins.
+
+..
+
+.. date: 2026-10-13-16-38-00
+.. gh-issue: 159320
+.. nonce: _Yhg1s
+.. section: Core and Builtins
+
+Add dynamic detection of stack sizes on Android, allowing safer deep
+recursion.
+
+..
+
+.. date: 2026-10-13-06-23-56
+.. gh-issue: 159294
+.. nonce: 9LTsNA
+.. section: Core and Builtins
+
+Fix a crash in a debug build when creating an :exc:`ExceptionGroup` or
+:exc:`BaseExceptionGroup` fails with :exc:`MemoryError`. Patch by Christian
+Aurich Zanettini Martins.
+
+..
+
+.. date: 2026-10-13-04-03-48
+.. gh-issue: 159288
+.. nonce: vhqBQG
+.. section: Core and Builtins
+
+Fix a crash when walking a very long chain of lazy import placeholders, as
+created by an aliased dotted import such as ``lazy import a.b.c as d``.
+:exc:`RecursionError` is now raised instead.
+
+..
+
+.. date: 2026-10-12-20-00-00
+.. gh-issue: 159136
+.. nonce: fnAttr
+.. section: Core and Builtins
+
+Setting ``__name__``, ``__qualname__``, ``__doc__`` or ``__module__`` on a
+function no longer stops all threads in the free-threaded build. The setters
+now use the per-object lock and defer freeing the old value with QSBR, the
+same approach used for generator ``__name__``. This fixes a large slowdown
+in multi-threaded code using :func:`functools.wraps` since 3.14.7. Readers
+of these attributes now use atomic loads, and argument error reporting reads
+``__qualname__`` after keyword comparisons, which may execute Python code
+and replace it. Previously this could use a freed object.
+
+..
+
+.. date: 2026-10-12-16-00-34
+.. gh-issue: 159244
+.. nonce: ThiobE
+.. section: Core and Builtins
+
+Fix a crash in :class:`dict` and :meth:`dict.update` in the
+:term:`free-threaded build` when another thread concurrently mutates a list
+used as a key/value pair. Patch by Christian Aurich Zanettini Martins.
+
+..
+
+.. date: 2026-10-12-11-59-37
+.. gh-issue: 68241
+.. nonce: jVpLIJ
+.. section: Core and Builtins
+
+Add EXIT_FAILURE and EXIT_SUCCESS in the sys module.
+
+..
+
+.. date: 2026-10-11-06-36-25
+.. gh-issue: 159188
+.. nonce: Fq7wLm
+.. section: Core and Builtins
+
+In the :term:`free-threaded build`, :func:`compile` no longer immortalizes
+the constants of the code objects when it is given an AST object, as was
+already the case for a source string. The output of :mod:`marshal` for such
+code no longer depends on the code objects which were created before in the
+process.
+
+..
+
+.. date: 2026-10-10-20-21-13
+.. gh-issue: 159111
+.. nonce: XVf2k-
+.. section: Core and Builtins
+
+Update mimalloc version from 2.1.2 to 2.5.2. Patch by Donghee Na.
+
+..
+
+.. date: 2026-10-09-16-04-40
+.. gh-issue: 159041
+.. nonce: PUP8bU
+.. section: Core and Builtins
+
+Fix a use-after-free in :mod:`asyncio` task bookkeeping when a finalizer
+creates a task during thread shutdown.
+
+..
+
+.. date: 2026-10-07-00-00-00
+.. gh-issue: 158973
+.. nonce: warnings-fork
+.. section: Core and Builtins
+
+Reset the warnings lock in the child after :func:`os.fork`, before clearing
+other threads' states, to avoid deadlocks when their finalizers issue
+warnings. Preserve the lock's recursion depth if the forking thread owns it.
+
+..
+
+.. date: 2026-10-05-13-19-49
+.. gh-issue: 87613
+.. nonce: JLTGBy
+.. section: Core and Builtins
+
+Speed up :class:`bytes` and :class:`bytearray` construction by adding
+:ref:`vectorcall` support.
+
+..
+
+.. date: 2026-10-04-20-04-55
+.. gh-issue: 158816
+.. nonce: 9ulhWb
+.. section: Core and Builtins
+
+Speed up deleting items from split dictionaries (for example the
+materialized ``__dict__`` of an instance with inline values) by skipping a
+redundant hash table probe.
+
+..
+
+.. date: 2026-10-03-13-00-00
+.. gh-issue: 158197
+.. nonce: Qk7sVd
+.. section: Core and Builtins
+
+Fix crashes and debug-build assertion failures in the :term:`free-threaded
+build` when iterating over a split dictionary while another thread deletes
+entries or clears it. Publish insertion-order updates atomically so readers
+cannot observe an increased size before the corresponding order entry is
+initialized.
+
+..
+
+.. date: 2026-10-01-00-00-00
+.. gh-issue: 158525
+.. nonce: Xw3K9a
+.. section: Core and Builtins
+
+Fix slow ``dict.copy()`` for dicts with many deleted entries in the
+free-threaded build.
+
+..
+
+.. date: 2026-09-30-21-29-54
+.. gh-issue: 158529
+.. nonce: kZO7mX
+.. section: Core and Builtins
+
+Fixed crash on Android x86_64, API levels 27-28, caused by mimalloc calling
+system calls directly.
+
+..
+
+.. date: 2026-09-29-14-35-00
+.. gh-issue: 158121
+.. nonce: Kj4nQ8
+.. section: Core and Builtins
+
+Fix missing :mod:`sys.monitoring` ``INSTRUCTION`` events when a ``LINE``
+callback returns :data:`sys.monitoring.DISABLE`.
+
+..
+
+.. date: 2026-09-28-10-12-25
+.. gh-issue: 158304
+.. nonce: 3pdcnJ
+.. section: Core and Builtins
+
+Speed up iteration over asynchronous generators: values yielded to ``async
+for`` no longer create and discard a :exc:`StopIteration` exception at every
+nesting level. The ``async_generators`` pyperformance benchmark is about 30%
+faster. Patch by Shamil Abdulaev.
+
+..
+
+.. date: 2026-09-25-11-05-00
+.. gh-issue: 157746
+.. nonce: q7Lk3d
+.. section: Core and Builtins
+
+Reduce the overhead of :c:func:`PyErr_CheckSignals` when no signal is
+pending: the cheap flag checks are now done before the main-thread check and
+the remote debugger configuration lookup.
+
+..
+
+.. date: 2026-09-21-12-44-38
+.. gh-issue: 132414
+.. nonce: uwxmd5
+.. section: Core and Builtins
+
+Quote the invalid option in the error message for an unknown command-line
+option: ``Invalid option '-z'`` instead of ``Unknown option: -z``. A stray
+space, as passed by a shebang line like ``#!/usr/bin/python3 -q -i``, is now
+reported as ``Invalid option '- '``.
+
+..
+
+.. date: 2026-09-13-10-00-00
+.. gh-issue: 157361
+.. nonce: aiterpy
+.. section: Core and Builtins
+
+Implement :func:`aiter` in Python instead of C, in the frozen
+``_pybuiltins`` module. The async iterator returned by ``aiter(callable,
+...)`` now has a plain coroutine ``__anext__()``, so introspection tools
+such as :func:`asyncio.print_call_graph` can see through it into the awaited
+callable result.
+
+..
+
+.. date: 2026-09-08-17-40-00
+.. gh-issue: 157194
+.. nonce: 17Ffhk
+.. section: Core and Builtins
+
+Fix a data race in the free-threaded build, reported by ThreadSanitizer,
+between the specializer reading an instruction opcode and another thread
+writing it. Only reachable when thread-local bytecode is disabled with ``-X
+tlbc=0``, which makes threads share one copy of the bytecode.
+
+..
+
+.. date: 2026-09-07-09-52-21
+.. gh-issue: 156443
+.. nonce: tT40sm
+.. section: Core and Builtins
+
+Speed up :func:`float` conversion and true division of large :class:`int`
+values.
+
+..
+
+.. date: 2026-08-30-16-30-00
+.. gh-issue: 135385
+.. nonce: Wn7Rd4
+.. section: Core and Builtins
+
+Reduce the memory consumption of instances of classes which define
+``__slots__`` and also have a ``__dict__``. Space for the attributes stored
+in slots is no longer reserved in the inline values of every instance.
+
+..
+
+.. date: 2026-08-27-17-26-21
+.. gh-issue: 106045
+.. nonce: wzTH7f
+.. section: Core and Builtins
+
+Fix standard library discovery in virtual environments created from a Python
+executable symlink located outside its base installation.
+
+..
+
+.. date: 2026-08-27-00-00-00
+.. gh-issue: 156399
+.. nonce: aB3xYz
+.. section: Core and Builtins
+
+Fix a regression where attribute access on a :class:`types.ModuleType`
+subclass could bypass a data descriptor defined on the subclass. The
+``LOAD_ATTR_MODULE`` specialization guarded on ``tp_getattro``, which
+subclasses inherit, and then read the module dictionary directly.
+
+..
+
+.. date: 2026-08-21-14-37-50
+.. gh-issue: 127716
+.. nonce: KrPth8
+.. section: Core and Builtins
+
+On the free-threaded build, :class:`memoryview` lifetime and bookkeeping
+operations are now thread safe: an operation that reads the buffer holds the
+managed buffer for its duration, so a concurrent :meth:`~memoryview.release`
+can no longer free the buffer under it; slicing a memoryview from several
+threads no longer loses buffer registrations and raises ``ValueError:
+operation forbidden on released memoryview object``; and :func:`hash` of a
+memoryview is no longer a data race. As a result :meth:`~memoryview.release`
+may now return while an operation started by another thread is still
+running, see :ref:`thread-safety-memoryview`.
+
+..
+
+.. date: 2026-07-21-10-42-15
+.. gh-issue: 154318
+.. nonce: Kq3Wm7
+.. section: Core and Builtins
+
+Fix a crash when hashing a deeply nested :class:`tuple` or
+:class:`frozendict`. A :exc:`RecursionError` is now raised instead of
+overflowing the C stack.
+
+..
+
+.. date: 2026-07-11-15-00-13
+.. gh-issue: 153568
+.. nonce: atomfp
+.. section: Core and Builtins
+
+Speed up parsing of simple expressions by recognizing single-token atoms
+without descending the full precedence rule chain.
+
+..
+
+.. date: 2026-07-04-18-00-00
+.. gh-issue: 153014
+.. nonce: gCdBg1
+.. section: Core and Builtins
+
+Fix a data race on the garbage collector debug flag in free-threading
+builds: :func:`gc.set_debug` and :func:`gc.get_debug` now access it
+atomically.
+
+..
+
+.. date: 2026-06-29-23-01-07
+.. gh-issue: 152631
+.. nonce: LKgCM_
+.. section: Core and Builtins
+
+Fix :func:`ast.parse` ability to parse lazy imports with *feature_version*
+older than 3.15, now it properly raises :exc:`SyntaxError`.
+
+..
+
+.. date: 2026-06-26-00-02-29
+.. gh-issue: 149816
+.. nonce: JKN-5B
+.. section: Core and Builtins
+
+Fix a race in free-threaded builds where storing an instance attribute could
+use a stale borrowed reference to an instance ``__dict__`` after another
+thread replaced it.
+
+..
+
+.. date: 2026-06-20-18-00-00
+.. gh-issue: 151818
+.. nonce: LsApDf
+.. section: Core and Builtins
+
+Fix a double-free crash in ``list.append()`` (the specialized
+``CALL_LIST_APPEND`` instruction) when growing the list fails with
+:exc:`MemoryError`.
+
+..
+
+.. date: 2026-06-07-22-03-20
+.. gh-issue: 151060
+.. nonce: tdexEE
+.. section: Core and Builtins
+
+Fix a crash or memory corruption in :func:`sum` when summing a
+:class:`float` subclass instance into a complex running total.
+
+..
+
+.. date: 2026-05-21-14-21-06
+.. gh-issue: 150075
+.. nonce: dLI21Z
+.. section: Core and Builtins
+
+tar.addfile() now sets member offsets in TarInfo objects
+
+..
+
+.. date: 2026-04-23-08-36-47
+.. gh-issue: 148891
+.. nonce: AMMHow
+.. section: Core and Builtins
+
+Fix a crash in :func:`contextvars.Context.run` where a GC invocation could
+free the current HAMT during traverse.
+
+..
+
+.. date: 2026-04-15-21-55-45
+.. gh-issue: 69605
+.. nonce: NwoP6l
+.. section: Core and Builtins
+
+Fix :term:`REPL` completions inserted incorrectly when there was spaces in
+import statements.
+
+..
+
+.. date: 2026-04-12-13-48-26
+.. gh-issue: 69605
+.. nonce: T9HWOL
+.. section: Core and Builtins
+
+Insert ``import`` after ``from x.y.z `` in the :term:`REPL`
+auto-completion.
+
+..
+
+.. date: 2026-03-14-11-20-52
+.. gh-issue: 145019
+.. nonce: ls2EXo
+.. section: Core and Builtins
+
+Improve :exc:`SyntaxError` when :keyword:`match` alternative patterns bind
+different names. Patch by Bénédikt Tran.
+
+..
+
+.. date: 2025-08-19-16-10-26
+.. gh-issue: 137966
+.. nonce: nEgFAt
+.. section: Core and Builtins
+
+Add support for additional special names to the built-in :func:`help`
+function. Patch by Adam Hartz.
+
+..
+
+.. date: 2024-10-27-22-23-57
+.. gh-issue: 125873
+.. nonce: BG97KU
+.. section: Core and Builtins
+
+Improved error message when an environment variable is misconfigured.
+
+..
+
+.. date: 2024-08-11-12-06-23
+.. gh-issue: 122901
+.. nonce: B2Huom
+.. section: Core and Builtins
+
+Speed up creating :class:`str` objects from non-ASCII character data.
+
+..
+
+.. date: 2024-03-07-22-38-07
+.. gh-issue: 116477
+.. nonce: AqwRAV
+.. section: Core and Builtins
+
+Speed up the :class:`range` object constructor in the case of a single
+argument.
+
+..
+
+.. date: 2026-11-06-11-59-26
+.. gh-issue: 161475
+.. nonce: 82LWf4
+.. section: Library
+
+Fix :mod:`ctypes` structures containing arrays of floating-point type
+returned by value on 64-bit Linux SPARC.
+
+..
+
+.. date: 2026-11-06-05-42-11
+.. gh-issue: 71199
+.. nonce: qJN4cV
+.. section: Library
+
+Change :mod:`os` module types such as :class:`~os.DirEntry` to report ``os``
+as their module on every platform. :ref:`Pickled ` objects
+using the platform-specific qualified name, such as ``nt.times_result``,
+still load.
+
+..
+
+.. date: 2026-11-06-00-00-00
+.. gh-issue: 142782
+.. nonce: qU7nE4
+.. section: Library
+
+Fix a use-after-free in :class:`zoneinfo.ZoneInfo` when a key's ``__eq__``
+clears the cache during a lookup. Strong cache keys are now compared by
+string contents.
+
+..
+
+.. date: 2026-11-05-12-00-24
+.. gh-issue: 161415
+.. nonce: NJhrAR
+.. section: Library
+
+Remove ``FILES`` and ``unicode`` from the related help topics listed by
+:func:`help` for the ``TYPES`` and ``UNICODE`` topics. Neither exists in
+Python 3, so asking for help on them failed.
+
+..
+
+.. date: 2026-11-05-11-59-58
+.. gh-issue: 161414
+.. nonce: Xnxe8A
+.. section: Library
+
+Remove the backquote from the symbols listed by :func:`help`, asking for
+help on it reported that no documentation was found.
+
+..
+
+.. date: 2026-11-05-11-56-50
+.. gh-issue: 161389
+.. nonce: EIl2E6
+.. section: Library
+
+Fixes a crash in :class:`decimal.Context` when passing invalid signaling
+dicts as *flags* and *traps*.
+
+..
+
+.. date: 2026-11-05-10-05-00
+.. gh-issue: 161387
+.. nonce: def456
+.. section: Library
+
+Fix a crash in :mod:`decimal` when the internal ``decimal_context``
+:class:`contextvars.ContextVar` holds a value that is not a context.
+
+..
+
+.. date: 2026-11-03-21-26-09
+.. gh-issue: 161295
+.. nonce: IJqoJM
+.. section: Library
+
+:class:`reprlib.Repr` objects now have a meaningful :meth:`~object.__repr__`
+describing the instance attributes.
+
+..
+
+.. date: 2026-11-03-18-56-28
+.. gh-issue: 161259
+.. nonce: iyZz6y
+.. section: Library
+
+Improved the accuracy of :func:`statistics.correlation` for very small
+inputs, where the product of the sums of squares is subnormal rather than
+zero.
+
+..
+
+.. date: 2026-11-03-12-00-00
+.. gh-issue: 93821
+.. nonce: aCcRsT
+.. section: Library
+
+Fix :class:`asyncio.ProactorEventLoop` servers that stopped accepting new
+connections on Windows when a client reset its connection before it was
+accepted (``WinError 64``, ``ERROR_NETNAME_DELETED``). The listening socket
+is now kept open and the server continues to accept connections.
+
+..
+
+.. date: 2026-11-03-12-00-00
+.. gh-issue: 161076
+.. nonce: nOdLy1
+.. section: Library
+
+Fix :mod:`asyncio` leaving a half-created transport registered with the
+event loop and the server when setting ``TCP_NODELAY`` on a socket fails.
+Such a failure could make :meth:`asyncio.Server.wait_closed` hang and
+prevent new connections from being served. Errors from
+``setsockopt(TCP_NODELAY)`` are now ignored.
+
+..
+
+.. date: 2026-11-03-10-33-33
+.. gh-issue: 161233
+.. nonce: _9VrfL
+.. section: Library
+
+Fix unraisable :exc:`TypeError` when ``None`` was passed as a *timer* to
+:class:`cProfile.Profile `.
+
+..
+
+.. date: 2026-11-02-21-10-00
+.. gh-issue: 161212
+.. nonce: pip263
+.. section: Library
+
+Bump the version of :pypi:`pip` bundled in :mod:`ensurepip` to version 26.3.
+
+..
+
+.. date: 2026-11-02-16-28-11
+.. gh-issue: 161178
+.. nonce: D3-23R
+.. section: Library
+
+Fix :meth:`asyncio.Task.print_stack` to include frames from async generator
+operations. Patch by Timofei Ivankov
+
+..
+
+.. date: 2026-11-02-13-26-36
+.. gh-issue: 161179
+.. nonce: H8Yyaw
+.. section: Library
+
+Fix the function names in the error messages of :func:`os.spawnve`,
+:func:`os.preadv` and :meth:`tkinter.Wm.wm_attributes`.
+
+..
+
+.. date: 2026-11-02-13-11-30
+.. gh-issue: 161166
+.. nonce: zfFDlW
+.. section: Library
+
+Fix :meth:`asyncio.Task.print_stack` displaying an incorrect exception line
+after a ``finally`` block. Patch by Timofei Ivankov.
+
+..
+
+.. date: 2026-11-01-22-07-24
+.. gh-issue: 161124
+.. nonce: c2YmcV
+.. section: Library
+
+Fix :func:`asyncio.print_call_graph` reporting event loop frames when
+*depth* exceeds the task stack. Patch by Timofei Ivankov.
+
+..
+
+.. date: 2026-11-01-19-38-33
+.. gh-issue: 161083
+.. nonce: PM21lv
+.. section: Library
+
+Fix stale task nodes left by :func:`asyncio.gather` when argument validation
+fails. Patch by Timofei Ivankov
+
+..
+
+.. date: 2026-10-31-21-34-00
+.. gh-issue: 161039
+.. nonce: k7_pTD
+.. section: Library
+
+Fix the :mod:`pydoc` pager not detecting ``less`` 706 and newer.
+
+..
+
+.. date: 2026-10-30-12-00-00
+.. gh-issue: 137549
+.. nonce: Tm0Bxg
+.. section: Library
+
+:func:`asyncio.timeout` now inserts :exc:`TimeoutError` into the context
+chain of sub-exceptions of a :exc:`BaseExceptionGroup`, as it already did
+for :exc:`ExceptionGroup`.
+
+..
+
+.. date: 2026-10-30-10-36-30
+.. gh-issue: 160782
+.. nonce: n6JCUU
+.. section: Library
+
+:mod:`venv`: a symbolic link or junction in place of a directory inside the
+environment now raises :exc:`ValueError` instead of being followed.
+
+..
+
+.. date: 2026-10-29-23-25-31
+.. gh-issue: 160782
+.. nonce: 1ZwCOr
+.. section: Library
+
+:mod:`venv`: a backslash before a quote in the prompt or the path no longer
+breaks ``activate.fish``.
+
+..
+
+.. date: 2026-10-29-21-43-53
+.. gh-issue: 160429
+.. nonce: eWapMs
+.. section: Library
+
+Fix :class:`asyncio.ProactorEventLoop` socket transports leaving the socket
+open, and :meth:`asyncio.Server.wait_closed` hanging, when the peer resets
+the connection while the transport is being closed.
+
+..
+
+.. date: 2026-10-29-21-36-08
+.. gh-issue: 160929
+.. nonce: mK8n2Q
+.. section: Library
+
+Fix reverse union with :class:`~collections.ChainMap` to preserve its lookup
+semantics for defaulting mappings such as :class:`~collections.Counter` and
+:class:`~collections.defaultdict`.
+
+..
+
+.. date: 2026-10-29-20-52-57
+.. gh-issue: 50720
+.. nonce: Kd1VMR
+.. section: Library
+
+:exc:`urllib.error.URLError` now sets the :attr:`~OSError.errno` and
+:attr:`~OSError.strerror` attributes from
+:attr:`~urllib.error.URLError.reason` when it is an :exc:`OSError`. On
+Windows, :attr:`~OSError.winerror` is set as well.
+
+..
+
+.. date: 2026-10-29-19-42-53
+.. gh-issue: 53089
+.. nonce: ewaIBvY6
+.. section: Library
+
+:class:`urllib.request.HTTPDigestAuthHandler` now sends ``uri="/"`` in the
+Digest ``Authorization`` header for URLs with an empty path, such as
+``http://example.com``, matching the request-target sent by
+:mod:`http.client`. Previously it sent ``uri=""``, which servers could
+reject. Patch by Senthil Kumaran.
+
+..
+
+.. date: 2026-10-28-20-36-44
+.. gh-issue: 109564
+.. nonce: WqoyNE
+.. section: Library
+
+Fix a race in :mod:`asyncio` where closing a server after it accepted a
+connection, but before the connection's transport was created, reported an
+:exc:`AssertionError` to the exception handler. Such connections are now
+closed quietly.
+
+..
+
+.. date: 2026-10-28-16-40-00
+.. gh-issue: 66333
+.. nonce: pdb-sigint
+.. section: Library
+
+Allow Ctrl-C to interrupt execution resumed with the :mod:`pdb` ``next``,
+``until``, and ``return`` commands without unwinding the debugged program,
+as with ``continue``.
+
+..
+
+.. date: 2026-10-28-13-23-28
+.. gh-issue: 59515
+.. nonce: wt31yNN4
+.. section: Library
+
+:class:`urllib.request.HTTPDigestAuthHandler` and
+:class:`urllib.request.ProxyDigestAuthHandler` now parse all
+``WWW-Authenticate`` (or ``Proxy-Authenticate``) headers and accept multiple
+challenges per header: the first Digest challenge is used.
+
+..
+
+.. date: 2026-10-28-12-00-00
+.. gh-issue: 53852
+.. nonce: Pr0xy4
+.. section: Library
+
+:class:`urllib.request.ProxyDigestAuthHandler` now raises
+:exc:`~urllib.error.HTTPError` with status code 407 (Proxy Authentication
+Required) instead of 401 when proxy authentication fails.
+
+..
+
+.. date: 2026-10-28-08-12-33
+.. gh-issue: 160811
+.. nonce: wQ3xT7
+.. section: Library
+
+Fix :meth:`io.TextIOWrapper.tell` reading past the end of the buffer after
+:meth:`~io.TextIOWrapper.seek`.
+
+..
+
+.. date: 2026-10-28-07-34-05
+.. gh-issue: 160806
+.. nonce: ZZRkhi
+.. section: Library
+
+Fix the pure-Python implementation of :class:`datetime.timedelta` losing
+sub-second precision with large float arguments. It now gives the same
+results as the C implementation.
+
+..
+
+.. date: 2026-10-28-07-26-47
+.. gh-issue: 160804
+.. nonce: R5HeTQ
+.. section: Library
+
+:mod:`asyncio` call graph introspection now includes frames of generator
+based awaitables, such as generators returned by ``__await__`` and
+:func:`types.coroutine` generators.
+
+..
+
+.. date: 2026-10-27-15-42-16
+.. gh-issue: 160781
+.. nonce: VGLB9S
+.. section: Library
+
+Fix :class:`io.BytesIO` implementation of :meth:`io.IOBase.truncate`
+rejecting sizes larger than ``2**31 - 1`` on Windows.
+
+..
+
+.. date: 2026-10-27-15-27-32
+.. gh-issue: 160781
+.. nonce: kARuHu
+.. section: Library
+
+Fix :class:`io.StringIO` implementation of :meth:`io.IOBase.truncate`
+rejecting sizes larger than ``2**31 - 1`` on Windows.
+
+..
+
+.. date: 2026-10-27-15-26-53
+.. gh-issue: 160781
+.. nonce: 4VSeQK
+.. section: Library
+
+Fix :class:`io.BytesIO` raising :exc:`SystemError` instead of
+:exc:`OverflowError` when writing at a position close to
+:data:`sys.maxsize`.
+
+..
+
+.. date: 2026-10-26-21-37-42
+.. gh-issue: 158500
+.. nonce: zxyuq5
+.. section: Library
+
+:meth:`datetime.date.fromisoformat` now rejects strings with trailing
+characters after a basic-format date, such as ``'2020010112'``. The
+pure-Python :meth:`datetime.datetime.fromisoformat` now rejects a date
+followed by a bare separator, such as ``'2020-01-01T'``, matching the C
+implementation.
+
+..
+
+.. date: 2026-10-26-16-17-45
+.. gh-issue: 160708
+.. nonce: w7z33g
+.. section: Library
+
+Fix out-of-bounds memory access in :func:`bool` on :mod:`ctypes` simple
+objects enlarged by :func:`ctypes.resize`, and when passing such objects to
+a foreign function.
+
+..
+
+.. date: 2026-10-26-16-15-29
+.. gh-issue: 160427
+.. nonce: 9G4EBb
+.. section: Library
+
+Fix :attr:`~io.TextIOBase.buffer` of a detached :class:`io.TextIOWrapper`
+raising :exc:`ValueError` instead of returning ``None``.
+
+..
+
+.. date: 2026-10-24-22-32-23
+.. gh-issue: 160596
+.. nonce: RKll-Z
+.. section: Library
+
+Fix the error message for invalid data passed to
+:meth:`!asyncio.proactor_events.sendto`.
+
+..
+
+.. date: 2026-10-24-07-58-00
+.. gh-issue: 160561
+.. nonce: b3Kq1z
+.. section: Library
+
+Fix a descriptor leak in :func:`socket.fromfd` when the socket constructor
+rejects its arguments. The duplicated descriptor was never closed.
+
+..
+
+.. date: 2026-10-24-01-53-42
+.. gh-issue: 160433
+.. nonce: DSTlog
+.. section: Library
+
+Fix incorrect backup names around daylight saving time changes in
+:class:`logging.handlers.TimedRotatingFileHandler`, including delayed
+rollovers.
+
+..
+
+.. date: 2026-10-23-23-21-21
+.. gh-issue: 160549
+.. nonce: q7ZdMt
+.. section: Library
+
+Fix a crash when a :class:`compression.zstd.ZstdCompressor` that uses worker
+threads and a :class:`~compression.zstd.ZstdDict` is deallocated, or the
+interpreter exits, while data passed to
+:meth:`~compression.zstd.ZstdCompressor.compress` is still being compressed.
+
+..
+
+.. date: 2026-10-23-22-34-55
+.. gh-issue: 160535
+.. nonce: Zk3dGc
+.. section: Library
+
+Fix a crash in :mod:`compression.zstd` when the garbage collector frees a
+:class:`~compression.zstd.ZstdCompressor` that uses worker threads together
+with its :class:`~compression.zstd.ZstdDict` before the compression of
+already submitted data has finished.
+
+..
+
+.. date: 2026-10-23-21-52-40
+.. gh-issue: 60299
+.. nonce: Af6IzL
+.. section: Library
+
+Fix :class:`urllib.request.ProxyDigestAuthHandler` failing to authenticate.
+It looked up credentials using the target request URL instead of the proxy's
+authority, so passwords registered via ``add_password()`` against the proxy
+never matched. Patch by Senthil Kumaran.
+
+..
+
+.. date: 2026-10-22-22-51-40
+.. gh-issue: 160386
+.. nonce: wYyboz
+.. section: Library
+
+Applied changes to ``importlib.metadata`` from `importlib_metadata 9.1
+`_:
+distribution discovery now prefers the greater of several metadata
+directories supplied by one path, so stale metadata left by an unclean
+upgrade no longer shadows the version in use; a missing required metadata
+field now raises a ``KeyError`` naming both the field and the distribution;
+``EntryPoint`` value validation is deferred until the value is used, so one
+malformed entry point no longer prevents others from being selected;
+``importlib.metadata.diagnose`` no longer crashes on a metadata directory
+with no metadata file or no declared name; and ``SimplePath.joinpath`` and
+``SimplePath.__truediv__`` take ``other`` positional-only.
+
+..
+
+.. date: 2026-10-22-18-30-00
+.. gh-issue: 160520
+.. nonce: sSdTmo
+.. section: Library
+
+Fix :mod:`asyncio` SSL transports not applying *ssl_shutdown_timeout* when
+the peer has sent EOF but does not read the data still queued for it.
+Closing such a connection could wait indefinitely; it is now aborted with
+:exc:`TimeoutError` once the timeout expires.
+
+..
+
+.. date: 2026-10-22-18-30-00
+.. gh-issue: 160326
+.. nonce: nAn7Tq
+.. section: Library
+
+Raise :exc:`ValueError` for a NaN *timeout* in
+:meth:`threading.Condition.wait` and the blocking calls built on it, such as
+:meth:`threading.Event.wait`, :meth:`threading.Semaphore.acquire` and
+:meth:`queue.Queue.get`, instead of returning at once or looping without
+ever timing out.
+
+..
+
+.. date: 2026-10-22-18-30-00
+.. gh-issue: 160314
+.. nonce: q7RkZd
+.. section: Library
+
+Raise an error in :class:`lzma.LZMAFile`, :func:`lzma.decompress`,
+:class:`bz2.BZ2File` and :func:`bz2.decompress` for a damaged ``.xz`` or
+bzip2 stream that follows another stream, instead of silently ignoring it
+and everything after it as trailing data.
+
+..
+
+.. date: 2026-10-22-16-30-00
+.. gh-issue: 159739
+.. nonce: tRq417
+.. section: Library
+
+Fix crashes in :mod:`sqlite3` when a row or text factory is replaced during
+a query, when cursor metadata is read during execution in a free-threaded
+build, or when allocating cursor metadata fails.
+
+..
+
+.. date: 2026-10-22-16-30-00
+.. gh-issue: 159739
+.. nonce: mFWntK
+.. section: Library
+
+Fix crashes in :mod:`profiling.tracing` when a custom timer reinitializes
+the profiler or its result clears or disables the profiler during conversion
+or cleanup.
+
+..
+
+.. date: 2026-10-22-16-23-01
+.. gh-issue: 159739
+.. nonce: XmlH3a
+.. section: Library
+
+Fix crashes in :mod:`xml.parsers.expat` when a character data callback
+disables buffering or clears another handler during a flush, or when
+interning an attribute name changes
+:attr:`~xml.parsers.expat.xmlparser.ordered_attributes`.
+
+..
+
+.. date: 2026-10-22-16-23-01
+.. gh-issue: 159739
+.. nonce: CjkR5a
+.. section: Library
+
+Fix the ``hz`` codec sometimes encoding ``~`` as a single ``~`` in text that
+mixes ASCII and Chinese characters, and the incremental ``iso2022_*`` codecs
+mishandling an escape sequence split across calls or keeping the previous
+character set after :meth:`!reset`. Also fix possible crashes in the CJK
+incremental and stream codecs when their ``errors`` attribute or their
+class's ``codec`` attribute is replaced while they are in use.
+
+..
+
+.. date: 2026-10-22-16-18-42
+.. gh-issue: 159739
+.. nonce: TioR3a
+.. section: Library
+
+Fix crashes in :class:`io.TextIOWrapper` and
+:class:`io.IncrementalNewlineDecoder` when a callback changes the active
+codec or decoded buffer. :class:`io.StringIO` now raises :exc:`ValueError`
+if converting the size passed to ``truncate()`` closes the stream.
+
+..
+
+.. date: 2026-10-22-08-34-22
+.. gh-issue: 160310
+.. nonce: q7Zm2K
+.. section: Library
+
+Fix quadratic time complexity of :func:`gzip.decompress`,
+:func:`bz2.decompress`, :func:`lzma.decompress` and
+:func:`compression.zstd.decompress` on data consisting of many concatenated
+members.
+
+..
+
+.. date: 2026-10-22-08-18-31
+.. gh-issue: 160522
+.. nonce: cJkSt8
+.. section: Library
+
+Fix the incremental encoders and stream writers of the stateful CJK codecs
+(``iso2022_*`` and ``hz``) keeping a changed shift state after an
+:meth:`!encode` or :meth:`!write` call failed. The next call could omit the
+escape sequence, writing multibyte characters in ASCII mode.
+
+..
+
+.. date: 2026-10-22-08-17-51
+.. gh-issue: 160316
+.. nonce: sRe9pQ
+.. section: Library
+
+Fix :meth:`re.Pattern.match`, :meth:`re.Pattern.prefixmatch`,
+:meth:`re.Pattern.fullmatch` and the ``match()`` and ``prefixmatch()``
+methods of scanner objects returning an empty match, or reading past the end
+of the string, when *pos* is greater than *endpos*. They now return
+``None``, as documented.
+
+..
+
+.. date: 2026-10-22-08-15-56
+.. gh-issue: 160324
+.. nonce: sIoRlz
+.. section: Library
+
+Fix a crash or garbage data when an :class:`io.StringIO` object is used
+again after one of its methods failed with :exc:`MemoryError`. The object
+now keeps its contents.
+
+..
+
+.. date: 2026-10-22-08-09-29
+.. gh-issue: 160406
+.. nonce: q7Rk2d
+.. section: Library
+
+Fix in-place filtering in :mod:`fileinput` deleting the file when it cannot
+be opened or the output file cannot be created: the backup file is now kept.
+The output file is now created exclusively, so :exc:`FileExistsError` is
+raised if a file or symbolic link appears under the name of the input file.
+
+..
+
+.. date: 2026-10-22-08-06-39
+.. gh-issue: 160513
+.. nonce: q7RkZd
+.. section: Library
+
+Fix :meth:`asyncio.loop.start_tls` and
+:meth:`asyncio.StreamWriter.start_tls` not calling the protocol's
+:meth:`~asyncio.BaseProtocol.connection_lost` when the connection is lost,
+the handshake times out or the call is cancelled during the TLS handshake.
+:meth:`asyncio.StreamWriter.wait_closed` no longer waits forever after such
+a failure.
+
+..
+
+.. date: 2026-10-22-08-04-26
+.. gh-issue: 160297
+.. nonce: hL4kQz
+.. section: Library
+
+Fix :meth:`tarfile.TarFile.extractall` and :meth:`tarfile.TarFile.extract`
+changing the mode, modification time and owner of a file outside the
+destination directory when a hard link member is extracted as a copy of a
+symbolic link member, for example with the ``'tar'`` filter.
+
+..
+
+.. date: 2026-10-22-05-24-34
+.. gh-issue: 161086
+.. nonce: FGPjqA
+.. section: Library
+
+Fix the :mod:`gzip` command-line interface ignoring :option:`gzip --fast`
+and :option:`gzip --best` when compressing files given as arguments.
+
+..
+
+.. date: 2026-10-22-05-24-21
+.. gh-issue: 161112
+.. nonce: BFrZRw
+.. section: Library
+
+Fix :func:`shutil.make_archive` adding the zip archive being created to
+itself when it is written inside the directory being archived or a symbolic
+link in that directory refers to it.
+
+..
+
+.. date: 2026-10-22-05-23-40
+.. gh-issue: 161088
+.. nonce: _-HEWz
+.. section: Library
+
+Fix the :mod:`gzip` command-line interface writing through a symbolic link
+at the output file name. Like :program:`gzip`, it now replaces an existing
+output file with a new one that has the permission bits of the input file.
+
+..
+
+.. date: 2026-10-22-05-21-00
+.. gh-issue: 161094
+.. nonce: MDjCNm
+.. section: Library
+
+Fix :func:`zipfile.is_zipfile` raising :exc:`ValueError` instead of
+returning ``False`` for a file-like object, such as :class:`io.BytesIO`,
+whose end of central directory record places the central directory before
+the start of the file.
+
+..
+
+.. date: 2026-10-22-05-20-52
+.. gh-issue: 161096
+.. nonce: vkhfyy
+.. section: Library
+
+Fix :meth:`zoneinfo.ZoneInfo.from_file` accepting TZif data with a negative
+or oversized abbreviation block, which could use hundreds of times the file
+size in memory; it now raises :exc:`ValueError`. Abbreviation indexes above
+127 now also give the correct time zone abbreviation.
+
+..
+
+.. date: 2026-10-22-05-20-44
+.. gh-issue: 161106
+.. nonce: t0ux5q
+.. section: Library
+
+Fix :func:`plistlib.dump` and :func:`plistlib.dumps` with
+:data:`~plistlib.FMT_BINARY` holding on to memory proportional to the size
+of large arrays and dictionaries after the call returns.
+
+..
+
+.. date: 2026-10-22-05-20-27
+.. gh-issue: 161098
+.. nonce: voMVnd
+.. section: Library
+
+Fix :class:`multiprocessing.shared_memory.ShareableList` leaving its newly
+created shared memory block behind when a value cannot be stored, such as an
+integer outside the signed 64-bit range.
+
+..
+
+.. date: 2026-10-22-05-20-18
+.. gh-issue: 161108
+.. nonce: xOVsRA
+.. section: Library
+
+Fix quadratic time complexity of :meth:`!clear` and :meth:`!popitem` on
+:class:`configparser.ConfigParser` objects and their section proxies.
+Clearing a section no longer fails part way with
+:exc:`~configparser.InterpolationError` on a value it removes.
+
+..
+
+.. date: 2026-10-22-05-20-11
+.. gh-issue: 161110
+.. nonce: miKrSQ
+.. section: Library
+
+Fix :meth:`~xml.dom.Document.getElementById` in :mod:`xml.dom.minidom` so
+that it returns the first element in document order when several elements
+have the same ID. Previously, the result could differ between calls on an
+unmodified document.
+
+..
+
+.. date: 2026-10-22-05-20-06
+.. gh-issue: 161100
+.. nonce: pLgnlA
+.. section: Library
+
+Fix :attr:`!ipaddress.IPv6Interface.is_unspecified` returning ``False`` for
+the IPv4-mapped address ``::ffff:0.0.0.0``. It now gives the same result as
+:attr:`ipaddress.IPv6Address.is_unspecified`.
+
+..
+
+.. date: 2026-10-22-05-20-02
+.. gh-issue: 161102
+.. nonce: gqDOIM7X
+.. section: Library
+
+Fix the incremental decoder of the :mod:`idna ` codec
+decoding some dots twice when its input starts with empty labels, for
+example ``b".example.com"``. Reading a run of dots through
+:class:`io.TextIOWrapper` no longer produces quadratically more text than
+the input holds.
+
+..
+
+.. date: 2026-10-22-05-20-02
+.. gh-issue: 161092
+.. nonce: OtC5l6
+.. section: Library
+
+Fix the ``uu`` codec decoder taking any line that starts with ``begin``,
+such as ``beginning of the report``, as the header of the encoded data. Like
+the :mod:`email` package, it now requires ``begin`` followed by an octal
+mode and skips other lines as leading text.
+
+..
+
+.. date: 2026-10-22-05-19-56
+.. gh-issue: 161090
+.. nonce: pxZ1IA
+.. section: Library
+
+Fix the ``punycode`` codec accepting a delimiter (``-``) that is not
+preceded by any basic code point. Such input, for example ``b'-80a1acny'``,
+now raises :exc:`UnicodeDecodeError`, as required by :rfc:`3492`.
+
+..
+
+.. date: 2026-10-22-03-55-33
+.. gh-issue: 159739
+.. nonce: ce26e1
+.. section: Library
+
+Fix :mod:`time` functions returning a negative year or failing to accept
+their own output for large timestamps on platforms that support them. Avoid
+reporting an incorrect year in errors raised by :mod:`datetime` for those
+timestamps.
+
+..
+
+.. date: 2026-10-22-03-55-33
+.. gh-issue: 159739
+.. nonce: b4c371
+.. section: Library
+
+Fix a crash when a :mod:`ctypes` structure subclass cannot be created due to
+an allocation failure.
+
+..
+
+.. date: 2026-10-22-03-55-33
+.. gh-issue: 159739
+.. nonce: a8bf30
+.. section: Library
+
+Fix clearing a :class:`pickle.Unpickler` memo so that the unpickler can be
+reused for independent records.
+
+..
+
+.. date: 2026-10-22-00-33-42
+.. gh-issue: 160171
+.. nonce: 11l4om
+.. section: Library
+
+On the server side, :meth:`ssl.SSLSocket.get_unverified_chain` now returns
+the client's certificate when the session was resumed from a session ticket,
+instead of an empty list, and returns an empty list instead of raising
+:exc:`AttributeError` when the client sent no certificate.
+
+..
+
+.. date: 2026-10-22-00-32-51
+.. gh-issue: 160181
+.. nonce: nnEeg1
+.. section: Library
+
+Fix :meth:`io.BytesIO.getvalue` sometimes returning a :class:`bytes` object
+with the hash of earlier contents after the buffer was written to, which
+made :class:`dict` and :class:`set` lookups with it fail.
+
+..
+
+.. date: 2026-10-22-00-30-04
+.. gh-issue: 160187
+.. nonce: 9dcj2B
+.. section: Library
+
+Fix the ISO-2022 decoders (``iso2022_jp``, ``iso2022_kr`` and related)
+accepting escape sequences that designate a character set to the wrong code
+element (G0, G1 or G2). Such sequences now raise :exc:`UnicodeDecodeError`
+instead of producing wrong text or :exc:`RuntimeError`.
+
+..
+
+.. date: 2026-10-22-00-29-55
+.. gh-issue: 160185
+.. nonce: BPz40E
+.. section: Library
+
+Fix :meth:`codecs.StreamWriter.reset` of the stateful CJK codecs (``hz`` and
+the ``iso2022_*`` family) not writing the sequence that returns the output
+to ASCII. ``seek(0)`` of :class:`codecs.StreamWriter`,
+:class:`codecs.StreamReaderWriter` and :class:`codecs.StreamRecoder` now
+resets the writer before moving the stream position.
+
+..
+
+.. date: 2026-10-22-00-29-50
+.. gh-issue: 160176
+.. nonce: tkNst1
+.. section: Library
+
+Fix a crash in :mod:`tkinter` when a deeply nested or recursive list or
+tuple is passed to Tcl, or a deeply nested Tcl list is converted to Python.
+These now raise :exc:`ValueError` (beyond 1000 levels) and
+:exc:`RecursionError` respectively.
+
+..
+
+.. date: 2026-10-21-21-26-10
+.. gh-issue: 159739
+.. nonce: yBc6Ei
+.. section: Library
+
+Fix a possible crash in :class:`abc.ABCMeta` instance checks when a
+subclass-checking callback changes the instance’s class.
+
+..
+
+.. date: 2026-10-21-21-26-10
+.. gh-issue: 159739
+.. nonce: rVWF2a
+.. section: Library
+
+Fix the ``truncate`` method on :class:`io.BytesIO` when converting its size
+argument closes the stream or exports its buffer.
+
+..
+
+.. date: 2026-10-21-21-26-10
+.. gh-issue: 159739
+.. nonce: k8uuGe
+.. section: Library
+
+Raise :exc:`TypeError` if a string subclass returns a non-string during
+newline translation in :class:`io.TextIOWrapper`. Recheck the stream state
+if the replacement callback closes, detaches or reinitializes the stream.
+
+..
+
+.. date: 2026-10-21-21-26-10
+.. gh-issue: 159739
+.. nonce: ghGctt
+.. section: Library
+
+Fix :class:`contextvars.ContextVar` returning a stale value after a
+reentrant finalizer changes it during :meth:`~contextvars.ContextVar.reset`.
+
+..
+
+.. date: 2026-10-21-21-26-10
+.. gh-issue: 159739
+.. nonce: b4ueJ7
+.. section: Library
+
+Detect recursive ``_as_parameter_`` chains for :mod:`ctypes` calls without
+argument types.
+
+..
+
+.. date: 2026-10-21-21-26-10
+.. gh-issue: 159739
+.. nonce: JIqZRY
+.. section: Library
+
+Fix a possible crash when a list of :mod:`sqlite3` parameters is modified
+concurrently on a free-threaded build.
+
+..
+
+.. date: 2026-10-21-20-05-00
+.. gh-issue: 160104
+.. nonce: BUAL5C
+.. section: Library
+
+Synchronized :class:`zipfile.Path` with :pypi:`zipp` 4.1.2.
+:meth:`zipfile.Path.iterdir` now raises :exc:`NotADirectoryError` instead of
+:exc:`ValueError` when the path does not reference a directory. Character
+classes in :meth:`!zipfile.Path.glob` and :meth:`!zipfile.Path.rglob`
+patterns now follow shell-style semantics, treating a leading ``!`` as
+negation and ``^`` as a literal, and no longer match path separators.
+
+..
+
+.. date: 2026-10-21-19-55-00
+.. gh-issue: 159739
+.. nonce: tloc01
+.. section: Library
+
+Avoid a crash when a :class:`threading.local` subclass finalizer accesses
+attributes after construction fails.
+
+..
+
+.. date: 2026-10-21-19-55-00
+.. gh-issue: 159739
+.. nonce: sque01
+.. section: Library
+
+Avoid a crash when a :class:`queue.SimpleQueue` subclass finalizer adds an
+item after construction fails.
+
+..
+
+.. date: 2026-10-21-19-40-00
+.. gh-issue: 100609
+.. nonce: THXgRC
+.. section: Library
+
+``str()`` of a :class:`zipfile.Path` whose underlying zipfile has no
+filename, such as one constructed from an :class:`io.BytesIO`, now renders
+that filename as ``:zipfile:`` instead of raising :exc:`TypeError`. The root
+of a zipfile is also no longer rendered with a trailing slash. Synchronized
+with :pypi:`zipp` 3.23.1.
+
+..
+
+.. date: 2026-10-21-19-38-33
+.. gh-issue: 89721
+.. nonce: uMpxRw
+.. section: Library
+
+Add ``copy_dir_stat`` parameter to :func:`shutil.copytree`: set it to false
+to skip copying permissions and times of directories with
+:func:`shutil.copystat`, e.g. when copying a read-only tree.
+
+..
+
+.. date: 2026-10-21-15-42-29
+.. gh-issue: 159875
+.. nonce: p6j3yW
+.. section: Library
+
+Fix :exc:`AttributeError` from the methods of an :mod:`asyncio` SSL
+transport, such as :meth:`~asyncio.WriteTransport.write` and
+:meth:`~asyncio.BaseTransport.set_protocol`, when the transport is closed
+after its connection was lost. This also affected the fallback of
+:meth:`loop.sendfile() ` over SSL when the peer went
+away mid-transfer. The SSL context is still released once the connection is
+lost.
+
+..
+
+.. date: 2026-10-21-15-10-00
+.. gh-issue: 160125
+.. nonce: pdbpkg
+.. section: Library
+
+Support setting breakpoints with the :mod:`pdb` ``break`` and ``tbreak``
+commands using ``package.module.function`` names when the module has not
+been imported in the current namespace.
+
+..
+
+.. date: 2026-10-20-17-29-14
+.. gh-issue: 138641
+.. nonce: FN6qM0
+.. section: Library
+
+Ignore :func:`pdb.set_trace` when called directly at the :mod:`pdb` prompt.
+
+..
+
+.. date: 2026-10-20-16-00-00
+.. gh-issue: 159868
+.. nonce: qLhYkP
+.. section: Library
+
+Allow :meth:`!collections.UserString.startswith` and
+:meth:`!collections.UserString.endswith` to accept a
+:class:`~collections.UserString` instance as the prefix or suffix argument.
+
+..
+
+.. date: 2026-10-20-12-30-00
+.. gh-issue: 159864
+.. nonce: 4FZ6MR
+.. section: Library
+
+Fix a crash in :func:`syslog.openlog` under the free-threaded build when
+:data:`sys.argv` is modified concurrently.
+
+..
+
+.. date: 2026-10-20-00-12-05
+.. gh-issue: 159690
+.. nonce: vZgLP6
+.. section: Library
+
+Fix :class:`logging.handlers.TimedRotatingFileHandler` permanently stopping
+rollover after a rollover failed or its backup file already existed, for
+example at a DST change.
+
+..
+
+.. date: 2026-10-20-00-00-00
+.. gh-issue: 159739
+.. nonce: eb8987
+.. section: Library
+
+Avoid undefined behavior when :func:`struct.pack_into` copies a bytearray
+into overlapping output.
+
+..
+
+.. date: 2026-10-20-00-00-00
+.. gh-issue: 159739
+.. nonce: 9ef89c
+.. section: Library
+
+Fix allocation error handling in the fallback implementation of
+``getaddrinfo()``.
+
+..
+
+.. date: 2026-10-20-00-00-00
+.. gh-issue: 159739
+.. nonce: 5d4269
+.. section: Library
+
+Fix a double free if remote unwinder initialization runs out of memory.
+
+..
+
+.. date: 2026-10-20-00-00-00
+.. gh-issue: 159739
+.. nonce: 4c9783
+.. section: Library
+
+Fix :meth:`io.IOBase.readline` returning more bytes than requested when a
+stream supports :meth:`!peek` and returns short reads.
+
+..
+
+.. date: 2026-10-20-00-00-00
+.. gh-issue: 159739
+.. nonce: 3660a6
+.. section: Library
+
+Fix multibyte encoders silently consuming a non-BMP character when looking
+up a two-character mapping.
+
+..
+
+.. date: 2026-10-20-00-00-00
+.. gh-issue: 159739
+.. nonce: 35942a
+.. section: Library
+
+Improve performance when parsing email address groups with many members.
+
+..
+
+.. date: 2026-10-20-00-00-00
+.. gh-issue: 159739
+.. nonce: 1e4599
+.. section: Library
+
+Fix off-by-one output buffer checks in the fallback implementation of
+``getnameinfo()``.
+
+..
+
+.. date: 2026-10-20-00-00-00
+.. gh-issue: 159739
+.. nonce: 0c4ae9
+.. section: Library
+
+Fix reference cycles involving the types of grapheme iterators and segments
+created by :func:`unicodedata.iter_graphemes`.
+
+..
+
+.. date: 2026-10-19-23-25-29
+.. gh-issue: 159811
+.. nonce: cMB4DO
+.. section: Library
+
+Fix a crash in :mod:`hashlib` when the OpenSSL routine used by
+:meth:`hash.update() ` or by hash object constructors
+fails on data larger than 2048 bytes. Patch by Bénédikt Tran.
+
+..
+
+.. date: 2026-10-19-23-25-29
+.. gh-issue: 159811
+.. nonce: P6yy0z
+.. section: Library
+
+Fix a crash in :mod:`hmac` when the OpenSSL routine used by
+:meth:`hmac.HMAC.update` or by :func:`hmac.new` fails on data larger than
+2048 bytes. Patch by Bénédikt Tran.
+
+..
+
+.. date: 2026-10-19-21-20-28
+.. gh-issue: 159786
+.. nonce: fThehQ
+.. section: Library
+
+Fix the error handling of the HACL* routine used by :func:`hmac.new` and
+:meth:`hmac.HMAC.update`. If the maximum input length of the underlying hash
+function is exceeded, an :exc:`OverflowError` is now raised on all builds,
+instead of crashing on DEBUG builds and being silently ignored otherwise.
+Code correctness. Realistically this can only happen at implausible sizes.
+Patch by Bénédikt Tran.
+
+..
+
+.. date: 2026-10-19-20-38-17
+.. gh-issue: 159739
+.. nonce: ff088c
+.. section: Library
+
+Fix copying :class:`collections.deque` subclasses with a large maximum
+length.
+
+..
+
+.. date: 2026-10-19-20-38-17
+.. gh-issue: 159739
+.. nonce: bc65da
+.. section: Library
+
+Allow cyclic garbage collection to reclaim group records returned by
+:mod:`grp`.
+
+..
+
+.. date: 2026-10-19-20-38-17
+.. gh-issue: 159739
+.. nonce: a81270
+.. section: Library
+
+Fix :class:`io.BytesIO` reads into overlapping views of the same buffer.
+
+..
+
+.. date: 2026-10-19-20-38-17
+.. gh-issue: 159739
+.. nonce: 5a6e94
+.. section: Library
+
+Avoid a crash when memory allocation fails while creating a
+:class:`collections.OrderedDict` items iterator.
+
+..
+
+.. date: 2026-10-19-20-38-17
+.. gh-issue: 159739
+.. nonce: 243aa8
+.. section: Library
+
+Avoid reading past the end of an encoding name when the ``surrogatepass``
+error handler receives a truncated UTF-16 or UTF-32 name.
+
+..
+
+.. date: 2026-10-19-20-38-17
+.. gh-issue: 159739
+.. nonce: 08caa7
+.. section: Library
+
+Fix incorrect :mod:`ctypes` scalar values after :func:`ctypes.resize`
+enlarges the object.
+
+..
+
+.. date: 2026-10-19-19-33-35
+.. gh-issue: 159739
+.. nonce: b5fbca
+.. section: Library
+
+Fix a memory leak when Unicode normalization cannot grow its temporary
+buffer.
+
+..
+
+.. date: 2026-10-19-19-33-35
+.. gh-issue: 159739
+.. nonce: a1c3c7
+.. section: Library
+
+Fix resource leaks in :mod:`ssl` when certificate conversion or key log
+setup fails.
+
+..
+
+.. date: 2026-10-19-16-49-09
+.. gh-issue: 159706
+.. nonce: ushGrx
+.. section: Library
+
+Fix the pure-Python :class:`zoneinfo.ZoneInfo` setting ``fold=0`` in
+:meth:`~datetime.tzinfo.fromutc` for times in the fold created by the only
+transition of a zone with a single transition.
+
+..
+
+.. date: 2026-10-19-16-26-57
+.. gh-issue: 71990
+.. nonce: K3FlJ9
+.. section: Library
+
+:mod:`ctypes`: objects with an :attr:`!_as_parameter_` attribute are now
+implicitly converted when passed for a :func:`~ctypes.POINTER` argument.
+
+..
+
+.. date: 2026-10-19-16-00-00
+.. gh-issue: 139122
+.. nonce: bYtEs1
+.. section: Library
+
+:class:`uuid.UUID` now consistently raises :exc:`TypeError` when the *bytes*
+or *bytes_le* argument is not a :class:`bytes` object. Previously, some
+invalid inputs raised :exc:`AssertionError` or :exc:`ValueError`.
+
+..
+
+.. date: 2026-10-19-12-00-00
+.. gh-issue: 78327
+.. nonce: Qk3hzA
+.. section: Library
+
+:mod:`ctypes` data types now set :meth:`~object.__hash__` to ``None``, so
+:class:`collections.abc.Hashable` checks report them correctly.
+
+..
+
+.. date: 2026-10-19-12-00-00
+.. gh-issue: 159714
+.. nonce: j59fix
+.. section: Library
+
+Fix :class:`zoneinfo.ZoneInfo` interpreting the Julian day rule ``J59`` as
+February 29 in leap years instead of February 28.
+
+..
+
+.. date: 2026-10-19-00-00-00
+.. gh-issue: 149015
+.. nonce: bdb
+.. section: Library
+
+Fix :meth:`bdb.Bdb.clear_all_file_breaks` leaving breakpoints behind when
+multiple breakpoints are set on the same line.
+
+..
+
+.. date: 2026-10-18-16-09-24
+.. gh-issue: 159684
+.. nonce: VHVYjVuE
+.. section: Library
+
+Update :mod:`configparser` and its tests to modern linter standards:
+printf-style and :meth:`str.format` call sites are now f-strings, and a
+handful of constructs have simpler spellings. No behavior change.
+
+..
+
+.. date: 2026-10-18-12-20-00
+.. gh-issue: 159465
+.. nonce: partial-escapes
+.. section: Library
+
+Preserve :exc:`SyntaxError` for malformed escapes in unfinished f-strings
+and t-strings passed to :func:`codeop.compile_command`.
+
+..
+
+.. date: 2026-10-18-08-30-10
+.. gh-issue: 155976
+.. nonce: feSum4_j
+.. section: Library
+
+:func:`curses.set_term` and :meth:`curses.screen.use` now update
+:data:`curses.LINES`, :data:`curses.COLS`, :data:`curses.COLORS` and
+:data:`curses.COLOR_PAIRS` for the current screen.
+
+..
+
+.. date: 2026-10-17-19-41-12
+.. gh-issue: 157210
+.. nonce: o9hycSeJ
+.. section: Library
+
+Fix entering a combining character in the lower-right cell of
+:class:`curses.textpad.Textbox`: it no longer takes a cell of its own,
+pushing its base character off the window. In insert mode, a combining
+character no longer shifts the following text.
+
+..
+
+.. date: 2026-10-17-19-33-13
+.. gh-issue: 159643
+.. nonce: EJfe0IXetV
+.. section: Library
+
+Fix :exc:`EOFError` raised by :mod:`tarfile` in stream mode with bz2, xz or
+zstd compression when reading past the end of the compressed data, for
+example with *ignore_zeros* or an archive without end-of-archive blocks.
+
+..
+
+.. date: 2026-10-17-15-22-16
+.. gh-issue: 159620
+.. nonce: Ynsu5L
+.. section: Library
+
+Fix ``python -m asyncio ps``, ``pstree`` and async-aware
+:mod:`profiling.sampling` stacks stopping at asynchronous generators. Patch
+by Timofei Ivankov.
+
+..
+
+.. date: 2026-10-16-18-23-03
+.. gh-issue: 159558
+.. nonce: ctRelk
+.. section: Library
+
+Speed up assignment to the ``value`` attribute of simple :mod:`ctypes`
+types, to the ``contents`` attribute of :mod:`ctypes` pointers and to
+:mod:`ctypes` structure fields, array items and pointer items on the
+free-threaded build by not re-entering the critical section already held on
+the object.
+
+..
+
+.. date: 2026-10-16-13-00-00
+.. gh-issue: 159435
+.. nonce: OMNI
+.. section: Library
+
+Fix an offset calculation in :mod:`tarfile` when a PAX header with a
+``size`` record is followed by a GNU long-name header. Such archives could
+duplicate or skip members while being read.
+
+..
+
+.. date: 2026-10-16-10-25-22
+.. gh-issue: 159458
+.. nonce: q02EnY
+.. section: Library
+
+Fix a ThreadSanitizer data race on the static cache in
+``normalize_century()`` of the datetime module under the free-threaded
+build.
+
+..
+
+.. date: 2026-10-16-01-56-15
+.. gh-issue: 159503
+.. nonce: WgYiow
+.. section: Library
+
+Fix quadratic copying in :mod:`asyncio` selector socket transports on
+partial sends. A :class:`bytearray` passed to
+:meth:`~asyncio.WriteTransport.write` now stays locked against resizing
+until it has been sent.
+
+..
+
+.. date: 2026-10-15-18-38-22
+.. gh-issue: 159500
+.. nonce: OjAQ8W
+.. section: Library
+
+Speed up :meth:`asyncio.StreamReader.readline` and
+:meth:`asyncio.StreamReader.readuntil` when the data is already buffered,
+and stop :meth:`~asyncio.StreamReader.readuntil` with a tuple of separators
+from scanning the whole buffer on every call.
+
+..
+
+.. date: 2026-10-15-13-44-03
+.. gh-issue: 159465
+.. nonce: Ph-m8w
+.. section: Library
+
+Improve incomplete input detection in :mod:`codeop` without an extra parser
+pass, and preserve syntax and compiler errors.
+
+..
+
+.. date: 2026-10-14-14-47-05
+.. gh-issue: 81954
+.. nonce: KvM0gY
+.. section: Library
+
+Fix :class:`zipfile.ZipFile` not being closed at interpreter shutdown when
+emitting its :exc:`ResourceWarning` failed with an :exc:`ImportError`.
+
+..
+
+.. date: 2026-10-14-11-41-00
+.. gh-issue: 159430
+.. nonce: ZEW-mx
+.. section: Library
+
+Report the correct exception if looking up ``__name__`` raises an exception
+when calling :func:`repr` on a :class:`weakref.ref`.
+
+..
+
+.. date: 2026-10-14-10-26-10
+.. gh-issue: 159387
+.. nonce: xMbQbB
+.. section: Library
+
+Fix :mod:`ssl` reporting TLS 1.0, 1.1, and 1.2 as unavailable when built
+with OpenSSL 4.0, despite support for these protocol versions.
+
+..
+
+.. date: 2026-10-14-08-50-00
+.. gh-issue: 159398
+.. nonce: k2Xd7q
+.. section: Library
+
+Fix the sampling profiler crashing when a string read from the target
+process contains code points above ``U+10FFFF``.
+
+..
+
+.. date: 2026-10-13-19-10-00
+.. gh-issue: 159322
+.. nonce: hP6k3A
+.. section: Library
+
+Fix :mod:`tarfile` to NUL-terminate user and group names in PAX archive
+headers and use extended headers for names longer than 31 characters.
+
+..
+
+.. date: 2026-10-13-12-00-00
+.. gh-issue: 159304
+.. nonce: mFbYq2
+.. section: Library
+
+Fix :exc:`AttributeError` in :meth:`email.message.EmailMessage.get_body`
+when a nested ``multipart`` part is malformed and its payload is a string.
+
+..
+
+.. date: 2026-10-12-21-20-00
+.. gh-issue: 159225
+.. nonce: T8jlor
+.. section: Library
+
+Prevent ``input`` calls in PyREPL from modifying readline history.
+
+..
+
+.. date: 2026-10-12-18-21-06
+.. gh-issue: 159240
+.. nonce: a1b2c3
+.. section: Library
+
+Deprecate, and schedule for removal in Python 3.20, the ``__author__``,
+``__credits__``, ``__copyright__`` and ``__date__`` attributes of
+:mod:`bz2`, :mod:`concurrent.futures`, :mod:`inspect`, :mod:`io`,
+:mod:`json`, :mod:`logging`, :mod:`optparse`, :mod:`platform`, :mod:`pydoc`,
+:mod:`tarfile`, :mod:`tkinter.ttk`, :mod:`tokenize` and :mod:`uuid`.
+
+..
+
+.. date: 2026-10-12-13-05-00
+.. gh-issue: 158501
+.. nonce: n7Qp3k
+.. section: Library
+
+:meth:`datetime.time.fromisoformat` and
+:meth:`datetime.datetime.fromisoformat` now reject stray text between the
+time and a UTC offset. The C implementation previously accepted strings that
+the pure-Python implementation rejected.
+
+..
+
+.. date: 2026-10-12-12-00-00
+.. gh-issue: 72113
+.. nonce: njkm8v
+.. section: Library
+
+Speed up creating a :mod:`ctypes` array from initializers, such as ``(c_int
+* 3)(1, 2, 3)``, by roughly 3x.
+
+..
+
+.. date: 2026-10-12-11-36-48
+.. gh-issue: 158856
+.. nonce: jLR-Lv
+.. section: Library
+
+Improve large Enum creation performance.
+
+..
+
+.. date: 2026-10-12-00-00-00
+.. gh-issue: 159044
+.. nonce: Tr8kXv
+.. section: Library
+
+Restore the previous behaviour of
+:meth:`http.client.HTTPConnection.set_tunnel` where header values that are
+not strings (such as :const:`None`, :class:`int` or other objects) are
+converted with :class:`str` instead of raising :exc:`AttributeError` when
+the request is sent.
+
+..
+
+.. date: 2026-10-11-13-40-44
+.. gh-issue: 159168
+.. nonce: z3KjB8
+.. section: Library
+
+Fix :exc:`RecursionError` in ``python -m asyncio pstree`` on a deep chain of
+awaiting tasks. Patch by Timofei Ivankov.
+
+..
+
+.. date: 2026-10-11-13-08-07
+.. gh-issue: 88037
+.. nonce: CzKcxh
+.. section: Library
+
+:func:`urllib.parse.urlsplit` and :func:`urllib.parse.urlparse` now raise
+:exc:`ValueError` for an invalid port when the URL is parsed, instead of
+when the :attr:`!port` attribute is read. Patch by Miguel Brito and Senthil
+Kumaran.
+
+..
+
+.. date: 2026-10-11-08-42-00
+.. gh-issue: 159184
+.. nonce: Tq2nSe
+.. section: Library
+
+The output of :func:`marshal.dumps` no longer depends on the order of the
+elements of a set which have the same marshalled form, such as NaNs which
+are distinct objects.
+
+..
+
+.. date: 2026-10-10-22-29-13
+.. gh-issue: 159049
+.. nonce: eJUiKL
+.. section: Library
+
+Fix reference cycles in :meth:`asyncio.loop.create_connection` and
+:meth:`asyncio.loop.start_tls` after a failed TLS handshake. Patch by
+Timofei Ivankov.
+
+..
+
+.. date: 2026-10-10-22-14-22
+.. gh-issue: 150751
+.. nonce: JInuGL
+.. section: Library
+
+:mod:`http.client` now ignores optional whitespace around the
+``Content-Length`` header value when validating it, as required by
+:rfc:`9112`. Previously a value with trailing whitespace (for example
+``Content-Length: 5`` followed by a space) was treated as missing and the
+response body was read until the connection was closed.
+
+..
+
+.. date: 2026-10-08-21-02-38
+.. gh-issue: 158998
+.. nonce: DZYJI7
+.. section: Library
+
+Fix :func:`os.statx` ignoring the *follow_symlinks* argument.
+
+..
+
+.. date: 2026-10-08-11-58-52
+.. gh-issue: 158628
+.. nonce: NJxwuw
+.. section: Library
+
+Implement :data:`sys._wasi_info` for exposing WASI-specific system details.
+
+..
+
+.. date: 2026-10-07-17-30-00
+.. gh-issue: 158287
+.. nonce: xY9zQp
+.. section: Library
+
+Fix a bug in :mod:`asyncio` where stopping a child process (such as with
+``SIGSTOP``) on macOS caused the event loop to block indefinitely.
+
+..
+
+.. date: 2026-10-07-10-59-27
+.. gh-issue: 155233
+.. nonce: YGuQGK
+.. section: Library
+
+Fix :meth:`asyncio.Barrier.wait` returning duplicate indices when a waiting
+task is cancelled before the barrier is released.```
+
+..
+
+.. date: 2026-10-05-14-58-12
+.. gh-issue: 158839
+.. nonce: wYd6fI
+.. section: Library
+
+The log functions in the :mod:`logging` module and the
+:class:`logging.Logger` class now normalize falsy ``exc_info`` arguments to
+``None`` before passing them to :meth:`logging.Logger.makeRecord` and
+subsequently to :class:`logging.LogRecord`. This aligns
+``logging.LogRecord.exc_info`` with the documentation.
+
+..
+
+.. date: 2026-10-05-08-35-10
+.. gh-issue: 130698
+.. nonce: iibO9V
+.. section: Library
+
+Fix PyREPL to convert :data:`sys.ps1` and :data:`sys.ps2` to strings before
+use, and fall back to the default prompts if the conversion raises.
+
+..
+
+.. date: 2026-09-29-19-34-30
+.. gh-issue: 158192
+.. nonce: 6wPjiU
+.. section: Library
+
+Expose the future being waited on by a ``FutureIter`` as ``fi_future``.
+
+..
+
+.. date: 2026-09-28-00-00-00
+.. gh-issue: 158370
+.. nonce: ctxmgr
+.. section: Library
+
+:class:`concurrent.interpreters.Interpreter` objects now support the
+:term:`context manager` protocol.
+
+..
+
+.. date: 2026-09-27-14-00-00
+.. gh-issue: 158277
+.. nonce: aBcDeF
+.. section: Library
+
+Fix :mod:`sqlite3` CLI completer to include view columns in column-name
+completion.
+
+..
+
+.. date: 2026-09-26-05-18-21
+.. gh-issue: 144650
+.. nonce: zqHLOW
+.. section: Library
+
+Use Argument Clinic vectorcall support for the :class:`decimal.Decimal`
+type. This offers 1.10x speedup on creation of small instances.
+
+..
+
+.. date: 2026-09-25-17-04-45
+.. gh-issue: 158159
+.. nonce: lbEalG
+.. section: Library
+
+Fix a use-after-free in :meth:`asyncio.Task.get_name` when formatting the
+default task name triggers a garbage collection whose finalizers call
+:meth:`~asyncio.Task.get_name` on the same task.
+
+..
+
+.. date: 2026-09-25-01-29-55
+.. gh-issue: 158126
+.. nonce: nWmFnq
+.. section: Library
+
+Speed up :func:`pickle.dumps` and creating a :class:`pickle.Pickler` by
+avoiding the creation of an :exc:`AttributeError` when looking up the
+optional ``reducer_override`` and ``dispatch_table`` attributes.
+
+..
+
+.. date: 2026-09-24-14-59-08
+.. gh-issue: 158095
+.. nonce: lcKOT4
+.. section: Library
+
+Fix a memory leak in :func:`re.finditer` and regular expression scanners
+when their input participates in a reference cycle.
+
+..
+
+.. date: 2026-09-23-23-34-30
+.. gh-issue: 144812
+.. nonce: ujptbVOI
+.. section: Library
+
+Make :class:`argparse.ArgumentGroup` and
+:class:`argparse.MutuallyExclusiveGroup` public. The private
+``_ArgumentGroup`` and ``_MutuallyExclusiveGroup`` names remain as aliases.
+
+..
+
+.. date: 2026-09-23-19-59-03
+.. gh-issue: 158004
+.. nonce: p68swW
+.. section: Library
+
+Fix :func:`asyncio.as_completed` to continue yielding every awaitable after
+a pending iteration step is cancelled.
+
+..
+
+.. date: 2026-09-23-09-21-25
+.. gh-issue: 89977
+.. nonce: fmia18
+.. section: Library
+
+Avoid releasing the GIL for :meth:`socket.socket.setblocking`,
+:meth:`socket.socket.getsockname`, :meth:`socket.socket.getpeername`, and
+:func:`socket.gethostname`.
+
+..
+
+.. date: 2026-09-21-21-07-12
+.. gh-issue: 157928
+.. nonce: ZPlNYC
+.. section: Library
+
+Correctly detect and handle OSC sequences in PyREPL.
+
+..
+
+.. date: 2026-09-21-14-41-07
+.. gh-issue: 157899
+.. nonce: s6vBQC
+.. section: Library
+
+:func:`os.readlink` now accepts a file descriptor referring to a symlink on
+Linux, Android, macOS and iOS.
+
+..
+
+.. date: 2026-09-20-21-24-05
+.. gh-issue: 157880
+.. nonce: aE7wIu
+.. section: Library
+
+Fix :class:`mailbox.Babyl` to write the visible headers of a
+:class:`mailbox.BabylMessage` to the mailbox file.
+
+..
+
+.. date: 2026-09-20-12-00-00
+.. gh-issue: 157856
+.. nonce: wq4xuF
+.. section: Library
+
+Fix :func:`asyncio.as_completed` raising :exc:`RuntimeError` ("no running
+event loop") when the iterator is created outside of a running event loop
+and driven with :meth:`loop.run_until_complete()
+`.
+
+..
+
+.. date: 2026-09-18-00-00-00
+.. gh-issue: 49960
+.. nonce: MDT3jE
+.. section: Library
+
+:mod:`ctypes` callback functions can now return structures and unions by
+value. Previously only "simple" types could be returned, and any other
+result type raised :exc:`TypeError`.
+
+..
+
+.. date: 2026-09-17-20-36-01
+.. gh-issue: 157290
+.. nonce: NfFmt
+.. section: Library
+
+Add the ``%Nf`` format code (where *N* is from 1 to 6) to
+:meth:`datetime.datetime.strftime`, :meth:`datetime.time.strftime`,
+:meth:`datetime.date.strftime`, :meth:`datetime.datetime.strptime` and
+:meth:`datetime.time.strptime`.
+
+..
+
+.. date: 2026-09-17-10-30-00
+.. gh-issue: 158252
+.. nonce: strptime
+.. section: Library
+
+Speed up :func:`time.strptime`, :meth:`datetime.date.strptime`,
+:meth:`datetime.time.strptime`, and :meth:`datetime.datetime.strptime` for
+common numeric formats by parsing fields and constructing the result in C.
+Other inputs continue to use the Python parser.
+
+..
+
+.. date: 2026-09-05-17-29-50
+.. gh-issue: 160837
+.. nonce: W6kHva
+.. section: Library
+
+:func:`asyncio.print_call_graph` no longer truncates the call stack of a
+task suspended inside an asynchronous generator.
+
+..
+
+.. date: 2026-09-01-00-00-00
+.. gh-issue: 156784
+.. nonce: 8gvtt4
+.. section: Library
+
+:class:`asyncio.ProactorEventLoop` no longer silently ignores
+:exc:`ConnectionResetError` on UDP sockets, matching
+:class:`asyncio.SelectorEventLoop`.
+
+..
+
+.. date: 2026-08-29-14-28-46
+.. gh-issue: 156568
+.. nonce: mkxLY8
+.. section: Library
+
+:func:`zipapp.create_archive` now correctly sets the executable bit on the
+target archive when copying a zipapp where the target is a path-like object.
+
+..
+
+.. date: 2026-08-29-13-41-56
+.. gh-issue: 154675
+.. nonce: cYvE-Z
+.. section: Library
+
+Improve import time of :mod:`pdb`, :mod:`bdb` and :mod:`code` by lazily
+importing several dependencies.
+
+..
+
+.. date: 2026-08-23-16-33-00
+.. gh-issue: 151126
+.. nonce: GUvtG7
+.. section: Library
+
+Fix a crash caused by failing to set :exc:`MemoryError` on allocation
+failure when first using a Chinese, Japanese or Korean codec.
+
+..
+
+.. date: 2026-08-21-06-00-00
+.. gh-issue: 156057
+.. nonce: tarfile-wrap-comp-err
+.. section: Library
+
+Wrap the underlying compression library's exception in
+:exc:`tarfile.ReadError` when a member's compressed data is corrupt past its
+header, for all of :mod:`tarfile`'s supported compression formats (gzip,
+bzip2, lzma, zstd). Previously the raw exception (e.g. :exc:`zlib.error`)
+could leak through :meth:`tarfile.TarFile.extractfile`. Patch by Jason Mak.
+
+..
+
+.. date: 2026-08-20-09-56-45
+.. gh-issue: 156078
+.. nonce: -E7gZc
+.. section: Library
+
+:meth:`zipfile.ZipFile.mkdir` now raises :exc:`ValueError` when the archive
+is closed or when a writable member handle is open.
+
+..
+
+.. date: 2026-08-15-12-08-33
+.. gh-issue: 155833
+.. nonce: Pi2Yjp
+.. section: Library
+
+Ensure that MD5 and SHA* objects are properly GC-untracked before freeing
+their internal HACL* state. Patch by Bénédikt Tran.
+
+..
+
+.. date: 2026-08-15-11-49-30
+.. gh-issue: 155830
+.. nonce: cY5xgK
+.. section: Library
+
+:mod:`!_blake2`: Ensure that BLAKE-2 objects are correctly initialized
+before being tracked by the garbage collector. Patch by Bénédikt Tran.
+
+..
+
+.. date: 2026-08-15-11-30-42
+.. gh-issue: 155782
+.. nonce: JUmDP4
+.. section: Library
+
+:mod:`ssl`: prevent a crash in :meth:`~ssl.SSLSocket.group` for session-less
+objects on OpenSSL 3.2 and later. Patch by Bénédikt Tran.
+
+..
+
+.. date: 2026-08-09-14-26-48
+.. gh-issue: 155428
+.. nonce: wi0_fI
+.. section: Library
+
+Ensure that :func:`hmac.digest` and :meth:`hmac.HMAC.digest` output
+identical values when using a digest's block size smaller than 16. Patch by
+Bénédikt Tran.
+
+..
+
+.. date: 2026-08-09-14-06-27
+.. gh-issue: 155426
+.. nonce: zZVPMd
+.. section: Library
+
+Make sure that the pure Python fallback of :func:`hmac.digest` reject keys
+that are neither :class:`bytes` or :class:`bytearray`. Previously, an
+:exc:`AttributeError` was raised instead of :exc:`TypeError`. Patch by
+Bénédikt Tran.
+
+..
+
+.. date: 2026-08-05-10-13-23
+.. gh-issue: 153711
+.. nonce: 9g9dVz
+.. section: Library
+
+On iOS, add :func:`os.pipe2`, and use the syscalls :manpage:`pipe2 (2)` and
+:manpage:`dup3 (2)` internally, when available at both build-time and
+run-time.
+
+..
+
+.. date: 2026-08-04-16-38-59
+.. gh-issue: 155152
+.. nonce: qN1EEN
+.. section: Library
+
+Improve performance of some :mod:`zipimport` archives that use Zstandard
+compression.
+
+..
+
+.. date: 2026-07-21-00-02-11
+.. gh-issue: 148228
+.. nonce: D3rP8m
+.. section: Library
+
+The :term:`REPL` now displays error messages when editing commands cannot be
+performed, such as when tab completion finds no matches or a history search
+fails. Patch by Bartosz Sławecki.
+
+..
+
+.. date: 2026-07-16-21-30-00
+.. gh-issue: 74876
+.. nonce: wR3fXk
+.. section: Library
+
+Weak references (:class:`weakref.ref`), :class:`weakref.WeakMethod`,
+:class:`weakref.WeakSet`, :class:`weakref.WeakValueDictionary` and
+:class:`weakref.WeakKeyDictionary` can now be pickled if the weakly
+referenced objects are strongly referenced elsewhere in the same pickle;
+otherwise pickling raises :exc:`pickle.PicklingError`.
+:class:`weakref.WeakMethod` and :class:`weakref.WeakSet` can now also be
+copied.
+
+..
+
+.. date: 2026-07-13-00-10-00
+.. gh-issue: 153679
+.. nonce: RJ2WGB
+.. section: Library
+
+:class:`zipimport.zipimporter` now raises :exc:`zipimport.ZipImportError`
+instead of :exc:`UnicodeDecodeError` for a UTF-8-flagged file name that is
+not valid UTF-8. Patch by tonghuaroot.
+
+..
+
+.. date: 2026-07-11-16-00-00
+.. gh-issue: 153605
+.. nonce: Rk7Xz3
+.. section: Library
+
+Fix :class:`gettext.GNUTranslations` raising :exc:`struct.error` instead of
+:exc:`OSError` when reading a malformed ``.mo`` file. Patch by tonghuaroot.
+
+..
+
+.. date: 2026-07-04-12-52-22
+.. gh-issue: 149816
+.. nonce: XQOutB
+.. section: Library
+
+:mod:`hashlib`: fix a crash arising from a race condition when looking up an
+OpenSSL hash algorithm by name the first time. Patch by Bénédikt Tran.
+
+..
+
+.. date: 2026-06-30-08-39-07
+.. gh-issue: 62222
+.. nonce: Zq7x2P
+.. section: Library
+
+Fix :func:`binascii.a2b_qp` and :mod:`quopri` discarding the character after
+a ``=`` that does not start a valid escape: ``b'==41'`` now decodes to
+``b'=A'``, as in the :mod:`email` package. Add a keyword-only *strip_ws*
+parameter to :func:`binascii.a2b_qp`, :func:`quopri.decode` and
+:func:`quopri.decodestring` to strip trailing whitespace from each line, as
+required by :rfc:`2045`.
+
+..
+
+.. date: 2026-06-28-14-37-01
+.. gh-issue: 152490
+.. nonce: A8qLbF
+.. section: Library
+
+Fix :exc:`TypeError` when formatting a :exc:`SyntaxError` raised with
+:data:`NotImplemented` as its argument, which caused unexpected REPL exit
+and IDLE Shell restart.
+
+..
+
+.. date: 2026-06-27-08-31-30
+.. gh-issue: 152373
+.. nonce: 3cd0aa
+.. section: Library
+
+Fix the :mod:`pdb` ``until`` command not stepping over a list comprehension
+when a breakpoint is set on it. Patch by tonghuaroot.
+
+..
+
+.. date: 2026-06-18-11-26-00
+.. gh-issue: 151633
+.. nonce: uJzHdc
+.. section: Library
+
+Fix a use-after-free under free-threading when multiple threads update the
+same :class:`~collections.Counter` concurrently.
+
+..
+
+.. date: 2026-05-21-16-15-01
+.. gh-issue: 105578
+.. nonce: oq-0pg
+.. section: Library
+
+Deprecate :data:`typing.AnyStr` type variable and raise a warning when it is
+imported.
+
+..
+
+.. date: 2026-05-09-12-58-04
+.. gh-issue: 149527
+.. nonce: hX36Yh
+.. section: Library
+
+:mod:`multiprocessing`: fix creation of temporary socket files following
+:gh:`137335` (`PR#148578 `__
+and corresponding backports). Patch by Bénédikt Tran.
+
+..
+
+.. date: 2026-05-03-22-52-07
+.. gh-issue: 149309
+.. nonce: gXhk9Y
+.. section: Library
+
+:exc:`bdb.BdbQuit` is now a subclass of :exc:`BaseException`, instead of
+:exc:`Exception`, to allow it to be used for cleanly exiting the debugger
+without being accidentally caught by user code.
+
+..
+
+.. date: 2026-04-27-20-30-16
+.. gh-issue: 149083
+.. nonce: xcmpSO
+.. section: Library
+
+:data:`functools.Placeholder` is now a :class:`sentinel`. It is no longer an
+instance of its own singleton type.
+
+..
+
+.. date: 2026-03-28-14-34-18
+.. gh-issue: 143376
+.. nonce: FvWTwi
+.. section: Library
+
+:mod:`concurrent.interpreters`: fix a crash when internal cross-interpreter
+channel ends have incorrect channel IDs. Patch by Bénédikt Tran.
+
+..
+
+.. date: 2026-03-28-10-27-46
+.. gh-issue: 146169
+.. nonce: RBF1xp
+.. section: Library
+
+:mod:`xml.parsers.expat`: raise :exc:`RuntimeError` when an Expat handler
+calls :meth:`parser.Parse ` or
+:meth:`parser.ParseFile ` on the
+parser that called the handler. Patch by Bénédikt Tran.
+
+..
+
+.. date: 2026-03-23-00-04-13
+.. gh-issue: 146065
+.. nonce: FIdn8D
+.. section: Library
+
+Fix a crash in asyncio.Future iterator when send() is called after throw()
+or close().
+
+..
+
+.. date: 2026-01-06-09-13-53
+.. gh-issue: 84644
+.. nonce: V_cYP3
+.. section: Library
+
+Deprecate using a return annotation to infer the dispatch type for
+:func:`functools.singledispatch` and
+:class:`functools.singledispatchmethod`. It will raise :exc:`TypeError` in
+Python 3.21. Annotate the dispatch parameter or pass the dispatch type
+explicitly instead. Patch by Bartosz Sławecki.
+
+..
+
+.. date: 2025-10-20-13-08-04
+.. gh-issue: 84027
+.. nonce: HjBO0B
+.. section: Library
+
+:mod:`shutil` now can unpack wheel packages using the ``whl`` format.
+
+..
+
+.. date: 2025-10-13-15-43-09
+.. gh-issue: 140036
+.. nonce: b_59uN
+.. section: Library
+
+Avoid hanging in floor division of pure Python :class:`decimal.Decimal`
+instances when the context precision is very large. Patch by Bénédikt Tran.
+
+..
+
+.. date: 2025-09-18-18-03-32
+.. gh-issue: 139105
+.. nonce: 1QQ_W4
+.. section: Library
+
+Correct the EOF key shown in the :mod:`sqlite3` CLI ``.help`` text on
+Windows.
+
+..
+
+.. date: 2025-09-18-14-13-00
+.. gh-issue: 139122
+.. nonce: m3lp66
+.. section: Library
+
+:mod:`uuid`: Reimplement :class:`~uuid.UUID` objects, :func:`~uuid.uuid4`,
+and :func:`~uuid.uuid7` in C.
+
+..
+
+.. date: 2025-06-12-15-39-48
+.. gh-issue: 89730
+.. nonce: Lu35Fu
+.. section: Library
+
+Add support for Encrypted Client Hello (ECH) to the :mod:`ssl` module with
+OpenSSL 4.0 or later.
+
+..
+
+.. date: 2025-03-13-20-21-00
+.. gh-issue: 115810
+.. nonce: qwrb231
+.. section: Library
+
+Add :attr:`datetime.timezone.name`, the *name* passed to the constructor, or
+``None`` if no name was passed.
+
+..
+
+.. date: 2025-02-04-09-01-06
+.. gh-issue: 129605
+.. nonce: wKGNXQ
+.. section: Library
+
+Improve exception handling when computing suggestions in traceback.py. This
+fixes a bug that could cause PyREPL to exit unexpectedly.
+
+..
+
+.. date: 2024-12-27-15-41-55
+.. gh-issue: 128289
+.. nonce: -hCzEc
+.. section: Library
+
+Add *eager_tasks* parameter to :func:`asyncio.run` function and
+:class:`asyncio.Runner` class constructor.
+
+..
+
+.. date: 2023-01-26-09-36-24
+.. gh-issue: 61448
+.. nonce: SOAkvt
+.. section: Library
+
+Fix :func:`inspect.formatargvalues` raising :exc:`KeyError` for deleted
+arguments, including ``*args`` and ``**kwargs``, by displaying
+````. Patch by Ezio Melotti and Furkan Onder.
+
+..
+
+.. bpo: 19094
+.. date: 2021-06-11-20-00-16
+.. nonce: rMRoIL
+.. section: Library
+
+The :mod:`urllib.parse` URL parsing functions now raise :exc:`TypeError`
+instead of :exc:`AttributeError` when passed an object which is not a
+string, bytes, or ``None``. Accepting objects with false values (like ``0``
+and ``[]``) except empty strings, byte-like objects and ``None`` is now
+deprecated, extending the deprecation made in Python 3.14 for
+:func:`~urllib.parse.parse_qsl` and :func:`~urllib.parse.parse_qs`.
+
+..
+
+.. bpo: 44170
+.. date: 2021-05-24-14-41-29
+.. nonce: _v28mv
+.. section: Library
+
+Fix UnicodeDecodeError with multibyte utf8 characters in ShareableList.
+
+..
+
+.. date: 2025-08-31-02-28-21
+.. gh-issue: 138277
+.. nonce: kkORph
+.. section: Documentation
+
+Rearranged documentation search results to emphasize built-in types and
+functions. Patch by Adam Hartz.
+
+..
+
+.. date: 2023-09-04-16-01-20
+.. gh-issue: 107689
+.. nonce: LFLFtG
+.. section: Documentation
+
+Added docstrings to abstract ctypes.
+
+..
+
+.. date: 2026-11-07-01-45-00
+.. gh-issue: 160334
+.. nonce: F2n8qA
+.. section: Tests
+
+Fix the sampling profiler integration test for special frames without file
+and line information.
+
+..
+
+.. date: 2026-11-06-23-15-23
+.. gh-issue: 161517
+.. nonce: LkAlDt
+.. section: Tests
+
+Fix test_gdb when Python is built out-of-tree and Python is run from a
+virtual environment. Previously, test_gdb was just skipped. Patch by Victor
+Stinner.
+
+..
+
+.. date: 2026-11-05-16-20-23
+.. gh-issue: 161430
+.. nonce: M7b8N6
+.. section: Tests
+
+No longer list tests expected to be skipped in the final report. Patch by
+Victor Stinner.
+
+..
+
+.. date: 2026-11-03-13-12-50
+.. gh-issue: 161263
+.. nonce: Voe8VM
+.. section: Tests
+
+Skip tests which use MD5 algorithm for WWW-Authenticate challenges when
+libssl is in FIPS mode.
+
+..
+
+.. date: 2026-10-28-20-40-00
+.. gh-issue: 158646
+.. nonce: k2Xw7q
+.. section: Tests
+
+Fix a race in ``test_asyncio.test_sslproto`` where the server side of
+``test_shutdown_corrupted_ssl_sends_close_notify`` could fail with a
+connection reset on Windows.
+
+..
+
+.. date: 2026-10-19-17-05-00
+.. gh-issue: 107862
+.. nonce: qH3sTa
+.. section: Tests
+
+Add ``hypothesis.stateful`` and the ``timezones()`` and ``ip_addresses()``
+strategies to the Hypothesis stubs used when Hypothesis is not installed.
+
+..
+
+.. date: 2026-10-13-13-34-00
+.. gh-issue: 159293
+.. nonce: Lr8q2N
+.. section: Tests
+
+Restore the recursion limit after the free-threading recursion-limit race
+test to avoid failures in subsequent tests run in the same process.
+
+..
+
+.. date: 2026-10-07-12-00-58
+.. gh-issue: 158975
+.. nonce: yR8q2L
+.. section: Tests
+
+Replace fixed sleeps used for synchronization in multiprocessing tests with
+bounded waits to avoid failures on slow or overloaded systems. Ensure pool
+cleanup runs even when assertions fail in the imap buffer tests.
+
+..
+
+.. date: 2026-10-05-22-36-06
+.. gh-issue: 158895
+.. nonce: 3Dmc4J
+.. section: Tests
+
+When run in GitHub Actions, :mod:`test.regrtest` now annotates each test
+failure in the job log and writes a summary of the failures to the job
+summary.
+
+..
+
+.. date: 2026-11-06-09-16-30
+.. gh-issue: 161467
+.. nonce: oSuzx_
+.. section: Build
+
+Enable the use of ``__attribute__((hot))`` when building CPython with Clang
+and other compilers that support it.
+
+..
+
+.. date: 2026-11-04-15-00-00
+.. gh-issue: 160924
+.. nonce: WQgVVh
+.. section: Build
+
+Fix cross-compilation failures with ``--enable-shared`` caused by the build
+Python loading the target's ``libpython`` through the shared-library search
+path (such as musl from glibc).
+
+..
+
+.. date: 2026-11-04-14-37-13
+.. gh-issue: 75929
+.. nonce: nELdwE
+.. section: Build
+
+Fix a ``configure`` probe that could omit functions such as
+:func:`os.fchdir` from builds using ``-Wall -Werror``.
+
+..
+
+.. date: 2026-10-26-21-00-00
+.. gh-issue: 160704
+.. nonce: ZRYLKF
+.. section: Build
+
+Fix C11-C17 builds with old C library headers that do not define
+``static_assert``, including glibc versions older than 2.16.
+
+..
+
+.. date: 2026-10-25-15-30-00
+.. gh-issue: 160689
+.. nonce: bootsp
+.. section: Build
+
+The build helper programs ``Programs/_freeze_module`` and
+``_bootstrap_python`` are now linked only with the modules of
+:file:`Modules/Setup.bootstrap`, instead of with every static module.
+Builtin modules added via :file:`Modules/Setup.local` or
+``MODULE_BUILDTYPE=static`` can now depend on frozen modules or on
+``getpath``.
+
+..
+
+.. date: 2026-10-22-18-57-02
+.. gh-issue: 128884
+.. nonce: 3zR5Yp
+.. section: Build
+
+Report a configuration error when ``--enable-bolt`` is used with build flags
+that explicitly request the Cortex-A53 erratum 843419 workaround. Document
+how to disable the workaround for builds that will not run on affected
+processors.
+
+..
+
+.. date: 2026-10-21-18-00-00
+.. gh-issue: 128883
+.. nonce: perf-trampoline
+.. section: Build
+
+Fix crashes with ``-X perf`` and ``-X perf_jit`` in BOLT builds. The ELF
+perf trampoline templates now use read-only data sections.
+
+..
+
+.. date: 2026-10-21-14-52-56
+.. gh-issue: 128884
+.. nonce: Xs5jK-
+.. section: Build
+
+Fix ``--enable-bolt`` build failures on AArch64 with recent LLVM: pass
+``-frame-opt=hot`` only on x86. Patch by Donghee Na.
+
+..
+
+.. date: 2026-10-20-23-30-00
+.. gh-issue: 160004
+.. nonce: CfgPth
+.. section: Build
+
+Fix the paths in the :pep:`739` ``build-details.json`` file generated by
+:file:`Tools/build/generate-build-details.py` with both ``--relative-paths``
+and ``--config-file-path``. Previously, every path except ``base_prefix``
+was wrong and depended on the directory the script was run from.
+
+..
+
+.. date: 2026-10-20-23-00-00
+.. gh-issue: 159998
+.. nonce: FwDyn1
+.. section: Build
+
+Fix ``libpython.dynamic`` in the :pep:`739` ``build-details.json`` file for
+macOS and iOS framework builds. It now points at the framework's library
+instead of a nonexistent path under :file:`lib/`.
+
+..
+
+.. date: 2026-10-20-20-00-00
+.. gh-issue: 144942
+.. nonce: MdLibs
+.. section: Build
+
+Fix the macOS shared library and framework builds not linking the libraries
+required by built-in modules, such as the HACL* objects needed by
+``_blake2`` when it is built in via :file:`Modules/Setup.local`.
+
+..
+
+.. date: 2026-10-20-17-50-00
+.. gh-issue: 143632
+.. nonce: PrCtlM
+.. section: Build
+
+Fix the check that disables ``PR_SET_VMA_ANON_NAME`` on musl libc: it tested
+an unset variable, so it never had any effect and the build could fail with
+a redefinition of ``struct prctl_mm_map``.
+
+..
+
+.. date: 2026-10-20-12-06-22
+.. gh-issue: 131999
+.. nonce: OWoYGM
+.. section: Build
+
+Platform support for Apple's tvOS, watchOS and visionOS was added.
+
+..
+
+.. date: 2026-10-20-00-56-59
+.. gh-issue: 153195
+.. nonce: 35cRE-
+.. section: Build
+
+The PEG parser generator now supports splitting a grammar into several files
+with the ``@include`` meta, and generates a separate C file for the rules of
+each included file. The rules for specialized syntax errors moved from
+:file:`Grammar/python.gram` to :file:`Grammar/invalid.gram`, which generates
+the new :file:`Parser/parser_invalid.c`.
+
+..
+
+.. date: 2026-10-19-17-05-00
+.. gh-issue: 159819
+.. nonce: pyCfgSp
+.. section: Build
+
+Fix the shell version of :program:`python3-config` (used on all POSIX
+platforms except macOS) when the installation prefix contains spaces or
+other characters special to the shell or :program:`sed`: it printed an empty
+``--prefix`` and wrong ``--includes``/``--ldflags`` paths while exiting
+successfully. The script now also exits with status 1 if it cannot determine
+its installation prefix.
+
+..
+
+.. date: 2026-10-19-13-49-39
+.. gh-issue: 54767
+.. nonce: IdrGm6
+.. section: Build
+
+The ``--enable-loadable-sqlite-extensions=no`` and
+``--disable-loadable-sqlite-extensions`` configure options now disable
+loadable SQLite extensions instead of enabling them.
+
+..
+
+.. date: 2026-10-18-12-00-00
+.. gh-issue: 159759
+.. nonce: LibStA
+.. section: Build
+
+Fix the ``libpython.static`` path in :pep:`739` ``build-details.json``,
+which pointed to a file that is not installed when building with
+:option:`--enable-shared`, and no longer list a static library for framework
+builds, which do not install one.
+
+..
+
+.. date: 2026-10-15-19-09-31
+.. gh-issue: 75382
+.. nonce: DSrcra
+.. section: Build
+
+Make :program:`configure` fail early with a clear error when a
+``--with-*-sanitizer`` option is used but a program cannot be linked with
+the corresponding ``-fsanitize`` flag, for example because the sanitizer
+runtime library is not installed.
+
+..
+
+.. date: 2026-10-15-17-19-41
+.. gh-issue: 159452
+.. nonce: oJ1saO
+.. section: Build
+
+``Tools/build/regen-configure.sh`` no longer leaves root-owned files in the
+source tree.
+
+..
+
+.. date: 2026-10-15-11-20-48
+.. gh-issue: 159440
+.. nonce: uIz6ms
+.. section: Build
+
+The version string reported by ``sys.version`` no longer carries a spurious
+``-dirty`` suffix when CPython is built out-of-tree from a clean git
+checkout: the build stamp now checks the source tree instead of the build
+directory.
+
+..
+
+.. date: 2026-09-22-09-13-06
+.. gh-issue: 157949
+.. nonce: EZ8avp
+.. section: Build
+
+Remove dead build and preprocessor code for SCO UnixWare, OpenUNIX, SCO
+OpenServer and ReliantUNIX.
+
+..
+
+.. date: 2026-09-12-15-33-26
+.. gh-issue: 157354
+.. nonce: 2hw6fe
+.. section: Build
+
+Fix the :samp:`--with-{name}-sanitizer=no` and
+:samp:`--without-{name}-sanitizer` :program:`configure` options enabling the
+sanitizer instead of disabling it.
+
+..
+
+.. date: 2026-09-01-23-32-22
+.. gh-issue: 156780
+.. nonce: Qw3nRt
+.. section: Build
+
+Emscripten ``libpython.a`` can now be linked into a program statically.
+
+..
+
+.. date: 2026-08-27-23-24-29
+.. gh-issue: 155813
+.. nonce: LxRQu9
+.. section: Build
+
+On macOS, :option:`LIBFFI_CFLAGS` and :option:`LIBFFI_LIBS` are no longer
+ignored when the SDK provides ``libffi``, so :mod:`ctypes` can again be
+built against a different ``libffi``. Patch by Advit Arora.
+
+..
+
+.. date: 2026-07-11-01-53-58
+.. gh-issue: 153285
+.. nonce: YmSox4
+.. section: Build
+
+Fix incorrect executable linking on macOS with ``--with-lto`` caused by
+premature expansion of Make's ``$@`` target variable.
+
+..
+
+.. date: 2026-10-22-14-04-17
+.. gh-issue: 160239
+.. nonce: A1b2C3
+.. section: Windows
+
+Remove dead and broken ``_repr_info()`` methods from
+``asyncio.windows_events``; they called ``Future._repr_info()``, which no
+longer exists.
+
+..
+
+.. date: 2026-10-20-21-37-34
+.. gh-issue: 159880
+.. nonce: eKBiLr
+.. section: Windows
+
+Fix a key handle leak in :func:`winreg.CreateKey`,
+:func:`winreg.CreateKeyEx` and :func:`winreg.OpenKey` when the
+``winreg.OpenKey/result`` audit hook fails.
+
+..
+
+.. date: 2026-10-15-18-45-00
+.. gh-issue: 159118
+.. nonce: wmiMTA
+.. section: Windows
+
+Fix a crash (``RPC_NT_INTERNAL_ERROR``) and intermittent window class
+failures in :mod:`!_wmi` under high concurrency and load by initializing COM
+as multi-threaded (MTA) instead of apartment-threaded (STA).
+
+..
+
+.. date: 2026-09-14-16-49-44
+.. gh-issue: 157418
+.. nonce: r2IggA
+.. section: Windows
+
+Correct the third parameter name of ``IocpProactor.recvfrom_into()`` from
+*flags* to *nbytes* to reflect that it specifies the number of bytes to
+receive.
+
+..
+
+.. date: 2026-10-19-19-33-35
+.. gh-issue: 159739
+.. nonce: aaf575
+.. section: macOS
+
+Propagate errors that occur while converting macOS system proxy settings.
+
+..
+
+.. date: 2026-11-04-16-34-48
+.. gh-issue: 161367
+.. nonce: bO5MGy
+.. section: WASI
+
+Add a ``test`` command to :file:`Platforms/WASI` with ``--fast-ci`` and
+``--slow-ci`` to select fast CI or slow Buildbot tests and ``--target`` to
+test the build, gathered distribution, or release archive.
+
+..
+
+.. date: 2026-10-21-15-26-12
+.. gh-issue: 160135
+.. nonce: UP-DlO
+.. section: WASI
+
+Support wasm32-wasip3.
+
+..
+
+.. date: 2026-11-06-17-12-40
+.. gh-issue: 161477
+.. nonce: smXIKC
+.. section: IDLE
+
+Fix ``repr()`` of ``idlelib.redirector.WidgetRedirector`` and
+``idlelib.redirector.OriginalCommand``, which displayed a spurious
+one-element tuple.
+
+..
+
+.. date: 2026-10-16-15-12-36
+.. gh-issue: 159517
+.. nonce: uzRtAd
+.. section: IDLE
+
+Fix the completion list and the call tip grabbing the focus on macOS with
+Tcl/Tk 9.1.
+
+..
+
+.. date: 2026-10-21-11-53-40
+.. gh-issue: 87613
+.. nonce: tmKBlg
+.. section: Tools/Demos
+
+Extend Argument Clinic :ref:`vectorcall` to support :ref:`heap-types` with
+zero argument construction.
+
+..
+
+.. date: 2026-10-20-12-50-00
+.. gh-issue: 114258
+.. nonce: slotNx
+.. section: Tools/Demos
+
+Argument Clinic now supports the ``__next__`` type slot (``tp_iternext``),
+including ``@critical_section``.
+
+..
+
+.. date: 2026-10-14-09-48-26
+.. gh-issue: 159385
+.. nonce: 0aWOA9
+.. section: Tools/Demos
+
+iOS builds can now be configured to generate free-threading or debug output.
+
+..
+
+.. date: 2025-03-25-18-00-00
+.. gh-issue: 131725
+.. nonce: qwfh321
+.. section: Tools/Demos
+
+``Tools/i18n/msgfmt.py`` now writes a hash table to the generated ``.mo``
+file, as GNU :program:`msgfmt` does.
+
+..
+
+.. date: 2026-11-05-16-56-57
+.. gh-issue: 160109
+.. nonce: Fvs4m2
+.. section: C API
+
+Remove the unused ``FVS_MASK`` and ``FVS_HAVE_SPEC`` macros. They were used
+by the ``FORMAT_VALUE`` opcode, which was removed in Python 3.13.
+
+..
+
+.. date: 2026-11-05-10-51-17
+.. gh-issue: 161407
+.. nonce: rVoqaQ
+.. section: C API
+
+Fix a crash at exit when an audit hook was added with
+:c:func:`PySys_AddAuditHook` before :c:func:`Py_Initialize` and the raw
+memory allocator changed during startup, for example with
+``PYTHONMALLOC=mimalloc`` or in the :ref:`Python Development Mode
+`.
+
+..
+
+.. date: 2026-11-03-18-27-42
+.. gh-issue: 160962
+.. nonce: 06816I
+.. section: C API
+
+Fix :c:func:`PyInitConfig_SetStr` when setting an optional string option to
+``NULL``. Previously, the function crashed. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-11-03-01-24-01
+.. gh-issue: 161226
+.. nonce: MPrJKp
+.. section: C API
+
+:c:func:`_PyTuple_Resize` now fails with :exc:`SystemError` if the hash
+value was already computed. Patch by Victor Stinner.
+
+..
+
+.. date: 2026-11-02-15-17-50
+.. gh-issue: 161185
+.. nonce: 4bpyDC
+.. section: C API
+
+Fix a strict aliasing issue in the :c:func:`!memcpy` implementation of
+:c:macro:`Py_SETREF`, :c:macro:`Py_XSETREF` and :c:macro:`Py_CLEAR` macros.
+Patch by Nathan Goldbaum and Victor Stinner.
+
+..
+
+.. date: 2026-11-02-13-15-22
+.. gh-issue: 161172
+.. nonce: U6kpuN
+.. section: C API
+
+Add the :ref:`PyUnicodeWriter API ` to the limited C API.
+Patch by Victor Stinner.
+
+..
+
+.. date: 2026-10-21-19-55-00
+.. gh-issue: 159739
+.. nonce: ctxt01
+.. section: C API
+
+Avoid a crash if a context watcher is cleared while other context watchers
+are being notified.
+
+..
+
+.. date: 2026-10-19-21-05-12
+.. gh-issue: 159739
+.. nonce: Rk3fTq
+.. section: C API
+
+Fix a crash in :c:func:`_PyTuple_Resize` when resizing a non-empty tuple to
+a negative or too large size. It now raises :exc:`SystemError` or
+:exc:`MemoryError` respectively.
+
+..
+
+.. date: 2026-10-19-20-38-17
+.. gh-issue: 159739
+.. nonce: eb9cdc
+.. section: C API
+
+:c:func:`PyInitConfig_SetStr` now releases a previously configured value and
+preserves it if conversion of the replacement fails.
+
+..
+
+.. date: 2026-10-19-19-33-35
+.. gh-issue: 159739
+.. nonce: dee9a0
+.. section: C API
+
+Fix a reference leak when :c:func:`_PyTuple_Resize` fails.
+
+..
+
+.. date: 2026-09-12-18-37-22
+.. gh-issue: 157384
+.. nonce: uFbdle
+.. section: C API
+
+:c:func:`PyImport_CreateModuleFromInitfunc` now accepts non-ASCII module
+names for multi-phase init modules, instead of raising
+:exc:`UnicodeEncodeError`.
+
+..
+
+.. date: 2026-08-20-12-00-00
+.. gh-issue: 156133
+.. nonce: GetLoc
+.. section: C API
+
+Add :c:func:`PyUnstable_InterpreterFrame_GetLocal` to read a local variable
+of an internal interpreter frame by its localsplus index, and
+:c:func:`PyUnstable_Code_GetLocalPlusNames` to get the matching variable
+names.
+
+..
+
+.. date: 2026-07-09-13-52-17
+.. gh-issue: 153410
+.. nonce: neaDgY
+.. section: C API
+
+Add :c:func:`PyDict_AsFrozenDictAndClear` C-API function to create
+:class:`frozendict` from existing :class:`dict` object and clear the input
+dict instance.
diff --git a/Misc/NEWS.d/next/Android/README.rst b/Misc/NEWS.d/next/Android/README.rst
new file mode 100644
index 000000000000000..719c2aa8ce916e6
--- /dev/null
+++ b/Misc/NEWS.d/next/Android/README.rst
@@ -0,0 +1 @@
+Put news entry ``blurb`` files for the *Android* section in this directory.
diff --git a/Misc/NEWS.d/next/Build/2025-05-13-12-38-26.gh-issue-115119.7n0nx3.rst b/Misc/NEWS.d/next/Build/2025-05-13-12-38-26.gh-issue-115119.7n0nx3.rst
deleted file mode 100644
index 0c6804ebf9c890d..000000000000000
--- a/Misc/NEWS.d/next/Build/2025-05-13-12-38-26.gh-issue-115119.7n0nx3.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Removed bundled copy of the libmpdec, use system library if it's available.
-Patch by Sergey B Kirpichev.
diff --git a/Misc/NEWS.d/next/Build/2026-04-21-17-27-52.gh-issue-148832.Kx9aQ1.rst b/Misc/NEWS.d/next/Build/2026-04-21-17-27-52.gh-issue-148832.Kx9aQ1.rst
deleted file mode 100644
index 867cfcc5ab62ca2..000000000000000
--- a/Misc/NEWS.d/next/Build/2026-04-21-17-27-52.gh-issue-148832.Kx9aQ1.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Fix :option:`--enable-bolt` build by switching the default BOLT flag from
-``-icf=1`` to ``-icf=0``. ``-icf=1`` folds address-taken functions and
-breaks type-slot dispatch, crashing on :mod:`list` and :mod:`tuple`
-concatenation. Patched by Shamil Abdulaev.
diff --git a/Misc/NEWS.d/next/Build/2026-05-18-16-00-41.gh-issue-148260.UwFiIX.rst b/Misc/NEWS.d/next/Build/2026-05-18-16-00-41.gh-issue-148260.UwFiIX.rst
deleted file mode 100644
index 8248c24cbd511ac..000000000000000
--- a/Misc/NEWS.d/next/Build/2026-05-18-16-00-41.gh-issue-148260.UwFiIX.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-On Linux when Python is linked to the musl C library, use a thread stack
-size of at least 1 MiB instead of musl default which is 128 kiB. Patch by
-Victor Stinner.
diff --git a/Misc/NEWS.d/next/Build/2026-05-19-12-45-23.gh-issue-131372.oJykeB.rst b/Misc/NEWS.d/next/Build/2026-05-19-12-45-23.gh-issue-131372.oJykeB.rst
deleted file mode 100644
index 912f4131af27dae..000000000000000
--- a/Misc/NEWS.d/next/Build/2026-05-19-12-45-23.gh-issue-131372.oJykeB.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Add a :option:`--with-build-details-suffix` configure flag to allow Linux
-distributions that co-install multiple versions of Python in the same tree
-to avoid ``build-details.json`` clashes.
diff --git a/Misc/NEWS.d/next/Build/2026-05-21-15-14-59.gh-issue-148294.VtFaW4.rst b/Misc/NEWS.d/next/Build/2026-05-21-15-14-59.gh-issue-148294.VtFaW4.rst
deleted file mode 100644
index 861261dd97269f9..000000000000000
--- a/Misc/NEWS.d/next/Build/2026-05-21-15-14-59.gh-issue-148294.VtFaW4.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Corrected the use of ``AC_PATH_TOOL`` in ``configure.ac`` to allow a C++
-compiler to be found on :envvar:`!PATH`.
diff --git a/Misc/NEWS.d/next/Build/2026-05-27-14-28-36.gh-issue-115119.wotFWh.rst b/Misc/NEWS.d/next/Build/2026-05-27-14-28-36.gh-issue-115119.wotFWh.rst
deleted file mode 100644
index 04fdf3617f0cdef..000000000000000
--- a/Misc/NEWS.d/next/Build/2026-05-27-14-28-36.gh-issue-115119.wotFWh.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fix the detection of libmpdec header when no .pc files are available.
diff --git a/Misc/NEWS.d/next/Build/2026-06-09-11-54-13.gh-issue-151163.vFAtjv.rst b/Misc/NEWS.d/next/Build/2026-06-09-11-54-13.gh-issue-151163.vFAtjv.rst
deleted file mode 100644
index e4f3a044c81c6f5..000000000000000
--- a/Misc/NEWS.d/next/Build/2026-06-09-11-54-13.gh-issue-151163.vFAtjv.rst
+++ /dev/null
@@ -1 +0,0 @@
-Updated Android build to include SQLite version 3.53.2.
diff --git a/Misc/NEWS.d/next/Build/2026-06-26-16-30-00.gh-issue-152240.loongarch.rst b/Misc/NEWS.d/next/Build/2026-06-26-16-30-00.gh-issue-152240.loongarch.rst
deleted file mode 100644
index ce9274a5c108377..000000000000000
--- a/Misc/NEWS.d/next/Build/2026-06-26-16-30-00.gh-issue-152240.loongarch.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix C stack unwinding tests on Linux LoongArch builds by teaching the manual
-frame pointer unwinder to recognize the LoongArch frame layout.
diff --git a/Misc/NEWS.d/next/Build/2026-06-28-16-17-55.gh-issue-152502.6SNqMg.rst b/Misc/NEWS.d/next/Build/2026-06-28-16-17-55.gh-issue-152502.6SNqMg.rst
deleted file mode 100644
index 6c7e62a59a34412..000000000000000
--- a/Misc/NEWS.d/next/Build/2026-06-28-16-17-55.gh-issue-152502.6SNqMg.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-The :mod:`curses` module now detects its optional functions with
-:program:`configure` capability probes instead of assuming ncurses, so it
-builds against narrow (non-wide) ncurses and other curses implementations such
-as NetBSD curses, exposing exactly the functions they provide.
diff --git a/Misc/NEWS.d/next/Build/2026-07-01-17-53-00.gh-issue-152769.Kp7mQ2.rst b/Misc/NEWS.d/next/Build/2026-07-01-17-53-00.gh-issue-152769.Kp7mQ2.rst
deleted file mode 100644
index 04a6ef4f5e0a7f8..000000000000000
--- a/Misc/NEWS.d/next/Build/2026-07-01-17-53-00.gh-issue-152769.Kp7mQ2.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Enable the :ref:`perf profiler ` trampoline on Alpine Linux with the
-musl C library on ``x86_64`` and ``aarch64``. The
-trampoline is architecture-specific and does not depend on the C library, so
-the same assembly trampoline used for glibc is reused for musl.
diff --git a/Misc/NEWS.d/next/Build/2026-07-02-16-25-13.gh-issue-152870.oh9eD1.rst b/Misc/NEWS.d/next/Build/2026-07-02-16-25-13.gh-issue-152870.oh9eD1.rst
deleted file mode 100644
index eaddd22a60fc09b..000000000000000
--- a/Misc/NEWS.d/next/Build/2026-07-02-16-25-13.gh-issue-152870.oh9eD1.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Fix a compilation error in the :mod:`decimal` C extension (``_decimal``) when
-it is built with ``EXTRA_FUNCTIONALITY``. ``Context.apply()`` called the
-internal ``_apply`` helper using its pre-Argument-Clinic signature; the call is
-now made through the generated ``_impl`` function.
diff --git a/Misc/NEWS.d/next/Build/2026-07-09-22-45-00.gh-issue-153438.Qr7N2p.rst b/Misc/NEWS.d/next/Build/2026-07-09-22-45-00.gh-issue-153438.Qr7N2p.rst
deleted file mode 100644
index edab8e6ba7b2595..000000000000000
--- a/Misc/NEWS.d/next/Build/2026-07-09-22-45-00.gh-issue-153438.Qr7N2p.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Update Windows build and installer tooling and documentation to use the
-current download URL for ``nuget.exe``.
diff --git a/Misc/NEWS.d/next/Build/2026-07-11-07-26-16.gh-issue-126877.Zt7Kq2.rst b/Misc/NEWS.d/next/Build/2026-07-11-07-26-16.gh-issue-126877.Zt7Kq2.rst
deleted file mode 100644
index 1d7d4fad886c56f..000000000000000
--- a/Misc/NEWS.d/next/Build/2026-07-11-07-26-16.gh-issue-126877.Zt7Kq2.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix the :program:`configure` check for Tcl/Tk which could wrongly succeed
-with optimizing compilers when the libraries are missing.
diff --git a/Misc/NEWS.d/next/Build/2026-11-06-12-00-00.gh-issue-140266.K3hP9z.rst b/Misc/NEWS.d/next/Build/2026-11-06-12-00-00.gh-issue-140266.K3hP9z.rst
new file mode 100644
index 000000000000000..399aca8a9bcff6c
--- /dev/null
+++ b/Misc/NEWS.d/next/Build/2026-11-06-12-00-00.gh-issue-140266.K3hP9z.rst
@@ -0,0 +1,3 @@
+Fix ``"platform": ""`` in ``build-details.json`` for native builds configured
+with :option:`--with-build-python`: :envvar:`!_PYTHON_HOST_PLATFORM` is now
+only passed to the build interpreter when cross compiling.
diff --git a/Misc/NEWS.d/next/Build/2026-11-06-12-00-01.gh-issue-136267.Qv7mRs.rst b/Misc/NEWS.d/next/Build/2026-11-06-12-00-01.gh-issue-136267.Qv7mRs.rst
new file mode 100644
index 000000000000000..43cc054a04ac7a2
--- /dev/null
+++ b/Misc/NEWS.d/next/Build/2026-11-06-12-00-01.gh-issue-136267.Qv7mRs.rst
@@ -0,0 +1,8 @@
+``build-details.json`` now describes the interpreter being built rather than
+the interpreter running :program:`generate-build-details.py`: ``abi.flags``,
+``suffixes.extensions``, ``abi.stable_abi_suffix`` and
+``implementation.supports_isolated_interpreters`` are derived from the
+target's configuration, which fixes cross builds and builds that use
+:option:`--with-build-python`. ``abi.extension_suffix`` and
+``abi.stable_abi_suffix`` are now also present when libpython is only built
+as a static library.
diff --git a/Misc/NEWS.d/next/Build/2026-11-06-12-00-02.gh-issue-136267.Vt4pLm.rst b/Misc/NEWS.d/next/Build/2026-11-06-12-00-02.gh-issue-136267.Vt4pLm.rst
new file mode 100644
index 000000000000000..d99ae1c42133402
--- /dev/null
+++ b/Misc/NEWS.d/next/Build/2026-11-06-12-00-02.gh-issue-136267.Vt4pLm.rst
@@ -0,0 +1,4 @@
+``build-details.json`` now takes ``language.version_info``,
+``implementation.version`` and ``implementation.hexversion`` from
+:file:`Include/patchlevel.h` instead of the interpreter running the generator,
+which can be a different patch release under :option:`--with-build-python`.
diff --git a/Misc/NEWS.d/next/Build/2026-11-11-11-36-01.gh-issue-161821.9wjElMQP.rst b/Misc/NEWS.d/next/Build/2026-11-11-11-36-01.gh-issue-161821.9wjElMQP.rst
new file mode 100644
index 000000000000000..2cfece1209c6e94
--- /dev/null
+++ b/Misc/NEWS.d/next/Build/2026-11-11-11-36-01.gh-issue-161821.9wjElMQP.rst
@@ -0,0 +1,4 @@
+When building with ``--with-lto`` and Clang, :program:`configure` now checks
+that the linker can link LTO objects and falls back to ``lld``
+(``-fuse-ld=lld``) if it cannot. This fixes LTO builds on systems where the
+default GNU linker lacks the ``LLVMgold.so`` plugin, such as Debian 13.
diff --git a/Misc/NEWS.d/next/Build/2026-11-17-20-12-03.gh-issue-162170.0SpcRZ.rst b/Misc/NEWS.d/next/Build/2026-11-17-20-12-03.gh-issue-162170.0SpcRZ.rst
new file mode 100644
index 000000000000000..caa4b13ce303395
--- /dev/null
+++ b/Misc/NEWS.d/next/Build/2026-11-17-20-12-03.gh-issue-162170.0SpcRZ.rst
@@ -0,0 +1,3 @@
+``make install`` now depends on the ``all`` target, so running it directly
+after ``./configure --enable-optimizations`` installs the PGO-optimized
+interpreter rather than an unoptimized build.
diff --git a/Misc/NEWS.d/next/Build/2026-11-19-17-34-03.gh-issue-153668.A7mK2q.rst b/Misc/NEWS.d/next/Build/2026-11-19-17-34-03.gh-issue-153668.A7mK2q.rst
new file mode 100644
index 000000000000000..95de6504bdbd074
--- /dev/null
+++ b/Misc/NEWS.d/next/Build/2026-11-19-17-34-03.gh-issue-153668.A7mK2q.rst
@@ -0,0 +1,2 @@
+Disable ``unicodectype.c`` optimization in regular Windows ARM64 Release
+builds due to a compiler bug in MSVC 14.50, 14.51, and 14.52. PGO builds are not affected.
diff --git a/Misc/NEWS.d/next/Build/2026-11-20-16-30-00.gh-issue-162308.Mk7pQ2.rst b/Misc/NEWS.d/next/Build/2026-11-20-16-30-00.gh-issue-162308.Mk7pQ2.rst
new file mode 100644
index 000000000000000..90a734551591f83
--- /dev/null
+++ b/Misc/NEWS.d/next/Build/2026-11-20-16-30-00.gh-issue-162308.Mk7pQ2.rst
@@ -0,0 +1,4 @@
+Use the newly built interpreter to check extension modules in native builds
+configured with :option:`--with-build-python`. This also applies when
+generating missing standard library module information. Cross builds continue
+to use the build interpreter without importing target extension modules.
diff --git a/Misc/NEWS.d/next/Build/README.rst b/Misc/NEWS.d/next/Build/README.rst
index d43e989e18051aa..0d2d2c1fc38be93 100644
--- a/Misc/NEWS.d/next/Build/README.rst
+++ b/Misc/NEWS.d/next/Build/README.rst
@@ -1,3 +1 @@
-Put news entry `blurb`_ files for the *Build* section in this directory.
-
-.. _blurb: https://pypi.org/project/blurb/
+Put news entry ``blurb`` files for the *Build* section in this directory.
diff --git a/Misc/NEWS.d/next/C_API/2026-02-25-13-37-10.gh-issue-145235.-1ySNR.rst b/Misc/NEWS.d/next/C_API/2026-02-25-13-37-10.gh-issue-145235.-1ySNR.rst
deleted file mode 100644
index 98a8c2687357265..000000000000000
--- a/Misc/NEWS.d/next/C_API/2026-02-25-13-37-10.gh-issue-145235.-1ySNR.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Made :c:func:`PyDict_AddWatcher`, :c:func:`PyDict_ClearWatcher`,
-:c:func:`PyDict_Watch`, and :c:func:`PyDict_Unwatch` thread-safe on the
-:term:`free threaded ` build.
diff --git a/Misc/NEWS.d/next/C_API/2026-05-12-16-47-21.gh-issue-149725.HZLBTZ.rst b/Misc/NEWS.d/next/C_API/2026-05-12-16-47-21.gh-issue-149725.HZLBTZ.rst
deleted file mode 100644
index 97721430edbd69d..000000000000000
--- a/Misc/NEWS.d/next/C_API/2026-05-12-16-47-21.gh-issue-149725.HZLBTZ.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Add :c:func:`PySentinel_CheckExact` for exact :class:`sentinel` type tests
-to accompany the existing :c:func:`PySentinel_Check`.
diff --git a/Misc/NEWS.d/next/C_API/2026-05-31-15-39-58.gh-issue-150671.bTkDVC.rst b/Misc/NEWS.d/next/C_API/2026-05-31-15-39-58.gh-issue-150671.bTkDVC.rst
deleted file mode 100644
index a67a0f85db1a506..000000000000000
--- a/Misc/NEWS.d/next/C_API/2026-05-31-15-39-58.gh-issue-150671.bTkDVC.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Deprecate these C-API functions: :c:func:`PyGen_New`,
-:c:func:`PyGen_NewWithQualName`, :c:func:`PyCoro_New`, and
-:c:func:`PyAsyncGen_New`.
-Schedule them for removal in 3.18
diff --git a/Misc/NEWS.d/next/C_API/2026-06-04-14-26-17.gh-issue-150907.CA91_B.rst b/Misc/NEWS.d/next/C_API/2026-06-04-14-26-17.gh-issue-150907.CA91_B.rst
deleted file mode 100644
index f58b248f3a0b986..000000000000000
--- a/Misc/NEWS.d/next/C_API/2026-06-04-14-26-17.gh-issue-150907.CA91_B.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix ``dynamic_annotations.h`` header file when built with C++ and Valgrind:
-add ``extern "C++" scope`` for the C++ template. Patch by Victor Stinner.
diff --git a/Misc/NEWS.d/next/C_API/2026-06-09-14-50-35.gh-issue-80384.UEGyvB.rst b/Misc/NEWS.d/next/C_API/2026-06-09-14-50-35.gh-issue-80384.UEGyvB.rst
deleted file mode 100644
index c4f5e8f3f9bbc2d..000000000000000
--- a/Misc/NEWS.d/next/C_API/2026-06-09-14-50-35.gh-issue-80384.UEGyvB.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-:c:func:`PyWeakref_NewRef` and :c:func:`PyWeakref_NewProxy` now raise
-:exc:`TypeError` if the *callback* argument is not callable, ``None``, or
-``NULL``.
diff --git a/Misc/NEWS.d/next/C_API/2026-06-10-15-22-44.gh-issue-149044.O7KEcs.rst b/Misc/NEWS.d/next/C_API/2026-06-10-15-22-44.gh-issue-149044.O7KEcs.rst
deleted file mode 100644
index fe0730b1bf87c4d..000000000000000
--- a/Misc/NEWS.d/next/C_API/2026-06-10-15-22-44.gh-issue-149044.O7KEcs.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Improved error message when specifying non-type base classes in
-:c:macro:`Py_tp_bases`, :c:macro:`Py_tp_base`, and *bases* argument to
-:c:func:`PyType_FromMetaclass` and other ``PyType_From*`` functions.
diff --git a/Misc/NEWS.d/next/C_API/2026-06-10-16-43-37.gh-issue-123619.dV82r6.rst b/Misc/NEWS.d/next/C_API/2026-06-10-16-43-37.gh-issue-123619.dV82r6.rst
deleted file mode 100644
index 4d4c94563330c06..000000000000000
--- a/Misc/NEWS.d/next/C_API/2026-06-10-16-43-37.gh-issue-123619.dV82r6.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-:c:func:`PyUnstable_Object_EnableDeferredRefcount` now returns ``0`` if the
-object is not tracked by the garbage collector: if :func:`gc.is_tracked` is
-false. Patch by Victor Stinner.
diff --git a/Misc/NEWS.d/next/C_API/2026-06-18-18-24-11.gh-issue-141510.-EOHJ1.rst b/Misc/NEWS.d/next/C_API/2026-06-18-18-24-11.gh-issue-141510.-EOHJ1.rst
deleted file mode 100644
index c77b462e97bdd1d..000000000000000
--- a/Misc/NEWS.d/next/C_API/2026-06-18-18-24-11.gh-issue-141510.-EOHJ1.rst
+++ /dev/null
@@ -1 +0,0 @@
-Add :class:`frozendict` to the fast paths of :c:func:`PyMapping_GetOptionalItem`, :c:func:`PyMapping_Keys`, :c:func:`PyMapping_Values`, and :c:func:`PyMapping_Items`.
diff --git a/Misc/NEWS.d/next/C_API/2026-07-08-00-38-32.gh-issue-153300.lVoWyR.rst b/Misc/NEWS.d/next/C_API/2026-07-08-00-38-32.gh-issue-153300.lVoWyR.rst
deleted file mode 100644
index 3c19c0e15d2bc65..000000000000000
--- a/Misc/NEWS.d/next/C_API/2026-07-08-00-38-32.gh-issue-153300.lVoWyR.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-:c:func:`PyConfig_Set()` now also set global configuration variables. For
-example, ``PyConfig_Set("inspect", value)`` now also sets
-:c:var:`Py_InspectFlag`. Patch by Victor Stinner.
diff --git a/Misc/NEWS.d/next/C_API/2026-07-09-16-46-30.gh-issue-145633.jyNwAs.rst b/Misc/NEWS.d/next/C_API/2026-07-09-16-46-30.gh-issue-145633.jyNwAs.rst
deleted file mode 100644
index cdb68372b6ba7d9..000000000000000
--- a/Misc/NEWS.d/next/C_API/2026-07-09-16-46-30.gh-issue-145633.jyNwAs.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-:c:func:`PyFloat_Pack8` and ``PyFloat_Unpack*`` functions are no longer
-guaranteed to always succeed on CPython.
diff --git a/Misc/NEWS.d/next/C_API/2026-07-09-17-33-29.gh-issue-152132.Ma8MJZ.rst b/Misc/NEWS.d/next/C_API/2026-07-09-17-33-29.gh-issue-152132.Ma8MJZ.rst
deleted file mode 100644
index 633c41e40bf2696..000000000000000
--- a/Misc/NEWS.d/next/C_API/2026-07-09-17-33-29.gh-issue-152132.Ma8MJZ.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix :c:func:`Py_RunMain` to return an exit code, rather than calling
-:c:func:`Py_Exit`, when running a script, a command, or the REPL. Patch by
-Victor Stinner.
diff --git a/Misc/NEWS.d/next/C_API/2026-07-24-22-30-40.gh-issue-154643.z-ZutK.rst b/Misc/NEWS.d/next/C_API/2026-07-24-22-30-40.gh-issue-154643.z-ZutK.rst
new file mode 100644
index 000000000000000..17c2a58555e7ae9
--- /dev/null
+++ b/Misc/NEWS.d/next/C_API/2026-07-24-22-30-40.gh-issue-154643.z-ZutK.rst
@@ -0,0 +1,2 @@
+In ``pyport.h`` and ``pyatomic.h`` don't use ``_Py_STDC_VERSION`` when it is
+not defined, fixing build errors for C or C++ code built with ``-Werror=undef``.
diff --git a/Misc/NEWS.d/next/C_API/2026-11-04-14-24-36.gh-issue-160436.WmZEYT.rst b/Misc/NEWS.d/next/C_API/2026-11-04-14-24-36.gh-issue-160436.WmZEYT.rst
new file mode 100644
index 000000000000000..4cef63faaa4cdf2
--- /dev/null
+++ b/Misc/NEWS.d/next/C_API/2026-11-04-14-24-36.gh-issue-160436.WmZEYT.rst
@@ -0,0 +1,4 @@
+Fix a spurious ``-Wdeprecated-declarations`` warning when a
+:c:type:`PyStatus` is copied in C++ with clang 21 and older:
+:c:member:`PyStatus.exitcode` is no longer marked as deprecated for C++ on
+those compilers.
diff --git a/Misc/NEWS.d/next/C_API/2026-11-12-21-34-55.gh-issue-161694.71tZlp.rst b/Misc/NEWS.d/next/C_API/2026-11-12-21-34-55.gh-issue-161694.71tZlp.rst
new file mode 100644
index 000000000000000..e82a0a267cfe499
--- /dev/null
+++ b/Misc/NEWS.d/next/C_API/2026-11-12-21-34-55.gh-issue-161694.71tZlp.rst
@@ -0,0 +1,2 @@
+:c:func:`!_PyObject_VAR_SIZE` now returns ``SIZE_MAX`` on integer overflow (if
+the result would be greater than ``PY_SSIZE_T_MAX``). Patch by Victor Stinner.
diff --git a/Misc/NEWS.d/next/C_API/2026-11-16-17-25-12.gh-issue-158401.ADBBRG.rst b/Misc/NEWS.d/next/C_API/2026-11-16-17-25-12.gh-issue-158401.ADBBRG.rst
new file mode 100644
index 000000000000000..f1b59a75095b2a0
--- /dev/null
+++ b/Misc/NEWS.d/next/C_API/2026-11-16-17-25-12.gh-issue-158401.ADBBRG.rst
@@ -0,0 +1,4 @@
+:c:func:`Py_INCREF`, :c:func:`Py_XINCREF`, :c:func:`Py_DECREF` and
+:c:func:`Py_XDECREF` are now implemented as function calls on all limited C
+API versions. Previously, they were only implemented as function calls on
+the limited C API version 3.12 or newer. Patch by Victor Stinner:
diff --git a/Misc/NEWS.d/next/C_API/README.rst b/Misc/NEWS.d/next/C_API/README.rst
index a4eb261579f2097..5a04f76f47b67eb 100644
--- a/Misc/NEWS.d/next/C_API/README.rst
+++ b/Misc/NEWS.d/next/C_API/README.rst
@@ -1,3 +1 @@
-Put news entry `blurb`_ files for the *C API* section in this directory.
-
-.. _blurb: https://pypi.org/project/blurb/
+Put news entry ``blurb`` files for the *C API* section in this directory.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2019-12-27-19-20-33.bpo-38131.J5fv54.rst b/Misc/NEWS.d/next/Core_and_Builtins/2019-12-27-19-20-33.bpo-38131.J5fv54.rst
deleted file mode 100644
index 8b606c4335e033a..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2019-12-27-19-20-33.bpo-38131.J5fv54.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Produce more meaningful messages when compiling AST objects with wrong field
-values. Patch by Batuhan Taskaya.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2023-01-02-14-54-12.gh-issue-100687.yenIag.rst b/Misc/NEWS.d/next/Core_and_Builtins/2023-01-02-14-54-12.gh-issue-100687.yenIag.rst
new file mode 100644
index 000000000000000..f4f63584b1659ea
--- /dev/null
+++ b/Misc/NEWS.d/next/Core_and_Builtins/2023-01-02-14-54-12.gh-issue-100687.yenIag.rst
@@ -0,0 +1,2 @@
+Reduce the memory used by the result of adding two large :class:`int`
+values. Such additions are also slightly faster for most sizes.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-03-16-02-23-48.gh-issue-145854.rRexF3.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-03-16-02-23-48.gh-issue-145854.rRexF3.rst
deleted file mode 100644
index a4944615369edf5..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-03-16-02-23-48.gh-issue-145854.rRexF3.rst
+++ /dev/null
@@ -1 +0,0 @@
-The ``DELETE_NAME`` opcode is now replaced with ``PUSH_NULL; STORE_NAME``.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-03-20-16-27-15.gh-issue-145855.3yaHO4.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-03-20-16-27-15.gh-issue-145855.3yaHO4.rst
deleted file mode 100644
index e34e51601fe5994..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-03-20-16-27-15.gh-issue-145855.3yaHO4.rst
+++ /dev/null
@@ -1 +0,0 @@
-The ``DELETE_ATTR`` opcode is now replaced with ``PUSH_NULL; STORE_ATTR``.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-03-23-00-45-44.gh-issue-145857.dB66WV.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-03-23-00-45-44.gh-issue-145857.dB66WV.rst
deleted file mode 100644
index 8fd4f078817d404..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-03-23-00-45-44.gh-issue-145857.dB66WV.rst
+++ /dev/null
@@ -1 +0,0 @@
-The ``DELETE_GLOBAL`` opcode is now replaced with ``PUSH_NULL; STORE_GLOBAL``.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-03-31-16-15-15.gh-issue-75723.BZ4Rsn.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-03-31-16-15-15.gh-issue-75723.BZ4Rsn.rst
deleted file mode 100644
index 596ca89958c9ed4..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-03-31-16-15-15.gh-issue-75723.BZ4Rsn.rst
+++ /dev/null
@@ -1 +0,0 @@
-Avoid re-executing ``.pth`` files when :func:`site.addsitedir` is called for a known directory.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-04-15-15-48-04.gh-issue-148450.2MEVqH.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-04-15-15-48-04.gh-issue-148450.2MEVqH.rst
deleted file mode 100644
index 2a7d0d9bb3a7f7e..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-04-15-15-48-04.gh-issue-148450.2MEVqH.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fix ``abc.register()`` so it invalidates type version tags for registered classes.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-04-21-15-07-03.gh-issue-148825.AbJzmZ.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-04-21-15-07-03.gh-issue-148825.AbJzmZ.rst
deleted file mode 100644
index 5cf727b5d91fad1..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-04-21-15-07-03.gh-issue-148825.AbJzmZ.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fix build error if specialization is disabled.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-04-29-15-10-59.gh-issue-149162.BPPyrq.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-04-29-15-10-59.gh-issue-149162.BPPyrq.rst
deleted file mode 100644
index b4c443ecee07adf..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-04-29-15-10-59.gh-issue-149162.BPPyrq.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix a potential deadlock in :c:func:`PyUnicode_InternFromString` and other
-interning functions in the :term:`free-threaded build` when called from C++
-static local initializers.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-05-12-00-00.gh-issue-149321.remove-lazy-imports-none.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-05-12-00-00.gh-issue-149321.remove-lazy-imports-none.rst
deleted file mode 100644
index 44e96ce7be0bfb4..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-05-12-00-00.gh-issue-149321.remove-lazy-imports-none.rst
+++ /dev/null
@@ -1 +0,0 @@
-Do not support ``none`` as a lazy imports mode.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-07-03-18-59.gh-issue-149459.5fhAqP.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-07-03-18-59.gh-issue-149459.5fhAqP.rst
deleted file mode 100644
index 4cd0a148df3c704..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-07-03-18-59.gh-issue-149459.5fhAqP.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fix a crash in the JIT optimizer when a specialized ``LOAD_SPECIAL`` guard deoptimized after inserting the synthetic ``NULL`` stack entry.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-09-15-22-32.gh-issue-144957.u1F2aQ.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-09-15-22-32.gh-issue-144957.u1F2aQ.rst
deleted file mode 100644
index 3063f1a3c0e6d3e..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-09-15-22-32.gh-issue-144957.u1F2aQ.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix lazy ``from`` imports of module attributes provided by module-level
-``__getattr__``.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-10-07-42-36.gh-issue-149642.6ZksML.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-10-07-42-36.gh-issue-149642.6ZksML.rst
deleted file mode 100644
index 815a084db69d8d8..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-10-07-42-36.gh-issue-149642.6ZksML.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Allow imports inside ``exec()`` calls within functions under
-``PYTHON_LAZY_IMPORTS=all``.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-10-16-43-50.gh-issue-148829.gscS14.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-10-16-43-50.gh-issue-148829.gscS14.rst
deleted file mode 100644
index 3f9b1ccb518787d..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-10-16-43-50.gh-issue-148829.gscS14.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-:class:`sentinel` objects now support a ``repr=`` argument and their
-:attr:`~sentinel.__module__` attribute is writable.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-11-14-48-56.gh-issue-149676.6aTrw1.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-11-14-48-56.gh-issue-149676.6aTrw1.rst
deleted file mode 100644
index 96f407cf5ad25a1..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-11-14-48-56.gh-issue-149676.6aTrw1.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fix ``frozendict | frozendict`` hash.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-11-15-58-23.gh-issue-149689.9Ht49z.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-11-15-58-23.gh-issue-149689.9Ht49z.rst
deleted file mode 100644
index aa672760730bd43..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-11-15-58-23.gh-issue-149689.9Ht49z.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix missing error propagation in parser action helpers when memory allocation
-fails. Patch by Thomas Kowalski.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-11-18-20-41.gh-issue-148871.AeCbq7.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-11-18-20-41.gh-issue-148871.AeCbq7.rst
deleted file mode 100644
index 506e369f553e506..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-11-18-20-41.gh-issue-148871.AeCbq7.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-The empty tuple ``()`` is now loaded via :opcode:`LOAD_COMMON_CONSTANT`
-instead of :opcode:`LOAD_CONST`, removing it from per-code-object
-:attr:`~codeobject.co_consts` tuples.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-12-12-49-30.gh-issue-127727.hNmj9G.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-12-12-49-30.gh-issue-127727.hNmj9G.rst
deleted file mode 100644
index 474ae434f6885ea..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-12-12-49-30.gh-issue-127727.hNmj9G.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Warn when running a virtual environment created for a different minor Python
-version than the current interpreter, and suggest using ``python -m venv
---upgrade``.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-12-16-47-23.gh-issue-139808.iIs7_E.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-12-16-47-23.gh-issue-139808.iIs7_E.rst
deleted file mode 100644
index 3e9d930bf1de894..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-12-16-47-23.gh-issue-139808.iIs7_E.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Add branch protections for AArch64 (BTI/PAC) in assembly code used by
-:option:`-X perf_jit <-X>` (Linux perf profiler integration).
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-13-06-54-41.gh-issue-149738.4BLFoH.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-13-06-54-41.gh-issue-149738.4BLFoH.rst
deleted file mode 100644
index e62b681d716650b..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-13-06-54-41.gh-issue-149738.4BLFoH.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-:mod:`sqlite3`: Disallow removing ``row_factory`` and ``text_factory`` attributes
-of a connection to prevent a crash on a query.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-13-21-26-26.gh-issue-149805.IG6cza.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-13-21-26-26.gh-issue-149805.IG6cza.rst
deleted file mode 100644
index 02d050840ee1f9b..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-13-21-26-26.gh-issue-149805.IG6cza.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix a :exc:`SystemError` when compiling a compiling ``__classdict__`` class
-annotation. Found by OSS-Fuzz in :oss-fuzz:`512907042`.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-14-19-41-03.gh-issue-149807.IwGaCo.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-14-19-41-03.gh-issue-149807.IwGaCo.rst
deleted file mode 100644
index a94c737e73619d8..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-14-19-41-03.gh-issue-149807.IwGaCo.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix ``hash(frozendict)``: compute the hash of each ``(key, value)`` pair
-correctly. Patch by Victor Stinner.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-15-11-31-57.gh-issue-149816.ugN2rx.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-15-11-31-57.gh-issue-149816.ugN2rx.rst
deleted file mode 100644
index 016c17dd66b19ea..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-15-11-31-57.gh-issue-149816.ugN2rx.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fix a race condition in :class:`memoryview` with free-threading.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-16-11-03-54.gh-issue-149816.X_gqMT.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-16-11-03-54.gh-issue-149816.X_gqMT.rst
deleted file mode 100644
index d35f0857a1aefe8..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-16-11-03-54.gh-issue-149816.X_gqMT.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fix a race condition in ``_PyBytes_FromList`` in free-threading mode.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-17-12-00-00.gh-issue-138325.h2XSfe.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-17-12-00-00.gh-issue-138325.h2XSfe.rst
deleted file mode 100644
index 0eb528c68d8d6f0..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-17-12-00-00.gh-issue-138325.h2XSfe.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Speed up converting a list to a tuple in the ``tuple(genexpr)`` fast path
-and in starred tuple displays (e.g. ``(*a, *b)``) by stealing the list's
-items into the tuple instead of copying them.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-18-13-47-17.gh-issue-149590.IPBeQx.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-18-13-47-17.gh-issue-149590.IPBeQx.rst
deleted file mode 100644
index 8d3b29d69cc8578..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-18-13-47-17.gh-issue-149590.IPBeQx.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fix crash when faulthandler is imported more than once.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-18-16-54-54.gh-issue-150042.LSr5W8.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-18-16-54-54.gh-issue-150042.LSr5W8.rst
deleted file mode 100644
index 18a4fbd9dadd60f..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-18-16-54-54.gh-issue-150042.LSr5W8.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fix refleak in queue.SimpleQueue.put if memory allocation fails.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-18-17-16-51.gh-issue-150027.sJgLvd.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-18-17-16-51.gh-issue-150027.sJgLvd.rst
deleted file mode 100644
index 66446105da3fba2..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-18-17-16-51.gh-issue-150027.sJgLvd.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Improve performance of :class:`frozenset` objects by avoiding copies during
-construction.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-18-18-36-28.gh-issue-148587.-RD3z5.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-18-18-36-28.gh-issue-148587.-RD3z5.rst
deleted file mode 100644
index d623dbdd75f0c8e..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-18-18-36-28.gh-issue-148587.-RD3z5.rst
+++ /dev/null
@@ -1 +0,0 @@
-:py:attr:`sys.lazy_modules` is now a set instead of a dict as initially spelled out in PEP 810.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-20-13-06-17.gh-issue-150146.i5m_SL.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-20-13-06-17.gh-issue-150146.i5m_SL.rst
deleted file mode 100644
index f373f0bee7023ef..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-20-13-06-17.gh-issue-150146.i5m_SL.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-Fix a crash on a complex type variable substitution.
-
-``from typing import TypeVar; memoryview[TypeVar("")][*typing.Mapping[...,
-...]]`` used to fail due to missing ``NULL`` check on ``_unpack_args`` C
-function call.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-21-21-04-43.gh-issue-150208.VOkxRG.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-21-21-04-43.gh-issue-150208.VOkxRG.rst
deleted file mode 100644
index e9bc1d9e976523b..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-21-21-04-43.gh-issue-150208.VOkxRG.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Avoid double-quoting string values from ``pyconfig.h`` in ``sysconfigdata``
-variables.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-22-17-09-28.gh-issue-150107.GD72-D.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-22-17-09-28.gh-issue-150107.GD72-D.rst
deleted file mode 100644
index a13f249e48cc021..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-22-17-09-28.gh-issue-150107.GD72-D.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-:mod:`asyncio`: ``sendfile()`` and ``sock_sendfile()`` event loop methods
-now call ``file.seek(offset)`` if *file* has a ``seek()`` method,
-even if *offset* is ``0`` (default value).
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-22-21-52-38.gh-issue-150207.l2BUtI.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-22-21-52-38.gh-issue-150207.l2BUtI.rst
deleted file mode 100644
index 12fbffcd170684c..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-22-21-52-38.gh-issue-150207.l2BUtI.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fix a crash when a memory allocation fails during tokenizer initialization. A proper :exc:`MemoryError` is now raised instead.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-23-22-08-01.gh-issue-149449.2lhQFF.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-23-22-08-01.gh-issue-149449.2lhQFF.rst
deleted file mode 100644
index 7d11442468d2077..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-23-22-08-01.gh-issue-149449.2lhQFF.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix a use-after-free crash when the :mod:`unicodedata` module was removed
-from :data:`sys.modules` and garbage-collected between calls that decode
-``\N{...}`` escapes or use the ``namereplace`` codec error handler.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-24-14-45-00.gh-issue-149156.NP73rB.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-24-14-45-00.gh-issue-149156.NP73rB.rst
deleted file mode 100644
index 2cb091e2b162f6a..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-24-14-45-00.gh-issue-149156.NP73rB.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix an intermittent crash after :func:`os.fork` when perf trampoline
-profiling is enabled and the child returns through trampoline frames
-inherited from the parent process.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-24-22-46-49.gh-issue-148613.PLpmyd.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-24-22-46-49.gh-issue-148613.PLpmyd.rst
deleted file mode 100644
index 71a701bf3eb3551..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-24-22-46-49.gh-issue-148613.PLpmyd.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix a data race in the free-threaded build between :func:`gc.set_threshold`
-and garbage collection scheduling during object allocation.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-25-16-00-22.gh-issue-150374.Emu6d8.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-25-16-00-22.gh-issue-150374.Emu6d8.rst
deleted file mode 100644
index 7189ca186d2b7e0..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-25-16-00-22.gh-issue-150374.Emu6d8.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fix double release of the import lock on lazy import reification errors.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-26-00-06-30.gh-issue-150411.u-d-_5.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-26-00-06-30.gh-issue-150411.u-d-_5.rst
deleted file mode 100644
index 5b19a4fff5ddc73..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-26-00-06-30.gh-issue-150411.u-d-_5.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix a data race in the free-threaded build when :func:`gc.get_count` reads
-the young generation allocation count while another thread updates it.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-29-17-51-11.gh-issue-144774.jPcixe.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-29-17-51-11.gh-issue-144774.jPcixe.rst
deleted file mode 100644
index 3dd117e7d3c3502..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-29-17-51-11.gh-issue-144774.jPcixe.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fix data race in :class:`BaseException` when an exception is copied while being mutated.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-30-20-19-35.gh-issue-150633.XkNul0.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-30-20-19-35.gh-issue-150633.XkNul0.rst
deleted file mode 100644
index c397ad61f086c1b..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-30-20-19-35.gh-issue-150633.XkNul0.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix the frozen importer accepting module names with embedded null bytes, which
-caused it to bypass the :data:`sys.modules` cache and create duplicate module
-objects.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-01-19-00-00.gh-issue-150700.W8CzVR.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-01-19-00-00.gh-issue-150700.W8CzVR.rst
deleted file mode 100644
index e7734034ff5c814..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-01-19-00-00.gh-issue-150700.W8CzVR.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix a :exc:`SystemError` when compiling a class-scope comprehension containing
-a ``lambda`` that references ``__class__``, ``__classdict__``, or
-``__conditional_annotations__``. Patch by Bartosz Sławecki.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-01-19-21-01.gh-issue-150723.Hb3JDG.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-01-19-21-01.gh-issue-150723.Hb3JDG.rst
deleted file mode 100644
index 1920c8cdfce4f4c..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-01-19-21-01.gh-issue-150723.Hb3JDG.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Fix malformed perf jitdump thread ids on macOS. The ``thread_id`` field of the
-``JR_CODE_LOAD`` record was written as a 64-bit value instead of the 32-bit
-value required by the jitdump format, which shifted every following field and
-prevented profilers from resolving Python frames.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-01-19-24-12.gh-issue-150723.WlcL_-.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-01-19-24-12.gh-issue-150723.WlcL_-.rst
deleted file mode 100644
index 78c896b669c2393..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-01-19-24-12.gh-issue-150723.WlcL_-.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Fix perf jitdump timestamps on macOS. Events were stamped using
-``CLOCK_MONOTONIC``, but macOS profilers timestamp their samples with
-``mach_absolute_time()``. The mismatch prevented the JIT code mappings from
-lining up with the samples, so no Python frame could be resolved.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-03-16-27-00.gh-issue-150858.j2dSkD.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-03-16-27-00.gh-issue-150858.j2dSkD.rst
deleted file mode 100644
index dcb932bf320629a..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-03-16-27-00.gh-issue-150858.j2dSkD.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fix a data race while changing ``__qualname__`` of a type concurrently on free-threaded builds.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-03-21-14-28.gh-issue-150459.qpsCEl.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-03-21-14-28.gh-issue-150459.qpsCEl.rst
deleted file mode 100644
index a3e3e38ddcd1f43..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-03-21-14-28.gh-issue-150459.qpsCEl.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix :exc:`SyntaxError` error message for ``from x lazy import y``.
-Raise :exc:`SyntaxWarning` on ``from . lazy import x``
-(with whitespace between the dots and a module named ``lazy``).
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-04-12-53-10.gh-issue-148874.r121cG.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-04-12-53-10.gh-issue-148874.r121cG.rst
deleted file mode 100644
index 95f93338beb9129..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-04-12-53-10.gh-issue-148874.r121cG.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Ignore interrupts immediately after calling the ``__enter__`` method of a
-context menager in a ``with`` statement. This ensures that the ``__exit__``
-method is always called in a ``with`` statement.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-04-15-02-35.gh-issue-146495.wWRRvx.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-04-15-02-35.gh-issue-146495.wWRRvx.rst
deleted file mode 100644
index 1d86bf5307ba99d..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-04-15-02-35.gh-issue-146495.wWRRvx.rst
+++ /dev/null
@@ -1 +0,0 @@
-Improve :exc:`SyntaxError` message for ``&&`` and ``||`` operators, suggesting ``and``/``&`` and ``or``/``|`` respectively.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-05-22-52-41.gh-issue-150988.fDKfMJ.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-05-22-52-41.gh-issue-150988.fDKfMJ.rst
deleted file mode 100644
index 6fb70a1ce2685c8..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-05-22-52-41.gh-issue-150988.fDKfMJ.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix a reference leak in :exc:`OSError` when attributes are set before
-``super().__init__()``.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-06-08-20-00.gh-issue-150942.Jk9pQr.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-06-08-20-00.gh-issue-150942.Jk9pQr.rst
deleted file mode 100644
index 9777b8932271404..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-06-08-20-00.gh-issue-150942.Jk9pQr.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Speed up frame local variable item collection by appending result pairs to the
-output list without an extra reference-count round-trip (using the internal
-reference-stealing list append helper). Patch by Omkar Kabde.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-06-20-15-08.gh-issue-151029.A33CKK.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-06-20-15-08.gh-issue-151029.A33CKK.rst
deleted file mode 100644
index cbfe5952627ad8a..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-06-20-15-08.gh-issue-151029.A33CKK.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-On Linux, fix :func:`sys.remote_exec` unable to find remote writable memory
-when ``libpython`` replaced on disk.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-08-05-31-22.gh-issue-151065._o_31F.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-08-05-31-22.gh-issue-151065._o_31F.rst
deleted file mode 100644
index e46c96ef784cc9e..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-08-05-31-22.gh-issue-151065._o_31F.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fix memory leak when using the :ref:`mimalloc memory allocator `.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-08-13-14-42.gh-issue-150902.-CWZ66.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-08-13-14-42.gh-issue-150902.-CWZ66.rst
deleted file mode 100644
index e3b7cd387b439fe..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-08-13-14-42.gh-issue-150902.-CWZ66.rst
+++ /dev/null
@@ -1 +0,0 @@
-Apply an existing optimization of PyCriticalSection (single mutex) to PyCriticalSection2: avoid acquiring the same locks that the current CS has already acquired.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-09-10-28-30.gh-issue-151126.DKa6Sl.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-09-10-28-30.gh-issue-151126.DKa6Sl.rst
deleted file mode 100644
index 67e2ce4044431f9..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-09-10-28-30.gh-issue-151126.DKa6Sl.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-Fix a crash, when there's no memory left on a device,
-which happened in: code compilation, :mod:`!_interpchannels` module,
-:func:`!_winapi.CreateProcess` function.
-
-Now these places raise proper :exc:`MemoryError` errors.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-09-12-24-35.gh-issue-151112.4RKCkD.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-09-12-24-35.gh-issue-151112.4RKCkD.rst
deleted file mode 100644
index 93ee5c8cf1914b4..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-09-12-24-35.gh-issue-151112.4RKCkD.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fix a crash in the compiler that could occur when running out of memory.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-10-15-19-58.gh-issue-151238.C9Wu4x.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-10-15-19-58.gh-issue-151238.C9Wu4x.rst
deleted file mode 100644
index fe7519fb4878952..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-10-15-19-58.gh-issue-151238.C9Wu4x.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix a crash when compiling a concatenated f-string or t-string if an error
-occurs when processing one of it's parts.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-10-15-42-46.gh-issue-151253.7MMQ8P.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-10-15-42-46.gh-issue-151253.7MMQ8P.rst
deleted file mode 100644
index 56d2f3b2633bb01..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-10-15-42-46.gh-issue-151253.7MMQ8P.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-If ``import encodings`` (first import) fails at Python startup, dump the
-Python path configuration to help users debugging their configuration. Patch
-by Victor Stinner.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-11-16-03-23.gh-issue-151297.NGPkUM.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-11-16-03-23.gh-issue-151297.NGPkUM.rst
deleted file mode 100644
index 288d726e0f1004d..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-11-16-03-23.gh-issue-151297.NGPkUM.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fix an invalid pointer dereference that could occur when calling :c:func:`PyObject_Realloc` with a NULL pointer in :term:`free-threaded builds ` or with :envvar:`PYTHONMALLOC` set to ``mimalloc``.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-12-15-30-25.gh-issue-151218.5M_nv8.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-12-15-30-25.gh-issue-151218.5M_nv8.rst
deleted file mode 100644
index 46539efc373eb0d..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-12-15-30-25.gh-issue-151218.5M_nv8.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-:c:func:`PyConfig_Set` and :func:`sys.set_int_max_str_digits` now replace
-:data:`sys.flags` (create a new object), instead of modifying :data:`sys.flags`
-in-place. Patch by Victor Stinner.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-14-05-05-15.gh-issue-151461.5q0s88.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-14-05-05-15.gh-issue-151461.5q0s88.rst
deleted file mode 100644
index d76a9bc95278bcb..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-14-05-05-15.gh-issue-151461.5q0s88.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix direct execution of files with invalid source encodings to report the
-underlying codec lookup or decoding error instead of the generic
-``SyntaxError: encoding problem`` message. Patch by Bartosz Sławecki.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-16-00-45-42.gh-issue-151510.HJ-kGn.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-16-00-45-42.gh-issue-151510.HJ-kGn.rst
deleted file mode 100644
index cfa5ee8d3839c1b..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-16-00-45-42.gh-issue-151510.HJ-kGn.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix a crash in :func:`!__lazy_import__` when called without an explicit
-``globals`` argument and without a current Python frame.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-16-17-23-37.gh-issue-151546.LhiaZz.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-16-17-23-37.gh-issue-151546.LhiaZz.rst
deleted file mode 100644
index af1c23bd50355f2..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-16-17-23-37.gh-issue-151546.LhiaZz.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix the stack limit check if Python is linked to musl (ex: Alpine Linux).
-Use the stack size set by the linker to compute the stack limits. Patch by
-Victor Stinner.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-17-16-26-45.gh-issue-151126.Yc_6wC.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-17-16-26-45.gh-issue-151126.Yc_6wC.rst
deleted file mode 100644
index 29bb03d2d408598..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-17-16-26-45.gh-issue-151126.Yc_6wC.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Avoid possible crash in ``getpath.c`` where a device has no memory left. Now
-it properly raises a :exc:`MemoryError`. Patch by Ivy Xu.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-17-16-46-07.gh-issue-151126.vhTL0T.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-17-16-46-07.gh-issue-151126.vhTL0T.rst
deleted file mode 100644
index 6f2d230b1dcfc00..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-17-16-46-07.gh-issue-151126.vhTL0T.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Avoid possible crash in ``_winapi.c`` where a device has no memory left. Now
-it properly raises a :exc:`MemoryError`. Patch by Ivy Xu.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-18-00-00-00.gh-issue-151644.5cFffN.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-18-00-00-00.gh-issue-151644.5cFffN.rst
deleted file mode 100644
index ff5058e14b42f15..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-18-00-00-00.gh-issue-151644.5cFffN.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Fix a data race in :func:`sys.setdlopenflags` and :func:`sys.getdlopenflags`
-when called concurrently in the free-threaded build. The underlying
-``_PyImport_GetDLOpenFlags`` and ``_PyImport_SetDLOpenFlags`` functions now
-use atomic load/store operations.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-18-16-00-10.gh-issue-151126.tBqn6I.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-18-16-00-10.gh-issue-151126.tBqn6I.rst
deleted file mode 100644
index d495df43ede932c..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-18-16-00-10.gh-issue-151126.tBqn6I.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix a crash when sharing :class:`memoryview` objects between interpreters
-fails due to running out of memory. It now raises a proper
-:exc:`MemoryError`.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-19-12-00-00.gh-issue-151646.Gc5tAt.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-19-12-00-00.gh-issue-151646.Gc5tAt.rst
deleted file mode 100644
index fde428c8a2839bb..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-19-12-00-00.gh-issue-151646.Gc5tAt.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix a data race in free-threading builds between :func:`gc.get_stats` and a
-concurrent garbage collection cycle. Access to the per-generation statistics
-is now serialized with a mutex so the reader observes a consistent snapshot.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-19-16-40-01.gh-issue-151619.35yyJW.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-19-16-40-01.gh-issue-151619.35yyJW.rst
deleted file mode 100644
index 28ba2038e876fa7..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-19-16-40-01.gh-issue-151619.35yyJW.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix an issue where using non-module global or builtin namespaces (such as
-dictionaries passed to :func:`exec`) could cause cached global loads to
-produce unresolved :ref:`lazy imports `.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-20-00-30-47.gh-issue-151722.RPMPIY.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-20-00-30-47.gh-issue-151722.RPMPIY.rst
deleted file mode 100644
index 57b5dee7458ede5..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-20-00-30-47.gh-issue-151722.RPMPIY.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Defer GC tracking of :class:`frozendict` to end of construction. Patch by
-Donghee Na.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-20-10-01-26.gh-issue-151672.K-w7j0.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-20-10-01-26.gh-issue-151672.K-w7j0.rst
deleted file mode 100644
index 4f4823df0b21015..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-20-10-01-26.gh-issue-151672.K-w7j0.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix an inconsistency where calling ``__lazy_import__`` with a string
-``fromlist`` would return a :class:`types.LazyImportType` that resolves to
-the named member, rather than the module being imported.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-21-12-55-18.gh-issue-151665.82fmzx.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-21-12-55-18.gh-issue-151665.82fmzx.rst
deleted file mode 100644
index d08a1220cbe5efc..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-21-12-55-18.gh-issue-151665.82fmzx.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-:func:`inspect.signature` now works on the lazy evaluators of type aliases
-and type parameters instead of raising :exc:`ValueError`.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-21-16-00-00.gh-issue-151773.mN4kRt.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-21-16-00-00.gh-issue-151773.mN4kRt.rst
deleted file mode 100644
index b4193c5e15ffef8..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-21-16-00-00.gh-issue-151773.mN4kRt.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix a crash in :func:`contextvars.ContextVar.set` when memory allocation
-fails.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-22-02-42-38.gh-issue-151907.6Tol_J.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-22-02-42-38.gh-issue-151907.6Tol_J.rst
deleted file mode 100644
index cca300f6d0e2f42..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-22-02-42-38.gh-issue-151907.6Tol_J.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Avoid creating :class:`list` objects in comprehensions when the comprehension
-is not used as a value.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-22-06-26-34.gh-issue-151905.FOLMYg.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-22-06-26-34.gh-issue-151905.FOLMYg.rst
deleted file mode 100644
index c71122df6b8580f..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-22-06-26-34.gh-issue-151905.FOLMYg.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fix OOM error handling in :c:func:`PyFrame_GetBack` to propagate exceptions instead of masking them as None.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-22-14-48-22.gh-issue-151912.YcxfnU.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-22-14-48-22.gh-issue-151912.YcxfnU.rst
deleted file mode 100644
index 07b73949b438a33..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-22-14-48-22.gh-issue-151912.YcxfnU.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fixed a crash in ``type()`` when selecting a metaclass whose ``tp_new`` slot is ``NULL``. Such metaclasses are now rejected with ``TypeError`` instead of causing a NULL pointer dereference.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-23-12-03-55.gh-issue-151763.K7QfWG.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-23-12-03-55.gh-issue-151763.K7QfWG.rst
deleted file mode 100644
index 64d0146cb091016..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-23-12-03-55.gh-issue-151763.K7QfWG.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix a potential crash in :func:`compile`, :func:`exec`, :func:`eval` and
-:func:`ast.parse` when an allocation fails: the parser or compiler could
-return without setting an exception.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-23-19-50-22.gh-issue-152020.DTKXjR.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-23-19-50-22.gh-issue-152020.DTKXjR.rst
deleted file mode 100644
index 93c716f7a6a1c86..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-23-19-50-22.gh-issue-152020.DTKXjR.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-On the free-threaded build, :func:`asyncio.all_tasks` no longer loses
-eager-started tasks when called from a thread other than the one running the
-event loop.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-23-23-48-54.gh-issue-151763.Eu8pYQ.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-23-23-48-54.gh-issue-151763.Eu8pYQ.rst
deleted file mode 100644
index d4746e992f8779d..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-23-23-48-54.gh-issue-151763.Eu8pYQ.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fixes possible crash on :class:`types.CodeType` deallocation.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-24-13-36-31.gh-issue-151722.lWKfE1.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-24-13-36-31.gh-issue-151722.lWKfE1.rst
deleted file mode 100644
index db50b0058bdbdda..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-24-13-36-31.gh-issue-151722.lWKfE1.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-:meth:`!frozendict.fromkeys` now only tracks the :class:`frozendict` in the
-garbage collector once the dictionary is fully initialized. Patch by Donghee Na
-and Victor Stinner.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-25-21-34-15.gh-issue-152228.a6K14K.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-25-21-34-15.gh-issue-152228.a6K14K.rst
deleted file mode 100644
index 8af7ae0d1739130..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-25-21-34-15.gh-issue-152228.a6K14K.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix an assertion failure when python is built in a debug mode
-that happened in :meth:`str.replace` under a limited memory situation.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-26-05-49-13.gh-issue-152235.YU20T9.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-26-05-49-13.gh-issue-152235.YU20T9.rst
deleted file mode 100644
index 8d386ad458dfff1..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-26-05-49-13.gh-issue-152235.YU20T9.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Defer GC tracking of a :class:`set` or :class:`frozenset` to the end of its
-construction from iterable. Patch by Donghee Na.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-26-11-34-50.gh-issue-152254.yK6TGp.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-26-11-34-50.gh-issue-152254.yK6TGp.rst
new file mode 100644
index 000000000000000..206b88a2affb2b2
--- /dev/null
+++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-26-11-34-50.gh-issue-152254.yK6TGp.rst
@@ -0,0 +1,2 @@
+Fix a crash during the clean up of managed dict objects under a memory
+pressure in :c:func:`PyObject_ClearManagedDict`.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-26-22-03-16.gh-issue-152235.ZKWiWk.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-26-22-03-16.gh-issue-152235.ZKWiWk.rst
deleted file mode 100644
index ff89a2445cb4fe8..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-26-22-03-16.gh-issue-152235.ZKWiWk.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Defer GC tracking of :meth:`set.intersection`, :meth:`set.difference`,
-:meth:`set.symmetric_difference`, :meth:`set.union` and ``set.__sub__``.
-Patch by Donghee Na.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-26-22-38-21.gh-issue-152192.lX2jIM.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-26-22-38-21.gh-issue-152192.lX2jIM.rst
deleted file mode 100644
index 153cbeb317a2452..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-26-22-38-21.gh-issue-152192.lX2jIM.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix a truncated ``oparg`` being passed to JIT trace initialization for a
-``JUMP_BACKWARD`` with an ``EXTENDED_ARG``.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-27-10-05-12.gh-issue-152375.L-ZBk6.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-27-10-05-12.gh-issue-152375.L-ZBk6.rst
deleted file mode 100644
index db6ae3060d8328f..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-27-10-05-12.gh-issue-152375.L-ZBk6.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix undefined behaviour when a :mod:`sys.monitoring` callback raised an
-exception while the program was following a branch or loop.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-28-14-31-03.gh-issue-152492._09Zee.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-28-14-31-03.gh-issue-152492._09Zee.rst
deleted file mode 100644
index 16cb5a205c908a8..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-28-14-31-03.gh-issue-152492._09Zee.rst
+++ /dev/null
@@ -1 +0,0 @@
-:type:`collections.OrderedDict` ``update`` method can now accept :type:`frozendict` as an argument.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-28-14-39-05.gh-issue-152405.-_3YRo.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-28-14-39-05.gh-issue-152405.-_3YRo.rst
deleted file mode 100644
index d7c473ce171d4b7..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-28-14-39-05.gh-issue-152405.-_3YRo.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-Do not expose the internal mapping of :class:`types.MappingProxyType`
-when performing rich-compare operations with non-stdlib types.
-Previously, it was possible to mutate the internal mapping of a proxy there.
-Now we pass not the original :class:`dict` instance, but its copy,
-when dealing with custom types.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-29-23-29-14.gh-issue-152635.O21J0O.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-29-23-29-14.gh-issue-152635.O21J0O.rst
deleted file mode 100644
index dadb25fc7c44771..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-29-23-29-14.gh-issue-152635.O21J0O.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix a crash caused when running out of memory creating a
-:mod:`!_interpchannels` channel. Now a :exc:`MemoryError` is correctly raised.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-30-14-00-00.gh-issue-152682.yId7e5.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-30-14-00-00.gh-issue-152682.yId7e5.rst
deleted file mode 100644
index aba0b594382bcf8..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-30-14-00-00.gh-issue-152682.yId7e5.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix NULL pointer dereference in :func:`compile` when a reserved name (e.g.
-``__classdict__``) is used as a type parameter name and memory allocation
-fails while formatting the error message.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-07-01-12-00-00.gh-issue-102960.fR8kJa.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-07-01-12-00-00.gh-issue-102960.fR8kJa.rst
deleted file mode 100644
index fec1eeb242c1ed6..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-07-01-12-00-00.gh-issue-102960.fR8kJa.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-:ref:`Frame objects ` now support :mod:`weak references
-`. Patch by Łukasz Langa.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-07-06-18-00-00.gh-issue-153171.errloc1.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-07-06-18-00-00.gh-issue-153171.errloc1.rst
deleted file mode 100644
index aa3171b701894d7..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-07-06-18-00-00.gh-issue-153171.errloc1.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Improve syntax error messages for misplaced ``not`` after an operator
-in contexts where a generic "invalid syntax" error was previously reported,
-such as ``1 << 2 + not x`` and ``1 * + not x``.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-07-07-04-16-48.gh-issue-153205.5fE8QZ.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-07-07-04-16-48.gh-issue-153205.5fE8QZ.rst
deleted file mode 100644
index 9ccfbff7ee69778..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-07-07-04-16-48.gh-issue-153205.5fE8QZ.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix a potential :exc:`SystemError` during vector calls when memory allocation fails.
-A :exc:`MemoryError` is now raised instead.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-07-08-13-23-11.gh-issue-153298.wvcXxN.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-07-08-13-23-11.gh-issue-153298.wvcXxN.rst
deleted file mode 100644
index 38d548834d5e02e..000000000000000
--- a/Misc/NEWS.d/next/Core_and_Builtins/2026-07-08-13-23-11.gh-issue-153298.wvcXxN.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fixes a data race in :class:`types.GenericAlias` ``__parameters__``
-initialization on free-threading builds.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-07-18-22-56-27.gh-issue-152125.sEPvJf.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-07-18-22-56-27.gh-issue-152125.sEPvJf.rst
new file mode 100644
index 000000000000000..ae66f69f206217f
--- /dev/null
+++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-07-18-22-56-27.gh-issue-152125.sEPvJf.rst
@@ -0,0 +1,3 @@
+Fix a crash in the :term:`free-threaded build` where :c:func:`PyList_New` could leave
+a newly allocated list's item buffer pointer uninitialized when the backing
+array allocation failed under low memory, leading to an invalid free.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-08-05-01-10-20.gh-issue-155181.jj8jhk.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-08-05-01-10-20.gh-issue-155181.jj8jhk.rst
new file mode 100644
index 000000000000000..1acf8fda95e4652
--- /dev/null
+++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-08-05-01-10-20.gh-issue-155181.jj8jhk.rst
@@ -0,0 +1,3 @@
+:class:`frozenset` objects created from a set literal or a set comprehension
+are now untracked by the garbage collector when none of their elements can
+be tracked.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-08-05-19-10-00.gh-issue-155247.extKey.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-08-05-19-10-00.gh-issue-155247.extKey.rst
new file mode 100644
index 000000000000000..1e08323008d5b7a
--- /dev/null
+++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-08-05-19-10-00.gh-issue-155247.extKey.rst
@@ -0,0 +1,4 @@
+Fix importing an extension module whose path contains characters unencodable
+in UTF-8, e.g. undecodable bytes of a file name. Previously it failed with
+:exc:`UnicodeEncodeError`, which made it impossible to build or run Python in
+a directory with such name.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-08-23-16-31-00.gh-issue-151126.phAWIG.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-08-23-16-31-00.gh-issue-151126.phAWIG.rst
new file mode 100644
index 000000000000000..b1459de1c1596d8
--- /dev/null
+++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-08-23-16-31-00.gh-issue-151126.phAWIG.rst
@@ -0,0 +1 @@
+Fix a crash when allocation failure occurs during :ref:`interp-object-sharing`.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-08-28-10-15-00.gh-issue-144446.pQ7wXn.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-08-28-10-15-00.gh-issue-144446.pQ7wXn.rst
new file mode 100644
index 000000000000000..2718a4cc7487f05
--- /dev/null
+++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-08-28-10-15-00.gh-issue-144446.pQ7wXn.rst
@@ -0,0 +1,2 @@
+Fix thread safety of :attr:`frame.f_locals` and :c:func:`PyFrame_GetVar` on
+frames executing on another thread in the free-threaded build.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-10-08-19-03-14.gh-issue-159037.nbQ5wk.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-10-08-19-03-14.gh-issue-159037.nbQ5wk.rst
new file mode 100644
index 000000000000000..a27cc2782d0b7c0
--- /dev/null
+++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-10-08-19-03-14.gh-issue-159037.nbQ5wk.rst
@@ -0,0 +1 @@
+Improve performance of :meth:`str.join`.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-10-09-18-27-12.gh-issue-159054.YUCTvG.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-10-09-18-27-12.gh-issue-159054.YUCTvG.rst
new file mode 100644
index 000000000000000..eaa01aa05435a72
--- /dev/null
+++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-10-09-18-27-12.gh-issue-159054.YUCTvG.rst
@@ -0,0 +1,2 @@
+Fixed a crash when an allocation failure occurred while compiling code
+containing cold blocks.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-10-22-15-40-00.gh-issue-160303.q7Zb2K.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-10-22-15-40-00.gh-issue-160303.q7Zb2K.rst
new file mode 100644
index 000000000000000..ba72afc400bd0ab
--- /dev/null
+++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-10-22-15-40-00.gh-issue-160303.q7Zb2K.rst
@@ -0,0 +1,5 @@
+Fix :class:`bytearray` reading and writing memory outside of its buffer
+after ``del b[:n]`` or ``b[:n] = shorter`` failed with :exc:`MemoryError`.
+The bytes are now removed even if shrinking the memory block fails;
+:exc:`MemoryError` is still raised. Also fix the missing null byte after the
+data when shrinking fails for a slice which is not at the front.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-10-22-20-18-44.gh-issue-160247.WC8hRU.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-10-22-20-18-44.gh-issue-160247.WC8hRU.rst
new file mode 100644
index 000000000000000..97755e25aac7c26
--- /dev/null
+++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-10-22-20-18-44.gh-issue-160247.WC8hRU.rst
@@ -0,0 +1,2 @@
+Reduce padding in the internal instruction sequence structure, saving 8 bytes
+per instance on 64-bit platforms. Patch by Shamil Abdulaev.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-10-23-08-01-14.gh-issue-159580.lEl21_.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-10-23-08-01-14.gh-issue-159580.lEl21_.rst
new file mode 100644
index 000000000000000..5acc2d3283d5ad2
--- /dev/null
+++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-10-23-08-01-14.gh-issue-159580.lEl21_.rst
@@ -0,0 +1 @@
+Improve performance of :func:`isinstance` when the check fails.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-10-24-19-40-00.gh-issue-160573.sT9kQe.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-10-24-19-40-00.gh-issue-160573.sT9kQe.rst
new file mode 100644
index 000000000000000..7a69a4769204857
--- /dev/null
+++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-10-24-19-40-00.gh-issue-160573.sT9kQe.rst
@@ -0,0 +1,4 @@
+Fix a crash when a :class:`set` iterator that is shared between threads reaches
+its end in a free-threaded build: every thread that walked off the end of the
+table released the iterator's reference to the set, so the set was over-released.
+The iterator now keeps its reference to the set until it is deallocated.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-10-25-12-30-00.gh-issue-112564.gcDbgW.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-10-25-12-30-00.gh-issue-112564.gcDbgW.rst
new file mode 100644
index 000000000000000..5ff3cb147e71c0d
--- /dev/null
+++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-10-25-12-30-00.gh-issue-112564.gcDbgW.rst
@@ -0,0 +1,5 @@
+Fix a crash in the garbage collector when :data:`gc.DEBUG_COLLECTABLE` or
+:data:`gc.DEBUG_UNCOLLECTABLE` is set and writing the debug output to
+:data:`sys.stderr` frees one of the objects being reported. Object addresses
+in this output now use the same ``0x``-prefixed lowercase format on all
+platforms, including Windows.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-10-26-10-18-26.gh-issue-160697.qSbR1f.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-10-26-10-18-26.gh-issue-160697.qSbR1f.rst
new file mode 100644
index 000000000000000..55649732e8f4b23
--- /dev/null
+++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-10-26-10-18-26.gh-issue-160697.qSbR1f.rst
@@ -0,0 +1,4 @@
+Fix crashes and hangs in the :term:`free-threaded build` when a destructor
+ran in the middle of a :class:`dict` resize, a :class:`list` resize or a type
+cache update. The thread's queue of delayed frees is now processed only from
+the eval breaker, instead of synchronously when the queue fills up.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-01-16-02-42.gh-issue-161145.5vLdrm.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-01-16-02-42.gh-issue-161145.5vLdrm.rst
new file mode 100644
index 000000000000000..5d809624e25f420
--- /dev/null
+++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-01-16-02-42.gh-issue-161145.5vLdrm.rst
@@ -0,0 +1,2 @@
+Speed up UTF-8 decoding of long ASCII runs, such as in :meth:`bytes.decode`,
+by up to 1.5x.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-09-12-00-00.gh-issue-161693.Sp1tKy.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-09-12-00-00.gh-issue-161693.Sp1tKy.rst
new file mode 100644
index 000000000000000..ed820f6d29efe9a
--- /dev/null
+++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-09-12-00-00.gh-issue-161693.Sp1tKy.rst
@@ -0,0 +1,3 @@
+Fix a crash in :meth:`dict.setdefault` when called on an instance
+dictionary with a :class:`str` subclass key equal to an attribute name
+that is not set on that instance.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-11-04-58-51.gh-issue-161792.42EcBI8x.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-11-04-58-51.gh-issue-161792.42EcBI8x.rst
new file mode 100644
index 000000000000000..a4b685d96bc8967
--- /dev/null
+++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-11-04-58-51.gh-issue-161792.42EcBI8x.rst
@@ -0,0 +1,4 @@
+Fix crashes in the callable iterator returned by :func:`iter` with a
+sentinel, when :meth:`!__setstate__` is called while the iterator is in use,
+or when the iterator is shared between threads in the :term:`free-threaded
+build`.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-11-21-52-02.gh-issue-161827.3PD3RK.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-11-21-52-02.gh-issue-161827.3PD3RK.rst
new file mode 100644
index 000000000000000..2ae6517db14f157
--- /dev/null
+++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-11-21-52-02.gh-issue-161827.3PD3RK.rst
@@ -0,0 +1,4 @@
+Keep ``_PyEval_EvalFrameDefault`` as a separate frame in the C call stack
+when Python is built with the tail-calling interpreter
+(:option:`--with-tail-call-interp`), so that stack unwinders, profilers and
+other tools that walk the stack can find the interpreter loop.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-12-14-37-21.gh-issue-161875.W-nGSw.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-12-14-37-21.gh-issue-161875.W-nGSw.rst
new file mode 100644
index 000000000000000..693f39a2bef9177
--- /dev/null
+++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-12-14-37-21.gh-issue-161875.W-nGSw.rst
@@ -0,0 +1,3 @@
+The :opcode:`GET_AWAITABLE` instruction now also pushes the ``NULL`` and
+``None`` that start the :opcode:`SEND` loop, so ``await`` no longer needs
+separate :opcode:`PUSH_NULL` and ``LOAD_CONST None`` instructions.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-12-14-46-10.gh-issue-161875.oOjR9w.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-12-14-46-10.gh-issue-161875.oOjR9w.rst
new file mode 100644
index 000000000000000..9afa682ea8b6ffb
--- /dev/null
+++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-12-14-46-10.gh-issue-161875.oOjR9w.rst
@@ -0,0 +1,4 @@
+The :opcode:`GET_ANEXT` instruction now also pushes the ``NULL`` and
+``None`` that start the :opcode:`SEND` loop, so each :keyword:`async for`
+iteration no longer needs separate :opcode:`PUSH_NULL` and ``LOAD_CONST None``
+instructions.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-13-00-00-00.gh-issue-161968.ytuf5z.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-13-00-00-00.gh-issue-161968.ytuf5z.rst
new file mode 100644
index 000000000000000..12d61b2eeee74e8
--- /dev/null
+++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-13-00-00-00.gh-issue-161968.ytuf5z.rst
@@ -0,0 +1,2 @@
+Fix ``x *= seq`` raising :exc:`TypeError` when ``x`` is an instance of an
+:class:`int` subclass or of a class defining :meth:`~object.__index__`.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-13-08-43-30.gh-issue-161849.m5BmNR.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-13-08-43-30.gh-issue-161849.m5BmNR.rst
new file mode 100644
index 000000000000000..744a5abed698f45
--- /dev/null
+++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-13-08-43-30.gh-issue-161849.m5BmNR.rst
@@ -0,0 +1,4 @@
+Fix a crash and a :exc:`SystemError` when compiling a class whose body binds
+``__classdict__`` (for example ``__classdict__ = 1`` or ``global
+__classdict__``) and also contains an annotated function, a generic class or
+function, or a generic type alias.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-14-23-17-18.gh-issue-161751.-silGa.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-14-23-17-18.gh-issue-161751.-silGa.rst
new file mode 100644
index 000000000000000..0c39e484386dc58
--- /dev/null
+++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-14-23-17-18.gh-issue-161751.-silGa.rst
@@ -0,0 +1,2 @@
+Fix race in mimalloc abandoned segment visit in free-threaded GC. Patch by
+Donghee Na.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-20-12-00-00.gh-issue-152276.bRcImm.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-20-12-00-00.gh-issue-152276.bRcImm.rst
new file mode 100644
index 000000000000000..9cc5d98dae0d0f1
--- /dev/null
+++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-20-12-00-00.gh-issue-152276.bRcImm.rst
@@ -0,0 +1,2 @@
+For the :term:`free-threaded build`, avoid an assertion failure when an object
+becomes immortal while queued for biased reference counting (BRC) merging.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-21-12-00-00.gh-issue-162227.fMtScl.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-21-12-00-00.gh-issue-162227.fMtScl.rst
new file mode 100644
index 000000000000000..06b6570b2cd26c2
--- /dev/null
+++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-21-12-00-00.gh-issue-162227.fMtScl.rst
@@ -0,0 +1,4 @@
+Improve multi-threaded scaling of :func:`format`, f-strings and
+:meth:`str.format` with a format specification on the :term:`free-threaded
+build` by avoiding the creation of a temporary bound method and reference
+count contention on the shared ``__format__`` method.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-23-09-17-41.gh-issue-162477.TEcSpB.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-23-09-17-41.gh-issue-162477.TEcSpB.rst
new file mode 100644
index 000000000000000..9bfe0a710fc669b
--- /dev/null
+++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-23-09-17-41.gh-issue-162477.TEcSpB.rst
@@ -0,0 +1,2 @@
+Speed up :c:func:`PyFloat_AsDouble` for exact :class:`int` arguments. Patch by
+Maurycy Pawłowski-Wieroński.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/README.rst b/Misc/NEWS.d/next/Core_and_Builtins/README.rst
index 00831936c450841..52b8c3e62631630 100644
--- a/Misc/NEWS.d/next/Core_and_Builtins/README.rst
+++ b/Misc/NEWS.d/next/Core_and_Builtins/README.rst
@@ -1,3 +1 @@
-Put news entry `blurb`_ files for the *Core and Builtins* section in this directory.
-
-.. _blurb: https://pypi.org/project/blurb/
+Put news entry ``blurb`` files for the *Core and Builtins* section in this directory.
diff --git a/Misc/NEWS.d/next/Documentation/2023-09-16-23-42-27.gh-issue-109503.mZ-kdU.rst b/Misc/NEWS.d/next/Documentation/2023-09-16-23-42-27.gh-issue-109503.mZ-kdU.rst
deleted file mode 100644
index c3c6c57569c2ea5..000000000000000
--- a/Misc/NEWS.d/next/Documentation/2023-09-16-23-42-27.gh-issue-109503.mZ-kdU.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix documentation for :func:`shutil.move` on usage of
-:func:`os.rename` since nonatomic move might be used even if the files are
-on the same filesystem. Patch by Fang Li
diff --git a/Misc/NEWS.d/next/Documentation/2026-05-23-17-27-41.gh-issue-150319.ol9tWK.rst b/Misc/NEWS.d/next/Documentation/2026-05-23-17-27-41.gh-issue-150319.ol9tWK.rst
deleted file mode 100644
index d56ccbce2fa325c..000000000000000
--- a/Misc/NEWS.d/next/Documentation/2026-05-23-17-27-41.gh-issue-150319.ol9tWK.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Generic builtin and standard library types now document the meaning of their
-type parameters.
diff --git a/Misc/NEWS.d/next/Documentation/2026-06-17-12-00-00.gh-issue-86726.__bOgH.rst b/Misc/NEWS.d/next/Documentation/2026-06-17-12-00-00.gh-issue-86726.__bOgH.rst
deleted file mode 100644
index 787b95dbf236279..000000000000000
--- a/Misc/NEWS.d/next/Documentation/2026-06-17-12-00-00.gh-issue-86726.__bOgH.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Greatly expand the :mod:`tkinter` documentation to cover the full public API
-of the package and its submodules. The descriptions are oriented towards
-Python rather than Tcl/Tk, with corrected return types and
-``versionadded``/``versionchanged`` information.
diff --git a/Misc/NEWS.d/next/Documentation/README.rst b/Misc/NEWS.d/next/Documentation/README.rst
index 245b7d635993de2..405f0ac01a7202e 100644
--- a/Misc/NEWS.d/next/Documentation/README.rst
+++ b/Misc/NEWS.d/next/Documentation/README.rst
@@ -1,3 +1 @@
-Put news entry `blurb`_ files for the *Documentation* section in this directory.
-
-.. _blurb: https://pypi.org/project/blurb/
+Put news entry ``blurb`` files for the *Documentation* section in this directory.
diff --git a/Misc/NEWS.d/next/Emscripten/README.rst b/Misc/NEWS.d/next/Emscripten/README.rst
new file mode 100644
index 000000000000000..521a81eeffb53f7
--- /dev/null
+++ b/Misc/NEWS.d/next/Emscripten/README.rst
@@ -0,0 +1 @@
+Put news entry ``blurb`` files for the *Emscripten* section in this directory.
diff --git a/Misc/NEWS.d/next/FreeBSD/README.rst b/Misc/NEWS.d/next/FreeBSD/README.rst
new file mode 100644
index 000000000000000..c2cae7b30e4d5e0
--- /dev/null
+++ b/Misc/NEWS.d/next/FreeBSD/README.rst
@@ -0,0 +1 @@
+Put news entry ``blurb`` files for the *FreeBSD* section in this directory.
diff --git a/Misc/NEWS.d/next/IDLE/2019-12-12-03-18-02.bpo-6699.1CqJFG.rst b/Misc/NEWS.d/next/IDLE/2019-12-12-03-18-02.bpo-6699.1CqJFG.rst
deleted file mode 100644
index e7fb9bf1b3bdf6a..000000000000000
--- a/Misc/NEWS.d/next/IDLE/2019-12-12-03-18-02.bpo-6699.1CqJFG.rst
+++ /dev/null
@@ -1 +0,0 @@
-Warn the user if a file will be overwritten when saving.
diff --git a/Misc/NEWS.d/next/IDLE/2026-06-28-06-46-46.gh-issue-85320.Hq2vKn.rst b/Misc/NEWS.d/next/IDLE/2026-06-28-06-46-46.gh-issue-85320.Hq2vKn.rst
deleted file mode 100644
index ec34bf8ead9eb9f..000000000000000
--- a/Misc/NEWS.d/next/IDLE/2026-06-28-06-46-46.gh-issue-85320.Hq2vKn.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-IDLE now reads and writes its configuration files and the breakpoints file
-using UTF-8 instead of the locale encoding. This keeps non-ASCII data (such
-as non-ASCII paths) from being corrupted and makes the files portable between
-environments.
diff --git a/Misc/NEWS.d/next/IDLE/2026-07-01-00-00-00.gh-issue-66331.wMcLaS.rst b/Misc/NEWS.d/next/IDLE/2026-07-01-00-00-00.gh-issue-66331.wMcLaS.rst
deleted file mode 100644
index e00e7c7d8fdc652..000000000000000
--- a/Misc/NEWS.d/next/IDLE/2026-07-01-00-00-00.gh-issue-66331.wMcLaS.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Set the ``WM_CLASS`` window property of IDLE's windows to ``Idle`` on X11,
-so that window managers group and label them correctly instead of using the
-default ``Toplevel``.
diff --git a/Misc/NEWS.d/next/IDLE/2026-07-01-00-15-58.gh-issue-152728.yxIhMN.rst b/Misc/NEWS.d/next/IDLE/2026-07-01-00-15-58.gh-issue-152728.yxIhMN.rst
deleted file mode 100644
index d73512a615c1898..000000000000000
--- a/Misc/NEWS.d/next/IDLE/2026-07-01-00-15-58.gh-issue-152728.yxIhMN.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Move functions run.fix_scaling, editor.fixwordbreaks (as fix_word_breaks)
-and pyshell.fix_x11_paste to idlelib.util.
diff --git a/Misc/NEWS.d/next/IDLE/2026-07-01-12-00-00.gh-issue-71956.rPlAlL.rst b/Misc/NEWS.d/next/IDLE/2026-07-01-12-00-00.gh-issue-71956.rPlAlL.rst
deleted file mode 100644
index 1a92ed4cd389cf5..000000000000000
--- a/Misc/NEWS.d/next/IDLE/2026-07-01-12-00-00.gh-issue-71956.rPlAlL.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix Replace All in the IDLE editor's Replace dialog when the search
-direction is "Up" and "Wrap around" is off: it now replaces all matches
-above the current position instead of only the first one.
diff --git a/Misc/NEWS.d/next/IDLE/2026-07-01-14-00-00.gh-issue-89360.mUlTiC.rst b/Misc/NEWS.d/next/IDLE/2026-07-01-14-00-00.gh-issue-89360.mUlTiC.rst
deleted file mode 100644
index 9e3023f8228233f..000000000000000
--- a/Misc/NEWS.d/next/IDLE/2026-07-01-14-00-00.gh-issue-89360.mUlTiC.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix a rare crash in the IDLE editor when the completion window is closed:
-deleting a key binding for a sequence that is not bound to the virtual
-event is now ignored instead of raising a ``ValueError``.
diff --git a/Misc/NEWS.d/next/IDLE/2026-07-01-15-00-00.gh-issue-134300.iDlPaT.rst b/Misc/NEWS.d/next/IDLE/2026-07-01-15-00-00.gh-issue-134300.iDlPaT.rst
deleted file mode 100644
index 791acbbed62aaf3..000000000000000
--- a/Misc/NEWS.d/next/IDLE/2026-07-01-15-00-00.gh-issue-134300.iDlPaT.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Do not add the ``idlelib`` directory to the path of the IDLE user process.
-User code run in IDLE can no longer import ``idlelib`` submodules as
-top-level modules, such as ``import help``.
diff --git a/Misc/NEWS.d/next/IDLE/2026-07-01-16-00-00.gh-issue-80504.gReP.rst b/Misc/NEWS.d/next/IDLE/2026-07-01-16-00-00.gh-issue-80504.gReP.rst
deleted file mode 100644
index 93adb33202a41c1..000000000000000
--- a/Misc/NEWS.d/next/IDLE/2026-07-01-16-00-00.gh-issue-80504.gReP.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-The "In files:" field of IDLE's Find in Files dialog now always contains a
-full directory path, even for an unsaved editor or the Shell. This shows
-in the grep output which directory was searched.
diff --git a/Misc/NEWS.d/next/IDLE/2026-07-01-17-00-00.gh-issue-65339.oUtTxt.rst b/Misc/NEWS.d/next/IDLE/2026-07-01-17-00-00.gh-issue-65339.oUtTxt.rst
deleted file mode 100644
index a8b216e86dc8d7e..000000000000000
--- a/Misc/NEWS.d/next/IDLE/2026-07-01-17-00-00.gh-issue-65339.oUtTxt.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Saving the IDLE Shell or an Output window now defaults to a ``.txt``
-extension and lists text files before Python files, since their content is
-not Python source.
diff --git a/Misc/NEWS.d/next/IDLE/2026-07-01-18-00-00.gh-issue-83653.cFgInt.rst b/Misc/NEWS.d/next/IDLE/2026-07-01-18-00-00.gh-issue-83653.cFgInt.rst
deleted file mode 100644
index 5812b2dd977f6a9..000000000000000
--- a/Misc/NEWS.d/next/IDLE/2026-07-01-18-00-00.gh-issue-83653.cFgInt.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Blanking an integer entry in IDLE's Settings dialog, such as "Auto squeeze
-min lines", no longer saves an empty string as an invalid configuration
-value.
diff --git a/Misc/NEWS.d/next/IDLE/2026-07-01-19-00-00.gh-issue-82183.rNsTrt.rst b/Misc/NEWS.d/next/IDLE/2026-07-01-19-00-00.gh-issue-82183.rNsTrt.rst
deleted file mode 100644
index 2af412f5200d0de..000000000000000
--- a/Misc/NEWS.d/next/IDLE/2026-07-01-19-00-00.gh-issue-82183.rNsTrt.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-When the shell is busy running code, using "Run... Customized" with "Restart
-shell" unchecked now reports that the shell is executing instead of
-restarting it anyway.
diff --git a/Misc/NEWS.d/next/IDLE/README.rst b/Misc/NEWS.d/next/IDLE/README.rst
index 834c5d48b95f608..5475f7b42050cd5 100644
--- a/Misc/NEWS.d/next/IDLE/README.rst
+++ b/Misc/NEWS.d/next/IDLE/README.rst
@@ -1,3 +1 @@
-Put news entry `blurb`_ files for the *IDLE* section in this directory.
-
-.. _blurb: https://pypi.org/project/blurb/
+Put news entry ``blurb`` files for the *IDLE* section in this directory.
diff --git a/Misc/NEWS.d/next/Library/2021-01-09-18-40-15.bpo-42861.T7Ge9O.rst b/Misc/NEWS.d/next/Library/2021-01-09-18-40-15.bpo-42861.T7Ge9O.rst
deleted file mode 100644
index 46ed99d1e1b4992..000000000000000
--- a/Misc/NEWS.d/next/Library/2021-01-09-18-40-15.bpo-42861.T7Ge9O.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Add :meth:`~ipaddress.IPv4Network.next_network` and
-:meth:`~ipaddress.IPv6Network.next_network`. Patch by Faisal Mahmood.
diff --git a/Misc/NEWS.d/next/Library/2021-02-26-13-17-57.bpo-40469.yJHeQg.rst b/Misc/NEWS.d/next/Library/2021-02-26-13-17-57.bpo-40469.yJHeQg.rst
deleted file mode 100644
index 239f856bb04c0ae..000000000000000
--- a/Misc/NEWS.d/next/Library/2021-02-26-13-17-57.bpo-40469.yJHeQg.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-:class:`~logging.handlers.TimedRotatingFileHandler` now uses the creation time
-instead of the last modification time of an existing log file as the basis
-for the first rotation after handler creation, if supported by the OS and file system.
-This allows it to be used in short-running programs that start and end before
-the rotation interval expires.
diff --git a/Misc/NEWS.d/next/Library/2021-10-18-13-46-55.bpo-45509.Upwb60.rst b/Misc/NEWS.d/next/Library/2021-10-18-13-46-55.bpo-45509.Upwb60.rst
deleted file mode 100644
index 80c38c03f8fe787..000000000000000
--- a/Misc/NEWS.d/next/Library/2021-10-18-13-46-55.bpo-45509.Upwb60.rst
+++ /dev/null
@@ -1 +0,0 @@
-Gzip headers are now checked for corrupted NAME, COMMENT and HCRC fields.
diff --git a/Misc/NEWS.d/next/Library/2022-04-04-17-58-05.bpo-47216.gPyPte.rst b/Misc/NEWS.d/next/Library/2022-04-04-17-58-05.bpo-47216.gPyPte.rst
deleted file mode 100644
index 066e17c1c6e06aa..000000000000000
--- a/Misc/NEWS.d/next/Library/2022-04-04-17-58-05.bpo-47216.gPyPte.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Added *mtime* option to :func:`gzip.open`, which will be passed
-to the constructor of :class:`~gzip.GzipFile`.
diff --git a/Misc/NEWS.d/next/Library/2022-04-10-20-10-59.bpo-46375.8j1ogZ.rst b/Misc/NEWS.d/next/Library/2022-04-10-20-10-59.bpo-46375.8j1ogZ.rst
deleted file mode 100644
index 0d1ebb6bbee1136..000000000000000
--- a/Misc/NEWS.d/next/Library/2022-04-10-20-10-59.bpo-46375.8j1ogZ.rst
+++ /dev/null
@@ -1 +0,0 @@
-Add :meth:`io.BytesIO.peek` method to read without advancing position.
diff --git a/Misc/NEWS.d/next/Library/2023-01-23-21-23-50.gh-issue-101267._f-cFH.rst b/Misc/NEWS.d/next/Library/2023-01-23-21-23-50.gh-issue-101267._f-cFH.rst
deleted file mode 100644
index 901a3fb60ab5b9f..000000000000000
--- a/Misc/NEWS.d/next/Library/2023-01-23-21-23-50.gh-issue-101267._f-cFH.rst
+++ /dev/null
@@ -1,7 +0,0 @@
-When a worker process terminates unexpectedly,
-:class:`concurrent.futures.ProcessPoolExecutor` now sets a separate
-:exc:`~concurrent.futures.process.BrokenProcessPool` exception on each pending
-future instead of sharing a single instance among them all. Sharing one
-exception produced malformed tracebacks: each
-:meth:`Future.result() ` call re-raised the
-same object, appending another copy of the traceback to it.
diff --git a/Misc/NEWS.d/next/Library/2023-02-26-14-07-18.gh-issue-91099._QPbEL.rst b/Misc/NEWS.d/next/Library/2023-02-26-14-07-18.gh-issue-91099._QPbEL.rst
deleted file mode 100644
index d886e8ac6032a4a..000000000000000
--- a/Misc/NEWS.d/next/Library/2023-02-26-14-07-18.gh-issue-91099._QPbEL.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-:meth:`imaplib.IMAP4.login` now raises exceptions with :class:`str` instead of
-:class:`bytes`. Patch by Florian Best.
diff --git a/Misc/NEWS.d/next/Library/2023-04-24-11-12-00.gh-issue-60055.UjP6aX.rst b/Misc/NEWS.d/next/Library/2023-04-24-11-12-00.gh-issue-60055.UjP6aX.rst
deleted file mode 100644
index 58fface7caded53..000000000000000
--- a/Misc/NEWS.d/next/Library/2023-04-24-11-12-00.gh-issue-60055.UjP6aX.rst
+++ /dev/null
@@ -1 +0,0 @@
-Let ``urllib.robotparser.RobotFileParser`` accept a ``urllib.request.Request`` object as well as a url string when setting a robots.txt url.
diff --git a/Misc/NEWS.d/next/Library/2023-06-12-21-31-02.gh-issue-105708.5fFwP8.rst b/Misc/NEWS.d/next/Library/2023-06-12-21-31-02.gh-issue-105708.5fFwP8.rst
deleted file mode 100644
index 79289c1f0bd4217..000000000000000
--- a/Misc/NEWS.d/next/Library/2023-06-12-21-31-02.gh-issue-105708.5fFwP8.rst
+++ /dev/null
@@ -1 +0,0 @@
-Accept an uppercase V prefix in IPvFuture addresses in :func:`urllib.parse.urlsplit`.
diff --git a/Misc/NEWS.d/next/Library/2023-10-18-13-31-10.gh-issue-110941.UVrYGE.rst b/Misc/NEWS.d/next/Library/2023-10-18-13-31-10.gh-issue-110941.UVrYGE.rst
new file mode 100644
index 000000000000000..5824b593460e9be
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2023-10-18-13-31-10.gh-issue-110941.UVrYGE.rst
@@ -0,0 +1,2 @@
+Fix ``json.dump`` and ``json.dumps`` encoding certain dict subclasses as
+empty.
diff --git a/Misc/NEWS.d/next/Library/2024-03-17-22-16-53.gh-issue-115988.EshSDM.rst b/Misc/NEWS.d/next/Library/2024-03-17-22-16-53.gh-issue-115988.EshSDM.rst
deleted file mode 100644
index 4efde6a48c26cc8..000000000000000
--- a/Misc/NEWS.d/next/Library/2024-03-17-22-16-53.gh-issue-115988.EshSDM.rst
+++ /dev/null
@@ -1 +0,0 @@
-:mod:`lzma` adds constants to support the newer BCJ filters for ARM64 and RISC-V.
diff --git a/Misc/NEWS.d/next/Library/2024-06-18-04-08-37.gh-issue-120665.x7T1hV.rst b/Misc/NEWS.d/next/Library/2024-06-18-04-08-37.gh-issue-120665.x7T1hV.rst
deleted file mode 100644
index 27e93988ed11efb..000000000000000
--- a/Misc/NEWS.d/next/Library/2024-06-18-04-08-37.gh-issue-120665.x7T1hV.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fixed an issue where ``unittest`` loaders would load and instantiate :class:`unittest.TestCase`-derived subclasses that are also abstract base classes, which can't be instantiated.
diff --git a/Misc/NEWS.d/next/Library/2024-07-02-20-57-43.gh-issue-121109.Tp6R2s.rst b/Misc/NEWS.d/next/Library/2024-07-02-20-57-43.gh-issue-121109.Tp6R2s.rst
deleted file mode 100644
index eca6014e4a0aed1..000000000000000
--- a/Misc/NEWS.d/next/Library/2024-07-02-20-57-43.gh-issue-121109.Tp6R2s.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix :mod:`tarfile` performance issue when reading archives in streaming mode
-(e.g. ``r|*``).
diff --git a/Misc/NEWS.d/next/Library/2024-11-02-02-02-31.gh-issue-107398.uUtA6Q.rst b/Misc/NEWS.d/next/Library/2024-11-02-02-02-31.gh-issue-107398.uUtA6Q.rst
deleted file mode 100644
index d5af322d68d309a..000000000000000
--- a/Misc/NEWS.d/next/Library/2024-11-02-02-02-31.gh-issue-107398.uUtA6Q.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fix :mod:`tarfile` stream mode exception when process the file with the gzip extra field.
diff --git a/Misc/NEWS.d/next/Library/2025-03-01-13-36-02.gh-issue-128110.9wx_G0.rst b/Misc/NEWS.d/next/Library/2025-03-01-13-36-02.gh-issue-128110.9wx_G0.rst
deleted file mode 100644
index b08b1886cff9cf6..000000000000000
--- a/Misc/NEWS.d/next/Library/2025-03-01-13-36-02.gh-issue-128110.9wx_G0.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-Fix bug in the parsing of :mod:`email` address headers that could result in
-extraneous spaces in the decoded text when using a modern email policy.
-Space between pairs of adjacent :rfc:`2047` encoded-words is now ignored, per
-section 6.2 (and consistent with existing parsing of unstructured
-headers like *Subject*).
diff --git a/Misc/NEWS.d/next/Library/2025-05-01-16-44-16.gh-issue-72902.19qwJW.rst b/Misc/NEWS.d/next/Library/2025-05-01-16-44-16.gh-issue-72902.19qwJW.rst
deleted file mode 100644
index 2b7d8e448408943..000000000000000
--- a/Misc/NEWS.d/next/Library/2025-05-01-16-44-16.gh-issue-72902.19qwJW.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Optimize (~x1.4 speedup) :meth:`fractions.Fraction.from_decimal` and
-:meth:`fractions.Fraction.from_float` for :class:`~decimal.Decimal` and
-:class:`float` inputs, respectively. Patch by Sergey B Kirpichev.
diff --git a/Misc/NEWS.d/next/Library/2025-05-07-18-31-31.gh-issue-46927.sF02gj.rst b/Misc/NEWS.d/next/Library/2025-05-07-18-31-31.gh-issue-46927.sF02gj.rst
deleted file mode 100644
index 3ba9757c8acb5de..000000000000000
--- a/Misc/NEWS.d/next/Library/2025-05-07-18-31-31.gh-issue-46927.sF02gj.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Prevent :mod:`readline` from overriding the ``COLUMNS`` and ``LINES``
-environment variables, as values are not updated on terminal resize.
diff --git a/Misc/NEWS.d/next/Library/2025-05-19-20-29-35.gh-issue-133998.KmElUw.rst b/Misc/NEWS.d/next/Library/2025-05-19-20-29-35.gh-issue-133998.KmElUw.rst
deleted file mode 100644
index 77d92628beefacd..000000000000000
--- a/Misc/NEWS.d/next/Library/2025-05-19-20-29-35.gh-issue-133998.KmElUw.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-Fix :exc:`struct.error` exception when creating a file with
-:class:`gzip.GzipFile` or compressing data with :func:`gzip.compress`
-if the system time is outside the range 00:00:00 UTC, January 1, 1970
-through 06:28:15 UTC, February 7, 2106, or explicitly passed *mtime*
-argument is outside the range ``0`` to ``2**32-1``.
diff --git a/Misc/NEWS.d/next/Library/2025-05-19-21-08-25.gh-issue-134261.ravGYm.rst b/Misc/NEWS.d/next/Library/2025-05-19-21-08-25.gh-issue-134261.ravGYm.rst
deleted file mode 100644
index bf552fee814acbf..000000000000000
--- a/Misc/NEWS.d/next/Library/2025-05-19-21-08-25.gh-issue-134261.ravGYm.rst
+++ /dev/null
@@ -1 +0,0 @@
-zip: On reproducible builds, ZipFile uses UTC instead of the local time when writing file datetimes to avoid underflows.
diff --git a/Misc/NEWS.d/next/Library/2025-05-24-11-17-34.gh-issue-51067.yHOgfy.rst b/Misc/NEWS.d/next/Library/2025-05-24-11-17-34.gh-issue-51067.yHOgfy.rst
deleted file mode 100644
index 204213c74de5dfd..000000000000000
--- a/Misc/NEWS.d/next/Library/2025-05-24-11-17-34.gh-issue-51067.yHOgfy.rst
+++ /dev/null
@@ -1 +0,0 @@
-Add :meth:`~zipfile.ZipFile.remove` and :meth:`~zipfile.ZipFile.repack` to :class:`~zipfile.ZipFile`.
diff --git a/Misc/NEWS.d/next/Library/2025-08-30-07-44-30.gh-issue-86533.pathlib.rst b/Misc/NEWS.d/next/Library/2025-08-30-07-44-30.gh-issue-86533.pathlib.rst
deleted file mode 100644
index 9c32671173e0ad2..000000000000000
--- a/Misc/NEWS.d/next/Library/2025-08-30-07-44-30.gh-issue-86533.pathlib.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-The :func:`os.makedirs` function and :meth:`pathlib.Path.mkdir` method now have
-a *parent_mode* parameter to specify the mode for intermediate directories when
-creating parent directories. This allows one to match the behavior from Python
-3.6 and earlier for :func:`os.makedirs`.
diff --git a/Misc/NEWS.d/next/Library/2025-09-05-20-50-35.gh-issue-79638.Y-JfaH.rst b/Misc/NEWS.d/next/Library/2025-09-05-20-50-35.gh-issue-79638.Y-JfaH.rst
deleted file mode 100644
index bd9fff0bc2e31b6..000000000000000
--- a/Misc/NEWS.d/next/Library/2025-09-05-20-50-35.gh-issue-79638.Y-JfaH.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Disallow all access in :mod:`urllib.robotparser` if the ``robots.txt`` file
-is unreachable due to server or network errors.
diff --git a/Misc/NEWS.d/next/Library/2025-10-09-12-13-29.gh-issue-139819.YxUDyH.rst b/Misc/NEWS.d/next/Library/2025-10-09-12-13-29.gh-issue-139819.YxUDyH.rst
deleted file mode 100644
index ab3a8c6ed16ce4a..000000000000000
--- a/Misc/NEWS.d/next/Library/2025-10-09-12-13-29.gh-issue-139819.YxUDyH.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-:mod:`rlcompleter`: Avoid suggesting attributes that are not accessible on
-instances (e.g., Enum members showing ``__name__``). Patch by Peter
-(ttw225).
diff --git a/Misc/NEWS.d/next/Library/2025-10-12-08-46-26.gh-issue-139398.hESOMl.rst b/Misc/NEWS.d/next/Library/2025-10-12-08-46-26.gh-issue-139398.hESOMl.rst
deleted file mode 100644
index 201b682d177c010..000000000000000
--- a/Misc/NEWS.d/next/Library/2025-10-12-08-46-26.gh-issue-139398.hESOMl.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Add supported ``_sunder_`` names to the :func:`dir` method of the :mod:`enum` module
-to support them in :term:`REPL` autocompletion.
diff --git a/Misc/NEWS.d/next/Library/2025-10-20-09-12-18.gh-issue-140344.WjbYg-.rst b/Misc/NEWS.d/next/Library/2025-10-20-09-12-18.gh-issue-140344.WjbYg-.rst
deleted file mode 100644
index ca3046941c6c93f..000000000000000
--- a/Misc/NEWS.d/next/Library/2025-10-20-09-12-18.gh-issue-140344.WjbYg-.rst
+++ /dev/null
@@ -1,11 +0,0 @@
-The classes ``ast.slice``, ``ast.ExtSlice``, ``ast.Index``, ``ast.Suite``, ``ast.AugLoad``,
-``ast.AugStore``, and ``ast.Param``, deprecated since Python 3.9, now issue
-deprecation warnings on use. They are now scheduled for removal in Python 3.21.
-
-The ``dims`` property of ``ast.Tuple`` objects, deprecated since Python 3.9,
-now issues a deprecation warning when accessed. The property is scheduled for
-removal in Python 3.21. Use the (non-deprecated) ``elts`` property of
-``ast.Tuple`` objects instead.
-
-The deprecated global names are also no longer imported by
-``from ast import *``.
diff --git a/Misc/NEWS.d/next/Library/2025-11-02-05-28-56.gh-issue-115634.JbcNnF.rst b/Misc/NEWS.d/next/Library/2025-11-02-05-28-56.gh-issue-115634.JbcNnF.rst
deleted file mode 100644
index f023ce999c60b7c..000000000000000
--- a/Misc/NEWS.d/next/Library/2025-11-02-05-28-56.gh-issue-115634.JbcNnF.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-Fix a deadlock in :class:`concurrent.futures.ProcessPoolExecutor` when
-using ``max_tasks_per_child``, present since the feature was introduced in
-Python 3.11. The executor stopped scheduling queued tasks after a worker
-process exited upon reaching its task limit. Based on a fix proposed by
-Tabrez Mohammed.
diff --git a/Misc/NEWS.d/next/Library/2025-11-02-22-24-13.gh-issue-140924.NQVbR_.rst b/Misc/NEWS.d/next/Library/2025-11-02-22-24-13.gh-issue-140924.NQVbR_.rst
deleted file mode 100644
index 91c30c95469f089..000000000000000
--- a/Misc/NEWS.d/next/Library/2025-11-02-22-24-13.gh-issue-140924.NQVbR_.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Add :func:`locale.localize`, :func:`locale.delocalize`
-and platform-specific locale constants
-from the :mod:`!_locale` module to ``locale.__all__``.
diff --git a/Misc/NEWS.d/next/Library/2025-11-08-13-22-33.gh-issue-140494.L_cKec.rst b/Misc/NEWS.d/next/Library/2025-11-08-13-22-33.gh-issue-140494.L_cKec.rst
new file mode 100644
index 000000000000000..142cdac28f70f87
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2025-11-08-13-22-33.gh-issue-140494.L_cKec.rst
@@ -0,0 +1,2 @@
+Require that Tcl is always built with thread support.
+This requirement only affects Tcl 8.x, as Tcl 9.x is always thread-enabled.
diff --git a/Misc/NEWS.d/next/Library/2025-12-14-06-44-34.gh-issue-81881.qancdQ.rst b/Misc/NEWS.d/next/Library/2025-12-14-06-44-34.gh-issue-81881.qancdQ.rst
deleted file mode 100644
index 6b6ca6a1918bdd1..000000000000000
--- a/Misc/NEWS.d/next/Library/2025-12-14-06-44-34.gh-issue-81881.qancdQ.rst
+++ /dev/null
@@ -1 +0,0 @@
-:func:`shutil.copyfile` now raises :exc:`~shutil.SpecialFileError` for sockets and device files.
diff --git a/Misc/NEWS.d/next/Library/2025-12-21-17-56-37.gh-issue-143008.aakErJ.rst b/Misc/NEWS.d/next/Library/2025-12-21-17-56-37.gh-issue-143008.aakErJ.rst
deleted file mode 100644
index 907cdb770ab65f9..000000000000000
--- a/Misc/NEWS.d/next/Library/2025-12-21-17-56-37.gh-issue-143008.aakErJ.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix crash in :class:`io.TextIOWrapper` when reentrant
-:meth:`io.TextIOBase.detach` is called reentrantly from the underlying buffer.
diff --git a/Misc/NEWS.d/next/Library/2026-01-10-17-39-09.gh-issue-143663.9LEFAf.rst b/Misc/NEWS.d/next/Library/2026-01-10-17-39-09.gh-issue-143663.9LEFAf.rst
new file mode 100644
index 000000000000000..8428770d51d734b
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-01-10-17-39-09.gh-issue-143663.9LEFAf.rst
@@ -0,0 +1,2 @@
+:meth:`tarfile.TarFile.extractall` now uses OS-specific separators to call
+lstat.
diff --git a/Misc/NEWS.d/next/Library/2026-01-18-06-42-47.gh-issue-143988.MtLtCP.rst b/Misc/NEWS.d/next/Library/2026-01-18-06-42-47.gh-issue-143988.MtLtCP.rst
deleted file mode 100644
index fcc0cb54934b90e..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-01-18-06-42-47.gh-issue-143988.MtLtCP.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fixed crashes in :meth:`socket.socket.sendmsg` and :meth:`socket.socket.recvmsg_into`
-that could occur if buffer sequences are concurrently mutated.
diff --git a/Misc/NEWS.d/next/Library/2026-02-11-16-47-27.gh-issue-140729.2uTPQp.rst b/Misc/NEWS.d/next/Library/2026-02-11-16-47-27.gh-issue-140729.2uTPQp.rst
deleted file mode 100644
index 49c9adc4679abbf..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-02-11-16-47-27.gh-issue-140729.2uTPQp.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix a pickling error in the ``cProfile`` module when profiling a script that
-uses :class:`multiprocessing.Process` with the ``spawn`` and ``forkserver``
-start methods.
diff --git a/Misc/NEWS.d/next/Library/2026-03-26-00-00-00.gh-issue-47005.xxc89c.rst b/Misc/NEWS.d/next/Library/2026-03-26-00-00-00.gh-issue-47005.xxc89c.rst
deleted file mode 100644
index 646367f0fa069d3..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-03-26-00-00-00.gh-issue-47005.xxc89c.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Fix :meth:`!urllib.request.AbstractHTTPHandler.do_open` to give regular
-headers set via :meth:`~urllib.request.Request.add_header` priority over
-unredirected headers, consistent with :meth:`~urllib.request.Request.get_header`
-and :meth:`~urllib.request.Request.header_items`.
diff --git a/Misc/NEWS.d/next/Library/2026-03-26-09-30-00.gh-issue-146452.Y2N6qZ8J.rst b/Misc/NEWS.d/next/Library/2026-03-26-09-30-00.gh-issue-146452.Y2N6qZ8J.rst
deleted file mode 100644
index 99f3cce33497a12..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-03-26-09-30-00.gh-issue-146452.Y2N6qZ8J.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix segfault in :mod:`pickle` when pickling a dictionary concurrently
-mutated by another thread in the free-threaded build.
diff --git a/Misc/NEWS.d/next/Library/2026-04-20-01-24-22.gh-issue-92455.vXhmad.rst b/Misc/NEWS.d/next/Library/2026-04-20-01-24-22.gh-issue-92455.vXhmad.rst
deleted file mode 100644
index 8d2a11cb7761377..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-04-20-01-24-22.gh-issue-92455.vXhmad.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix :mod:`mimetypes` to prefer case-sensitive matches for suffix mappings and
-MIME type suffixes before falling back to case-insensitive matches.
-Contributed by Xiao Yuan.
diff --git a/Misc/NEWS.d/next/Library/2026-04-21-06-30-59.gh-issue-119670.pMWZfY.rst b/Misc/NEWS.d/next/Library/2026-04-21-06-30-59.gh-issue-119670.pMWZfY.rst
deleted file mode 100644
index fc1941be4dc7925..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-04-21-06-30-59.gh-issue-119670.pMWZfY.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Add keyword-only parameter *force* to :func:`shlex.quote` to force quoting
-a string, even if it is already safe for a shell without being quoted.
diff --git a/Misc/NEWS.d/next/Library/2026-04-23-12-50-15.gh-issue-148441.zvpCkR.rst b/Misc/NEWS.d/next/Library/2026-04-23-12-50-15.gh-issue-148441.zvpCkR.rst
deleted file mode 100644
index 762815270e4d403..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-04-23-12-50-15.gh-issue-148441.zvpCkR.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-:mod:`xml.parsers.expat`: prevent a crash in
-:meth:`~xml.parsers.expat.xmlparser.CharacterDataHandler`
-when the character data size exceeds the parser's
-:attr:`buffer size `.
diff --git a/Misc/NEWS.d/next/Library/2026-04-24-19-54-00.gh-issue-148954.v1.rst b/Misc/NEWS.d/next/Library/2026-04-24-19-54-00.gh-issue-148954.v1.rst
deleted file mode 100644
index 6245af7e362e920..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-04-24-19-54-00.gh-issue-148954.v1.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fix XML injection vulnerability in :func:`xmlrpc.client.dumps` where the ``methodname`` was not being escaped before interpolation into the XML body.
diff --git a/Misc/NEWS.d/next/Library/2026-04-26-11-25-38.gh-issue-118158.xIy05H.rst b/Misc/NEWS.d/next/Library/2026-04-26-11-25-38.gh-issue-118158.xIy05H.rst
deleted file mode 100644
index bd22871c1c0c172..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-04-26-11-25-38.gh-issue-118158.xIy05H.rst
+++ /dev/null
@@ -1 +0,0 @@
-Ensure py_compile CLI error messages end with a newline. Contributed by Xiao Yuan.
diff --git a/Misc/NEWS.d/next/Library/2026-04-27-11-12-00.gh-issue-149046.74shDd.rst b/Misc/NEWS.d/next/Library/2026-04-27-11-12-00.gh-issue-149046.74shDd.rst
deleted file mode 100644
index b05c4222e30fcd2..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-04-27-11-12-00.gh-issue-149046.74shDd.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-:mod:`io`: Fix :class:`io.StringIO` serialization: no longer call ``str(obj)`` on :class:`str`
-subclasses. Patch by Thomas Kowalski.
diff --git a/Misc/NEWS.d/next/Library/2026-04-29-08-10-17.gh-issue-149056.jnaD4W.rst b/Misc/NEWS.d/next/Library/2026-04-29-08-10-17.gh-issue-149056.jnaD4W.rst
deleted file mode 100644
index 0026d02c8762570..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-04-29-08-10-17.gh-issue-149056.jnaD4W.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix :func:`json.load` not forwarding the *array_hook* argument to
-:func:`json.loads`. Patch by Thomas Kowalski.
diff --git a/Misc/NEWS.d/next/Library/2026-05-06-20-10-44.gh-issue-149464.3mPhcr.rst b/Misc/NEWS.d/next/Library/2026-05-06-20-10-44.gh-issue-149464.3mPhcr.rst
deleted file mode 100644
index 9f987d2a662d8fb..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-06-20-10-44.gh-issue-149464.3mPhcr.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Add :func:`os.pidfd_getfd` for duplicating a file descriptor from another
-process via a pidfd. Available on Linux 5.6+. Patch by Maurycy
-Pawłowski-Wieroński.
diff --git a/Misc/NEWS.d/next/Library/2026-05-07-14-18-47.gh-issue-149489.bX9iHe.rst b/Misc/NEWS.d/next/Library/2026-05-07-14-18-47.gh-issue-149489.bX9iHe.rst
deleted file mode 100644
index 1550c893fd7c45b..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-07-14-18-47.gh-issue-149489.bX9iHe.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-Fix :mod:`~xml.etree.ElementTree` serialization to HTML. The content of
-comments, processing instructions and elements "xmp", "iframe", "noembed",
-"noframes", and "plaintext" is no longer escaped. The "plaintext" element no
-longer have the closing tag. Add support of empty attributes (with value
-``None``).
diff --git a/Misc/NEWS.d/next/Library/2026-05-07-17-35-47.gh-issue-149499.G2ER-R.rst b/Misc/NEWS.d/next/Library/2026-05-07-17-35-47.gh-issue-149499.G2ER-R.rst
deleted file mode 100644
index 796d39f5ba05bf1..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-07-17-35-47.gh-issue-149499.G2ER-R.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Removed the :func:`!sysconfig.expand_makefile_vars` function which has been
-deprecated since Python 3.14. Use the ``vars`` argument of
-:func:`sysconfig.get_paths` instead.
diff --git a/Misc/NEWS.d/next/Library/2026-05-07-21-58-17.gh-issue-149388.DDBPeA.rst b/Misc/NEWS.d/next/Library/2026-05-07-21-58-17.gh-issue-149388.DDBPeA.rst
deleted file mode 100644
index 4a1c6f3f5b4e579..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-07-21-58-17.gh-issue-149388.DDBPeA.rst
+++ /dev/null
@@ -1 +0,0 @@
-Make :class:`!asyncio.windows_utils.PipeHandle` closing idempotent.
diff --git a/Misc/NEWS.d/next/Library/2026-05-08-06-12-26.gh-issue-149528.AxdDxa.rst b/Misc/NEWS.d/next/Library/2026-05-08-06-12-26.gh-issue-149528.AxdDxa.rst
deleted file mode 100644
index b2c6e427a1c592f..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-08-06-12-26.gh-issue-149528.AxdDxa.rst
+++ /dev/null
@@ -1 +0,0 @@
-Remove ``annotationlib.ForwardRef._evaludate`` deprecated method.
diff --git a/Misc/NEWS.d/next/Library/2026-05-08-06-56-57.gh-issue-149530.cl2AJ8.rst b/Misc/NEWS.d/next/Library/2026-05-08-06-56-57.gh-issue-149530.cl2AJ8.rst
deleted file mode 100644
index 2b74e8cdadd03c3..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-08-06-56-57.gh-issue-149530.cl2AJ8.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Removed :meth:`!symtable.Class.get_methods` which has been deprecated since
-3.14.
diff --git a/Misc/NEWS.d/next/Library/2026-05-08-07-51-54.gh-issue-80480.nnA4p1.rst b/Misc/NEWS.d/next/Library/2026-05-08-07-51-54.gh-issue-80480.nnA4p1.rst
deleted file mode 100644
index 2f7f15b169b26b5..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-08-07-51-54.gh-issue-80480.nnA4p1.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Remove deprecated ``'u'`` type code (:c:type:`wchar_t`) for the :mod:`array`
-module. Use ``'w'`` format code instead (:c:type:`Py_UCS4`, always 4 bytes).
diff --git a/Misc/NEWS.d/next/Library/2026-05-08-08-24-01.gh-issue-149537.hVFVnt.rst b/Misc/NEWS.d/next/Library/2026-05-08-08-24-01.gh-issue-149537.hVFVnt.rst
deleted file mode 100644
index 2fb0359a2ea8936..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-08-08-24-01.gh-issue-149537.hVFVnt.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Remove kw parameters from python version of :func:`functools.reduce`
-function.
diff --git a/Misc/NEWS.d/next/Library/2026-05-08-09-11-48.gh-issue-149534.Tw7eeY.rst b/Misc/NEWS.d/next/Library/2026-05-08-09-11-48.gh-issue-149534.Tw7eeY.rst
deleted file mode 100644
index 0938935a75d8c16..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-08-09-11-48.gh-issue-149534.Tw7eeY.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fix merging of :class:`collections.defaultdict` and :class:`frozendict`.
diff --git a/Misc/NEWS.d/next/Library/2026-05-08-14-24-16.gh-issue-149436.dEV02X.rst b/Misc/NEWS.d/next/Library/2026-05-08-14-24-16.gh-issue-149436.dEV02X.rst
deleted file mode 100644
index 401cf044e1514fb..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-08-14-24-16.gh-issue-149436.dEV02X.rst
+++ /dev/null
@@ -1 +0,0 @@
-Improve performance of :meth:`inspect.getattr_static`.
diff --git a/Misc/NEWS.d/next/Library/2026-05-08-15-08-35.gh-issue-112821.t9T1YD.rst b/Misc/NEWS.d/next/Library/2026-05-08-15-08-35.gh-issue-112821.t9T1YD.rst
deleted file mode 100644
index cfbcde81493e221..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-08-15-08-35.gh-issue-112821.t9T1YD.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-In the REPL, autocompletion might run arbitrary code in the getter of a
-descriptor. If that getter raised an exception, autocompletion would fail to
-present any options for the entire object. Autocompletion now works as
-expected for these objects.
diff --git a/Misc/NEWS.d/next/Library/2026-05-08-16-44-20.gh-issue-149567.iiZKEj.rst b/Misc/NEWS.d/next/Library/2026-05-08-16-44-20.gh-issue-149567.iiZKEj.rst
deleted file mode 100644
index e30563df79b3bcf..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-08-16-44-20.gh-issue-149567.iiZKEj.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Remove the :exc:`!shutil.ExecError` exception which has been deprecated
-since Python 3.14.
diff --git a/Misc/NEWS.d/next/Library/2026-05-09-11-22-29.gh-issue-149595.1nuYXw.rst b/Misc/NEWS.d/next/Library/2026-05-09-11-22-29.gh-issue-149595.1nuYXw.rst
deleted file mode 100644
index f3971554de37487..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-09-11-22-29.gh-issue-149595.1nuYXw.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Remove the :func:`!sys._enablelegacywindowsfsencoding` function which has
-been deprecated since Python 3.13.
diff --git a/Misc/NEWS.d/next/Library/2026-05-09-15-17-59.gh-issue-149598.aLrXRw.rst b/Misc/NEWS.d/next/Library/2026-05-09-15-17-59.gh-issue-149598.aLrXRw.rst
deleted file mode 100644
index 8c06ba5e7d5e4e6..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-09-15-17-59.gh-issue-149598.aLrXRw.rst
+++ /dev/null
@@ -1 +0,0 @@
-Remove support of deprecated *strm* argument for :mod:`logging` handlers.
diff --git a/Misc/NEWS.d/next/Library/2026-05-09-15-42-54.gh-issue-149600.ZbL-iv.rst b/Misc/NEWS.d/next/Library/2026-05-09-15-42-54.gh-issue-149600.ZbL-iv.rst
deleted file mode 100644
index 732787dc92c1090..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-09-15-42-54.gh-issue-149600.ZbL-iv.rst
+++ /dev/null
@@ -1 +0,0 @@
-Remove deprecated :func:`!asyncio.iscoroutinefunction` function.
diff --git a/Misc/NEWS.d/next/Library/2026-05-09-21-02-08.gh-issue-149614.U4snj3.rst b/Misc/NEWS.d/next/Library/2026-05-09-21-02-08.gh-issue-149614.U4snj3.rst
deleted file mode 100644
index 5169c6c203fc1b3..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-09-21-02-08.gh-issue-149614.U4snj3.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fix a regression that broke the ability to deepcopy :class:`argparse.ArgumentParser` instances.
diff --git a/Misc/NEWS.d/next/Library/2026-05-10-07-21-51.gh-issue-139489.rS7LTA.rst b/Misc/NEWS.d/next/Library/2026-05-10-07-21-51.gh-issue-139489.rS7LTA.rst
deleted file mode 100644
index 40fe7e9fd6a0086..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-10-07-21-51.gh-issue-139489.rS7LTA.rst
+++ /dev/null
@@ -1 +0,0 @@
-Add :func:`xml.is_valid_text` to ``xml.__all__``.
diff --git a/Misc/NEWS.d/next/Library/2026-05-10-14-10-00.gh-issue-149634.iT5cwC.rst b/Misc/NEWS.d/next/Library/2026-05-10-14-10-00.gh-issue-149634.iT5cwC.rst
deleted file mode 100644
index 73e8d73c36891ab..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-10-14-10-00.gh-issue-149634.iT5cwC.rst
+++ /dev/null
@@ -1 +0,0 @@
-Remove deprecated and unused :attr:`!tarfile.TarInfo.tarfile` attribute.
diff --git a/Misc/NEWS.d/next/Library/2026-05-10-16-06-27.gh-issue-149609.yLKPXo.rst b/Misc/NEWS.d/next/Library/2026-05-10-16-06-27.gh-issue-149609.yLKPXo.rst
deleted file mode 100644
index 3acba7d25021b28..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-10-16-06-27.gh-issue-149609.yLKPXo.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Raise :exc:`DeprecationWarning` on using :class:`abc.abstractclassmethod`,
-:class:`abc.abstractstaticmethod`, and :class:`abc.abstractproperty`,
-schedule its removal for Python 3.21.
diff --git a/Misc/NEWS.d/next/Library/2026-05-10-19-26-50.gh-issue-149584.x7Qm9A.rst b/Misc/NEWS.d/next/Library/2026-05-10-19-26-50.gh-issue-149584.x7Qm9A.rst
deleted file mode 100644
index 6734250fdd6af3c..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-10-19-26-50.gh-issue-149584.x7Qm9A.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Fix excessive overhead in the Tachyon profiler when inspecting a remote
-process by avoiding repeated remote page-cache scans, batching predicted
-remote reads, and reusing cached profiler result objects. Patch by Pablo
-Galindo and Maurycy Pawłowski-Wieroński.
diff --git a/Misc/NEWS.d/next/Library/2026-05-10-23-51-23.gh-issue-149504.pDSCbn.rst b/Misc/NEWS.d/next/Library/2026-05-10-23-51-23.gh-issue-149504.pDSCbn.rst
deleted file mode 100644
index 88bf268123bbecc..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-10-23-51-23.gh-issue-149504.pDSCbn.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-Fix :func:`site.addsitedir` to allow re-entrant calls from within startup
-files. Previously, a ``.pth`` file containing an ``import`` line that
-called :func:`site.addsitedir` (or a ``.start`` entry point doing the same)
-could crash with ``RuntimeError: dictionary changed size during iteration``
-during site initialization, breaking tools such as ``uv run --with``.
diff --git a/Misc/NEWS.d/next/Library/2026-05-12-06-24-54.gh-issue-149701.8v9RTm.rst b/Misc/NEWS.d/next/Library/2026-05-12-06-24-54.gh-issue-149701.8v9RTm.rst
deleted file mode 100644
index 676d788cbce62a3..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-12-06-24-54.gh-issue-149701.8v9RTm.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fix bad return code from Lib/venv/bin/activate if hashing is disabled
diff --git a/Misc/NEWS.d/next/Library/2026-05-12-13-03-45.gh-issue-149718.SaM1NJ.rst b/Misc/NEWS.d/next/Library/2026-05-12-13-03-45.gh-issue-149718.SaM1NJ.rst
deleted file mode 100644
index 25344e5a90f022c..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-12-13-03-45.gh-issue-149718.SaM1NJ.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Coalesce consecutive identical stack frames in Tachyon, so aggregating
-collectors (pstats, collapsed, flamegraph, gecko) receive one collect.
-Improves sample rate 3x, error rate and missed rate drop by 70%. Patch by
-Maurycy Pawłowski-Wieroński.
diff --git a/Misc/NEWS.d/next/Library/2026-05-12-14-44-39.gh-issue-149720.ccsoW-.rst b/Misc/NEWS.d/next/Library/2026-05-12-14-44-39.gh-issue-149720.ccsoW-.rst
deleted file mode 100644
index f16d8770d740f49..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-12-14-44-39.gh-issue-149720.ccsoW-.rst
+++ /dev/null
@@ -1 +0,0 @@
-Remove support for undotted *ext* in :meth:`mimetypes.MimeTypes.add_type`.
diff --git a/Misc/NEWS.d/next/Library/2026-05-13-12-16-54.gh-issue-149473.nOQZqn.rst b/Misc/NEWS.d/next/Library/2026-05-13-12-16-54.gh-issue-149473.nOQZqn.rst
deleted file mode 100644
index db624aba31a9de0..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-13-12-16-54.gh-issue-149473.nOQZqn.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Calling ``os.environ.clear()`` now emits ``os._clearenv`` auditing event.
-Patch by Victor Stinner.
diff --git a/Misc/NEWS.d/next/Library/2026-05-13-23-18-39.gh-issue-149801.S_FfGr.rst b/Misc/NEWS.d/next/Library/2026-05-13-23-18-39.gh-issue-149801.S_FfGr.rst
deleted file mode 100644
index f9e8538527d204e..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-13-23-18-39.gh-issue-149801.S_FfGr.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Add IANA registered names and aliases with leading zeros before number (like
-IBM00858, CP00858, IBM01140, CP01140) for corresponding codecs.
diff --git a/Misc/NEWS.d/next/Library/2026-05-14-15-55-28.gh-issue-149816.ZaXQ0q.rst b/Misc/NEWS.d/next/Library/2026-05-14-15-55-28.gh-issue-149816.ZaXQ0q.rst
deleted file mode 100644
index 3ea70071ec3c75d..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-14-15-55-28.gh-issue-149816.ZaXQ0q.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix a race condition in ``_random.Random.__init__`` method in free-threading
-mode.
diff --git a/Misc/NEWS.d/next/Library/2026-05-14-17-01-19.gh-issue-62259.ytlFD5.rst b/Misc/NEWS.d/next/Library/2026-05-14-17-01-19.gh-issue-62259.ytlFD5.rst
deleted file mode 100644
index d0af77366378b88..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-14-17-01-19.gh-issue-62259.ytlFD5.rst
+++ /dev/null
@@ -1,9 +0,0 @@
-Add support for multiple multi-byte encodings in the :mod:`XML parser
-`: "cp932", "cp949", "cp950", "Big5","EUC-JP", "GB2312",
-"GBK", "johab", and "Shift_JIS". Add partial support (only BMP characters)
-for multi-byte encodings "Big5-HKSCS", "EUC_JIS-2004", "EUC_JISX0213",
-"Shift_JIS-2004", "Shift_JISX0213", "utf-8-sig" and non-standard aliases
-like "UTF8" (without hyphen). The parser now raises :exc:`ValueError` for
-known unsupported multi-byte encodings such us "ISO-2022-JP" or
-"raw-unicode-escape" instead of failing later, when encounter non-ASCII
-data.
diff --git a/Misc/NEWS.d/next/Library/2026-05-15-16-28-00.gh-issue-149819.fixpth.rst b/Misc/NEWS.d/next/Library/2026-05-15-16-28-00.gh-issue-149819.fixpth.rst
deleted file mode 100644
index 66e6da0ecf0d87c..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-15-16-28-00.gh-issue-149819.fixpth.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Fix regression in :func:`site.addsitedir` where ``.pth`` files were no
-longer processed in Python subprocesses. This happened because
-:func:`site.main` seeded ``known_paths`` with entries inherited from
-the parent process, causing ``addsitedir`` to skip ``.pth`` processing.
diff --git a/Misc/NEWS.d/next/Library/2026-05-15-18-44-20.gh-issue-142349.fHK3v1.rst b/Misc/NEWS.d/next/Library/2026-05-15-18-44-20.gh-issue-142349.fHK3v1.rst
deleted file mode 100644
index fa667c4110941e9..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-15-18-44-20.gh-issue-142349.fHK3v1.rst
+++ /dev/null
@@ -1 +0,0 @@
-Add :keyword:`lazy` to the list of support topic by :func:`help`.
diff --git a/Misc/NEWS.d/next/Library/2026-05-15-19-52-41.gh-issue-149891.BJUIGB.rst b/Misc/NEWS.d/next/Library/2026-05-15-19-52-41.gh-issue-149891.BJUIGB.rst
deleted file mode 100644
index f8bc28659533af8..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-15-19-52-41.gh-issue-149891.BJUIGB.rst
+++ /dev/null
@@ -1 +0,0 @@
-Add support for more encoding aliases `officially registered in IANA `__.
diff --git a/Misc/NEWS.d/next/Library/2026-05-16-21-08-33.gh-issue-149921.I1yNML.rst b/Misc/NEWS.d/next/Library/2026-05-16-21-08-33.gh-issue-149921.I1yNML.rst
deleted file mode 100644
index 113bd1a802f7990..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-16-21-08-33.gh-issue-149921.I1yNML.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix reference leaks in error paths of the :mod:`!_interpchannels` and
-:mod:`!_interpqueues` extension modules.
diff --git a/Misc/NEWS.d/next/Library/2026-05-16-22-00-00.gh-issue-146406.10e0da.rst b/Misc/NEWS.d/next/Library/2026-05-16-22-00-00.gh-issue-146406.10e0da.rst
deleted file mode 100644
index 8f65fecd85dbf4c..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-16-22-00-00.gh-issue-146406.10e0da.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Add cross-language hints for ``.clear()`` on :class:`tuple`,
-:class:`frozenset`, and :class:`frozendict`, suggesting the mutable
-counterpart. Follow-up to :gh:`146406`.
diff --git a/Misc/NEWS.d/next/Library/2026-05-17-02-25-56.gh-issue-149571.LNyuWJ.rst b/Misc/NEWS.d/next/Library/2026-05-17-02-25-56.gh-issue-149571.LNyuWJ.rst
deleted file mode 100644
index 2b71d9cf2200be4..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-17-02-25-56.gh-issue-149571.LNyuWJ.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix the C implementation of :meth:`xml.etree.ElementTree.Element.itertext`:
-it no longer emits text for comments and processing instructions.
diff --git a/Misc/NEWS.d/next/Library/2026-05-17-12-37-59.gh-issue-53144.c5tr1p.rst b/Misc/NEWS.d/next/Library/2026-05-17-12-37-59.gh-issue-53144.c5tr1p.rst
deleted file mode 100644
index 283a5ba44d1f19f..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-17-12-37-59.gh-issue-53144.c5tr1p.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-The :mod:`email` package now supports all aliases of Python codecs and uses
-MIME/IANA names for all IANA registered charsets.
diff --git a/Misc/NEWS.d/next/Library/2026-05-17-22-37-02.gh-issue-88726.BAoL6j.rst b/Misc/NEWS.d/next/Library/2026-05-17-22-37-02.gh-issue-88726.BAoL6j.rst
deleted file mode 100644
index ba9058d79c9873a..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-17-22-37-02.gh-issue-88726.BAoL6j.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-The :mod:`email` package now uses standard MIME charset names "gb2312" and
-"big5" instead of non-standard names "eucgb2312_cn" and "big5_tw".
diff --git a/Misc/NEWS.d/next/Library/2026-05-18-07-44-46.gh-issue-149995.vvtFHn.rst b/Misc/NEWS.d/next/Library/2026-05-18-07-44-46.gh-issue-149995.vvtFHn.rst
deleted file mode 100644
index a8e412b578da378..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-18-07-44-46.gh-issue-149995.vvtFHn.rst
+++ /dev/null
@@ -1 +0,0 @@
-Update various docstrings in :mod:`typing`.
diff --git a/Misc/NEWS.d/next/Library/2026-05-18-12-42-31.gh-issue-149816.F98iME.rst b/Misc/NEWS.d/next/Library/2026-05-18-12-42-31.gh-issue-149816.F98iME.rst
deleted file mode 100644
index 21e3ae0df57621c..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-18-12-42-31.gh-issue-149816.F98iME.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix a potential use after free condition in :func:`pickle.dumps` in free-threaded
-mode when serializing lists.
diff --git a/Misc/NEWS.d/next/Library/2026-05-18-13-43-06.gh-issue-79413.OpTXbV.rst b/Misc/NEWS.d/next/Library/2026-05-18-13-43-06.gh-issue-79413.OpTXbV.rst
deleted file mode 100644
index 8d62fda8b2b67f4..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-18-13-43-06.gh-issue-79413.OpTXbV.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Update :func:`dataclasses.make_dataclass` to add a *qualname* parameter. The
-*qualname* parameter will be used to set the :attr:`!__qualname__` of the
-created ``dataclass``.
diff --git a/Misc/NEWS.d/next/Library/2026-05-18-17-17-20.gh-issue-149189.a8IooK.rst b/Misc/NEWS.d/next/Library/2026-05-18-17-17-20.gh-issue-149189.a8IooK.rst
deleted file mode 100644
index bad027f2c71c6fd..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-18-17-17-20.gh-issue-149189.a8IooK.rst
+++ /dev/null
@@ -1 +0,0 @@
-Revert the changes to :mod:`pprint` defaults. Patch by Hugo van Kemenade.
diff --git a/Misc/NEWS.d/next/Library/2026-05-18-22-45-54.gh-issue-149816.T68vc_.rst b/Misc/NEWS.d/next/Library/2026-05-18-22-45-54.gh-issue-149816.T68vc_.rst
deleted file mode 100644
index 9996cc7ec0e8664..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-18-22-45-54.gh-issue-149816.T68vc_.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fix race condition in :attr:`ssl.SSLContext.sni_callback`
diff --git a/Misc/NEWS.d/next/Library/2026-05-19-11-42-37.gh-issue-127949.Ab3kZq.rst b/Misc/NEWS.d/next/Library/2026-05-19-11-42-37.gh-issue-127949.Ab3kZq.rst
deleted file mode 100644
index c295d5fffd82fcf..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-19-11-42-37.gh-issue-127949.Ab3kZq.rst
+++ /dev/null
@@ -1 +0,0 @@
-Remove the deprecated :mod:`asyncio` event loop policy system. Patch by Kumar Aditya.
diff --git a/Misc/NEWS.d/next/Library/2026-05-19-12-00-00.gh-issue-149980.Kx7p2A.rst b/Misc/NEWS.d/next/Library/2026-05-19-12-00-00.gh-issue-149980.Kx7p2A.rst
deleted file mode 100644
index b056f6a3cda25d3..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-19-12-00-00.gh-issue-149980.Kx7p2A.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix :mod:`tarfile` so that GNU long-name directory entries have all
-trailing slashes stripped from their names, matching the behavior for
-short-name entries. Previously, only a single trailing slash was removed.
diff --git a/Misc/NEWS.d/next/Library/2026-05-19-18-25-00.gh-issue-150077.zstopen-close.rst b/Misc/NEWS.d/next/Library/2026-05-19-18-25-00.gh-issue-150077.zstopen-close.rst
deleted file mode 100644
index 06d20e41e25037a..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-19-18-25-00.gh-issue-150077.zstopen-close.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix ``tarfile.TarFile.zstopen`` to close the underlying zstd file object
-when opening the tar archive is interrupted by a :exc:`BaseException`
-subclass such as :exc:`KeyboardInterrupt`.
diff --git a/Misc/NEWS.d/next/Library/2026-05-19-19-00-49.gh-issue-84353.ZU5zaQ.rst b/Misc/NEWS.d/next/Library/2026-05-19-19-00-49.gh-issue-84353.ZU5zaQ.rst
deleted file mode 100644
index 84fb12e2abd81a0..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-19-19-00-49.gh-issue-84353.ZU5zaQ.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-Preserve non-UTF-8 encoded filenames when appending to a
-:class:`zipfile.ZipFile`. Previously, non-ASCII names stored in a legacy
-encoding (without the UTF-8 flag bit set) could be corrupted when the
-central directory was rewritten: they were decoded as cp437 and then
-re-stored as UTF-8.
diff --git a/Misc/NEWS.d/next/Library/2026-05-21-11-25-58.gh-issue-150175.8H4Caz.rst b/Misc/NEWS.d/next/Library/2026-05-21-11-25-58.gh-issue-150175.8H4Caz.rst
deleted file mode 100644
index 80fc80d4d50a636..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-21-11-25-58.gh-issue-150175.8H4Caz.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix race condition in :class:`unittest.mock.ThreadingMock` where
-concurrent calls could lose increments to ``call_count`` and other
-attributes due to a missing lock in ``_increment_mock_call``.
diff --git a/Misc/NEWS.d/next/Library/2026-05-21-20-47-45.gh-issue-150157.ZvmO-bQZ.rst b/Misc/NEWS.d/next/Library/2026-05-21-20-47-45.gh-issue-150157.ZvmO-bQZ.rst
deleted file mode 100644
index 3a12e26cf736f79..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-21-20-47-45.gh-issue-150157.ZvmO-bQZ.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix a crash in free-threaded builds that occurs when pickling by name
-objects without a ``__module__`` attribute while :data:`sys.modules`
-is concurrently being modified.
diff --git a/Misc/NEWS.d/next/Library/2026-05-22-15-30-00.gh-issue-132372.YP4a6x.rst b/Misc/NEWS.d/next/Library/2026-05-22-15-30-00.gh-issue-132372.YP4a6x.rst
deleted file mode 100644
index bcd96e88eac1bfd..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-22-15-30-00.gh-issue-132372.YP4a6x.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Speed up :func:`logging.config.fileConfig` and
-:func:`logging.config.dictConfig` when handling many existing loggers.
diff --git a/Misc/NEWS.d/next/Library/2026-05-25-07-22-05.gh-issue-150372.9hLqhe.rst b/Misc/NEWS.d/next/Library/2026-05-25-07-22-05.gh-issue-150372.9hLqhe.rst
deleted file mode 100644
index 7b83bd8fe73f11d..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-25-07-22-05.gh-issue-150372.9hLqhe.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-:mod:`readline`: Fix a potential crash during tab completion caused by an
-out-of-memory error during module initialization.
diff --git a/Misc/NEWS.d/next/Library/2026-05-25-17-00-00.gh-issue-150406.jF3g63.rst b/Misc/NEWS.d/next/Library/2026-05-25-17-00-00.gh-issue-150406.jF3g63.rst
deleted file mode 100644
index 230e961abd3f588..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-25-17-00-00.gh-issue-150406.jF3g63.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix a possible crash occurring during :mod:`socket` module initialization
-when the system is out of memory on platforms without a reentrant
-``gethostbyname``.
diff --git a/Misc/NEWS.d/next/Library/2026-05-26-19-30-00.gh-issue-150479.Kq7Lm2.rst b/Misc/NEWS.d/next/Library/2026-05-26-19-30-00.gh-issue-150479.Kq7Lm2.rst
deleted file mode 100644
index 5a41273f3501e39..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-26-19-30-00.gh-issue-150479.Kq7Lm2.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-:func:`email.utils.formataddr` now raises :exc:`ValueError` when the name or
-address contains a carriage return or line feed, matching
-:class:`email.headerregistry.Address`. This check can be disabled by passing
-``strict=False``.
diff --git a/Misc/NEWS.d/next/Library/2026-05-27-11-18-36.gh-issue-150228.pNPiO-.rst b/Misc/NEWS.d/next/Library/2026-05-27-11-18-36.gh-issue-150228.pNPiO-.rst
deleted file mode 100644
index 8c03989e90b2401..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-27-11-18-36.gh-issue-150228.pNPiO-.rst
+++ /dev/null
@@ -1,11 +0,0 @@
-The new :class:`site.StartupState` class lets callers batch-process
-:pep:`829` startup configuration files across multiple site directories
-before any startup code runs, with public
-:meth:`~site.StartupState.addsitedir`,
-:meth:`~site.StartupState.addusersitepackages`,
-:meth:`~site.StartupState.addsitepackages`, and
-:meth:`~site.StartupState.process` methods. The signature of
-:func:`site.addsitedir` is unchanged from Python 3.14. The
-:data:`!defer_processing_start_files` argument and the
-``process_startup_files()`` function added earlier in the 3.15 cycle have
-been removed; use :class:`!site.StartupState` instead.
diff --git a/Misc/NEWS.d/next/Library/2026-05-27-15-51-29.gh-issue-150534.3Nan6S.rst b/Misc/NEWS.d/next/Library/2026-05-27-15-51-29.gh-issue-150534.3Nan6S.rst
deleted file mode 100644
index 2ead9990513015f..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-27-15-51-29.gh-issue-150534.3Nan6S.rst
+++ /dev/null
@@ -1,6 +0,0 @@
-Added trigonometric functions that work in units of half turns, rather than
-radians. The new functions :func:`math.acospi`, :func:`math.asinpi`,
-:func:`math.atanpi`, and :func:`math.atan2pi` return half-turn angles. The
-new functions :func:`math.cospi`, :func:`math.sinpi`, and :func:`math.tanpi`
-take half-turn angle arguments. These functions are recommended by IEEE
-754-2019 and standardized in C23.
diff --git a/Misc/NEWS.d/next/Library/2026-05-27-23-47-31.gh-issue-148932.Y1xmvA.rst b/Misc/NEWS.d/next/Library/2026-05-27-23-47-31.gh-issue-148932.Y1xmvA.rst
deleted file mode 100644
index a0b7a9740cd518d..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-27-23-47-31.gh-issue-148932.Y1xmvA.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fix ``profiling.sampling`` on Windows virtual environments to resolve the actual Python PID from a virtual environment shim.
diff --git a/Misc/NEWS.d/next/Library/2026-05-28-23-38-46.gh-issue-150478.qEr0E-.rst b/Misc/NEWS.d/next/Library/2026-05-28-23-38-46.gh-issue-150478.qEr0E-.rst
deleted file mode 100644
index 0ceae5e313977a4..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-28-23-38-46.gh-issue-150478.qEr0E-.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Add ``show_jit`` option to ``dis.dis`` to show JIT entry points in the
-bytecode. This is useful for visualizing where JIT traces are entered from
-the interpreter.
diff --git a/Misc/NEWS.d/next/Library/2026-05-31-10-00-00.gh-issue-150942.Tk9aRef.rst b/Misc/NEWS.d/next/Library/2026-05-31-10-00-00.gh-issue-150942.Tk9aRef.rst
deleted file mode 100644
index ba0de8fd434d303..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-31-10-00-00.gh-issue-150942.Tk9aRef.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Speed up :func:`json.loads` decoding of arrays and objects by storing
-parsed values into the result list/dict without an extra reference-count
-round-trip (using the internal reference-stealing append/insert helpers).
diff --git a/Misc/NEWS.d/next/Library/2026-05-31-12-00-00.gh-issue-150942.Re7Ref.rst b/Misc/NEWS.d/next/Library/2026-05-31-12-00-00.gh-issue-150942.Re7Ref.rst
deleted file mode 100644
index 63967108b1e0b3b..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-31-12-00-00.gh-issue-150942.Re7Ref.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Speed up :func:`re.findall`, :func:`re.sub` and :func:`re.subn` by appending
-result items to the output list without an extra reference-count round-trip
-(using the internal reference-stealing list append helper).
diff --git a/Misc/NEWS.d/next/Library/2026-05-31-14-39-25.gh-issue-150641.LLIhd1.rst b/Misc/NEWS.d/next/Library/2026-05-31-14-39-25.gh-issue-150641.LLIhd1.rst
deleted file mode 100644
index eba899c96fcd26b..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-31-14-39-25.gh-issue-150641.LLIhd1.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix bug where :func:`typing.evaluate_forward_ref` with the ``STRING`` format
-could leak internal names used by the annotation machinery.
diff --git a/Misc/NEWS.d/next/Library/2026-05-31-17-47-30.gh-issue-150685.EBB2mU.rst b/Misc/NEWS.d/next/Library/2026-05-31-17-47-30.gh-issue-150685.EBB2mU.rst
deleted file mode 100644
index eb7f31112d004c8..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-05-31-17-47-30.gh-issue-150685.EBB2mU.rst
+++ /dev/null
@@ -1 +0,0 @@
-Update bundled pip to 26.1.2
diff --git a/Misc/NEWS.d/next/Library/2026-06-01-08-12-34.gh-issue-150717.LVRJXH.rst b/Misc/NEWS.d/next/Library/2026-06-01-08-12-34.gh-issue-150717.LVRJXH.rst
deleted file mode 100644
index da7171fcc72ce41..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-01-08-12-34.gh-issue-150717.LVRJXH.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Avoid an unnecessary per-call memory allocation when matching :mod:`re`
-patterns that have no capturing groups. Patch by Bernát Gábor.
diff --git a/Misc/NEWS.d/next/Library/2026-06-02-14-21-46.gh-issue-150750.SVS2o0.rst b/Misc/NEWS.d/next/Library/2026-06-02-14-21-46.gh-issue-150750.SVS2o0.rst
deleted file mode 100644
index bda500383e7cda3..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-02-14-21-46.gh-issue-150750.SVS2o0.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fix a race condition in :meth:`collections.deque.index` with free-threading.
diff --git a/Misc/NEWS.d/next/Library/2026-06-02-15-44-57.gh-issue-150817.lpFCh0.rst b/Misc/NEWS.d/next/Library/2026-06-02-15-44-57.gh-issue-150817.lpFCh0.rst
deleted file mode 100644
index 42532bb0222cf4e..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-02-15-44-57.gh-issue-150817.lpFCh0.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Speed up the ``|``, ``&`` and ``^`` operations on :class:`enum.Flag` members.
-Patch by Bernát Gábor.
diff --git a/Misc/NEWS.d/next/Library/2026-06-02-15-44-58.gh-issue-150818.Orcefu.rst b/Misc/NEWS.d/next/Library/2026-06-02-15-44-58.gh-issue-150818.Orcefu.rst
deleted file mode 100644
index 3bb16001cc0bb41..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-02-15-44-58.gh-issue-150818.Orcefu.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Speed up :func:`logging.getLogger` with a lock-free fast path that returns an
-already-registered logger without acquiring the logging lock. Patch by Bernát
-Gábor.
diff --git a/Misc/NEWS.d/next/Library/2026-06-03-13-51-29.gh-issue-150662.ELT8Vg.rst b/Misc/NEWS.d/next/Library/2026-06-03-13-51-29.gh-issue-150662.ELT8Vg.rst
deleted file mode 100644
index 42ed6ad7cd3c65f..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-03-13-51-29.gh-issue-150662.ELT8Vg.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Fix the ``--gecko`` collector in :mod:`profiling.sampling` that kept every
-sample in memory. It now writes sample and marker data to temporary files
-and reads them back, ultimately building the output file at the end. Patch
-by Pablo Galindo and Maurycy Pawłowski-Wieroński.
diff --git a/Misc/NEWS.d/next/Library/2026-06-03-19-35-32.gh-issue-150583.dedI24.rst b/Misc/NEWS.d/next/Library/2026-06-03-19-35-32.gh-issue-150583.dedI24.rst
deleted file mode 100644
index edb551b3c3c8cbd..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-03-19-35-32.gh-issue-150583.dedI24.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Correctly set the default compression level in :mod:`compression.zstd` when passing a digested
-dictionary during compression.
diff --git a/Misc/NEWS.d/next/Library/2026-06-03-21-59-11.gh-issue-150886.r2c25g.rst b/Misc/NEWS.d/next/Library/2026-06-03-21-59-11.gh-issue-150886.r2c25g.rst
deleted file mode 100644
index b220b63cfdb4ab5..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-03-21-59-11.gh-issue-150886.r2c25g.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Remove the private, undocumented function
-``importlib._bootstrap._object_name()``. It had no caller after
-``load_module()`` and its deprecation warnings were removed from
-:mod:`importlib`.
diff --git a/Misc/NEWS.d/next/Library/2026-06-04-06-50-06.gh-issue-150898.1LkLA3.rst b/Misc/NEWS.d/next/Library/2026-06-04-06-50-06.gh-issue-150898.1LkLA3.rst
deleted file mode 100644
index 85328c43368e198..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-04-06-50-06.gh-issue-150898.1LkLA3.rst
+++ /dev/null
@@ -1 +0,0 @@
-Unconditionally assume :attr:`ssl.SSLContext.keylog_filename` exists.
diff --git a/Misc/NEWS.d/next/Library/2026-06-04-10-44-36.gh-issue-150889.UYNLR_.rst b/Misc/NEWS.d/next/Library/2026-06-04-10-44-36.gh-issue-150889.UYNLR_.rst
deleted file mode 100644
index a5cc1da758637c5..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-04-10-44-36.gh-issue-150889.UYNLR_.rst
+++ /dev/null
@@ -1 +0,0 @@
-Speed up :func:`unicodedata.normalize` for the NFC and NFKC forms of non-ASCII text up to a factor 2.
diff --git a/Misc/NEWS.d/next/Library/2026-06-04-18-22-56.gh-issue-143008.z5tw-J.rst b/Misc/NEWS.d/next/Library/2026-06-04-18-22-56.gh-issue-143008.z5tw-J.rst
deleted file mode 100644
index e99bc39c45f9b8f..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-04-18-22-56.gh-issue-143008.z5tw-J.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fix race conditions when re-initializing a :class:`io.TextIOWrapper` object.
diff --git a/Misc/NEWS.d/next/Library/2026-06-04-19-24-13.gh-issue-140006.TD8HKl.rst b/Misc/NEWS.d/next/Library/2026-06-04-19-24-13.gh-issue-140006.TD8HKl.rst
deleted file mode 100644
index 6d8d66b29b19902..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-04-19-24-13.gh-issue-140006.TD8HKl.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-The :mod:`venv` ``activate.fish`` script now calls fish builtins through
-``builtin`` so a user function that shadows ``.``/``source``, ``echo``,
-``printf``, ``set_color``, or ``functions`` can no longer hijack the virtual
-environment prompt or break exit-status reporting.
diff --git a/Misc/NEWS.d/next/Library/2026-06-04-21-49-18.gh-issue-150913.EmptyBl.rst b/Misc/NEWS.d/next/Library/2026-06-04-21-49-18.gh-issue-150913.EmptyBl.rst
deleted file mode 100644
index f95a6ee6ee15bf7..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-04-21-49-18.gh-issue-150913.EmptyBl.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix :class:`sqlite3.Blob` slice assignment to raise
-:exc:`TypeError` and :exc:`IndexError` for type and size mismatches
-respectively, even when the target slice is empty.
diff --git a/Misc/NEWS.d/next/Library/2026-06-04-23-10-31.gh-issue-62825.BtG_yQ.rst b/Misc/NEWS.d/next/Library/2026-06-04-23-10-31.gh-issue-62825.BtG_yQ.rst
deleted file mode 100644
index 95a4fb1c61d4c30..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-04-23-10-31.gh-issue-62825.BtG_yQ.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Encodings "KS_C_5601-1987", "KS X 1001", etc are now aliases of "CP949"
-instead of "EUC-KR".
diff --git a/Misc/NEWS.d/next/Library/2026-06-06-06-29-17.gh-issue-150994.I2119M.rst b/Misc/NEWS.d/next/Library/2026-06-06-06-29-17.gh-issue-150994.I2119M.rst
deleted file mode 100644
index c4a610c24806b0a..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-06-06-29-17.gh-issue-150994.I2119M.rst
+++ /dev/null
@@ -1 +0,0 @@
-Make the type annotations in the private ``_colorize`` module resolvable.
diff --git a/Misc/NEWS.d/next/Library/2026-06-06-15-20-54.gh-issue-151021.J4qk2A.rst b/Misc/NEWS.d/next/Library/2026-06-06-15-20-54.gh-issue-151021.J4qk2A.rst
deleted file mode 100644
index 0617fa068c844d6..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-06-15-20-54.gh-issue-151021.J4qk2A.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix :meth:`mmap.mmap.find` and :meth:`~mmap.mmap.rfind` to return ``-1``
-when searching for an empty subsequence with a start position past the end
-of the mapping.
diff --git a/Misc/NEWS.d/next/Library/2026-06-07-13-47-05.gh-issue-151042.NMdzF2.rst b/Misc/NEWS.d/next/Library/2026-06-07-13-47-05.gh-issue-151042.NMdzF2.rst
deleted file mode 100644
index a24a15c0cc267f5..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-07-13-47-05.gh-issue-151042.NMdzF2.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fixed venv exporting mixed path styles to PATH on Windows inside fish (via Cygwin, MinGW or MSYS2)
diff --git a/Misc/NEWS.d/next/Library/2026-06-07-17-29-33.gh-issue-151039.AZ0qBn.rst b/Misc/NEWS.d/next/Library/2026-06-07-17-29-33.gh-issue-151039.AZ0qBn.rst
deleted file mode 100644
index 1e99567f5550579..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-07-17-29-33.gh-issue-151039.AZ0qBn.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fix a crash when static :mod:`datetime` types outlive the ``_datetime`` module.
diff --git a/Misc/NEWS.d/next/Library/2026-06-08-15-04-35.gh-issue-150285.-Tj94n.rst b/Misc/NEWS.d/next/Library/2026-06-08-15-04-35.gh-issue-150285.-Tj94n.rst
deleted file mode 100644
index 60b1f3e0a71f5bb..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-08-15-04-35.gh-issue-150285.-Tj94n.rst
+++ /dev/null
@@ -1 +0,0 @@
-:mod:`pydoc` now wraps long single-line summary in text output.
diff --git a/Misc/NEWS.d/next/Library/2026-06-09-12-00-00.gh-issue-150771.K7mNx2.rst b/Misc/NEWS.d/next/Library/2026-06-09-12-00-00.gh-issue-150771.K7mNx2.rst
deleted file mode 100644
index 6535e5c48bf0360..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-09-12-00-00.gh-issue-150771.K7mNx2.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Fix :mod:`email` messages created with ``shift_jis`` or ``euc-jp`` charsets.
-``set_content()`` now stores the payload using the output charset
-(``iso-2022-jp``) so printing the message no longer raises
-:exc:`UnicodeEncodeError`.
diff --git a/Misc/NEWS.d/next/Library/2026-06-09-14-49-17.gh-issue-80384.ttRAja.rst b/Misc/NEWS.d/next/Library/2026-06-09-14-49-17.gh-issue-80384.ttRAja.rst
deleted file mode 100644
index 53d4d513ba757de..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-09-14-49-17.gh-issue-80384.ttRAja.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-:func:`weakref.ref` and :func:`weakref.proxy` now raise :exc:`TypeError` if
-the *callback* argument is not callable or ``None``.
diff --git a/Misc/NEWS.d/next/Library/2026-06-09-19-43-24.gh-issue-151179.hl_6Z0.rst b/Misc/NEWS.d/next/Library/2026-06-09-19-43-24.gh-issue-151179.hl_6Z0.rst
deleted file mode 100644
index 904edf3a8c70908..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-09-19-43-24.gh-issue-151179.hl_6Z0.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix a pidfd leak in ``_PidfdChildWatcher`` on Linux: the watcher no
-longer leaks the process file descriptor when ``waitpid()`` fails with an
-error other than :exc:`ChildProcessError`.
diff --git a/Misc/NEWS.d/next/Library/2026-06-10-00-00-02.gh-issue-109940.Cx1099.rst b/Misc/NEWS.d/next/Library/2026-06-10-00-00-02.gh-issue-109940.Cx1099.rst
deleted file mode 100644
index 130dc780b612864..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-10-00-00-02.gh-issue-109940.Cx1099.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix Windows :mod:`venv` activation in ``cmd.exe`` to respect
-``VIRTUAL_ENV_DISABLE_PROMPT``.
diff --git a/Misc/NEWS.d/next/Library/2026-06-11-00-00-00.gh-issue-151295.NQYUzW.rst b/Misc/NEWS.d/next/Library/2026-06-11-00-00-00.gh-issue-151295.NQYUzW.rst
deleted file mode 100644
index e9012f023ff7f77..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-11-00-00-00.gh-issue-151295.NQYUzW.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Fixed a crash (use-after-free) in :meth:`bytes.join` and
-:meth:`bytearray.join` that could occur if an item's
-:meth:`~object.__buffer__` concurrently mutates the sequence being joined.
-The mutation is now reported as a :exc:`RuntimeError` instead.
diff --git a/Misc/NEWS.d/next/Library/2026-06-11-06-56-31.gh-issue-150994.gd1wVw.rst b/Misc/NEWS.d/next/Library/2026-06-11-06-56-31.gh-issue-150994.gd1wVw.rst
deleted file mode 100644
index 005a1d99b766dce..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-11-06-56-31.gh-issue-150994.gd1wVw.rst
+++ /dev/null
@@ -1 +0,0 @@
-Make type annotations in the private ``_colorize`` module resolvable.
diff --git a/Misc/NEWS.d/next/Library/2026-06-11-11-52-23.gh-issue-149671.6Rpr5r.rst b/Misc/NEWS.d/next/Library/2026-06-11-11-52-23.gh-issue-149671.6Rpr5r.rst
deleted file mode 100644
index 5c08828e5fd77ec..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-11-11-52-23.gh-issue-149671.6Rpr5r.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Restore compatibility with setuptools ``-nspkg.pth`` files in the :mod:`site`
-module. Inject ``sitedir`` variable in the frame which executes pth code.
-Patch by Victor Stinner.
diff --git a/Misc/NEWS.d/next/Library/2026-06-11-16-25-38.gh-issue-151126.bh_Usy.rst b/Misc/NEWS.d/next/Library/2026-06-11-16-25-38.gh-issue-151126.bh_Usy.rst
deleted file mode 100644
index 25149057aa7d092..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-11-16-25-38.gh-issue-151126.bh_Usy.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix a crash when :exc:`MemoryError` in :func:`!os._path_splitroot`
-was not set properly.
diff --git a/Misc/NEWS.d/next/Library/2026-06-11-19-46-16.gh-issue-150285.wuhAsL.rst b/Misc/NEWS.d/next/Library/2026-06-11-19-46-16.gh-issue-150285.wuhAsL.rst
deleted file mode 100644
index 3f19150488f3131..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-11-19-46-16.gh-issue-150285.wuhAsL.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-:mod:`pydoc` now uses all available space (80 columns) for formatting reprs
-of module and class data, but ensure that they do not overflow.
diff --git a/Misc/NEWS.d/next/Library/2026-06-11-21-43-24.gh-issue-151337.JSVV18.rst b/Misc/NEWS.d/next/Library/2026-06-11-21-43-24.gh-issue-151337.JSVV18.rst
deleted file mode 100644
index 0344eee9471d292..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-11-21-43-24.gh-issue-151337.JSVV18.rst
+++ /dev/null
@@ -1 +0,0 @@
-Avoid possible memory leak in ``tkinter.c`` on Windows.
diff --git a/Misc/NEWS.d/next/Library/2026-06-12-00-00-00.gh-issue-151416.spawnUA.rst b/Misc/NEWS.d/next/Library/2026-06-12-00-00-00.gh-issue-151416.spawnUA.rst
deleted file mode 100644
index fd034d9885a8302..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-12-00-00-00.gh-issue-151416.spawnUA.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-Fix a crash in :func:`os.spawnv` and :func:`os.spawnve` when an *argv*
-item's :meth:`~os.PathLike.__fspath__` method mutates the *argv* list
-during argument conversion. :func:`!os.spawnv` argument conversion errors
-other than :exc:`TypeError`, such as the :exc:`ValueError` for an embedded
-null, are no longer replaced with a generic :exc:`TypeError`.
diff --git a/Misc/NEWS.d/next/Library/2026-06-12-00-04-34.gh-issue-151126.aHaBYq.rst b/Misc/NEWS.d/next/Library/2026-06-12-00-04-34.gh-issue-151126.aHaBYq.rst
deleted file mode 100644
index 20ef69d5de5ac55..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-12-00-04-34.gh-issue-151126.aHaBYq.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix crash on unset :exc:`MemoryError` on allocation failure in
-:func:`ctypes.get_errno`.
diff --git a/Misc/NEWS.d/next/Library/2026-06-12-00-17-29.gh-issue-151128.-LYO3a.rst b/Misc/NEWS.d/next/Library/2026-06-12-00-17-29.gh-issue-151128.-LYO3a.rst
deleted file mode 100644
index 6e760686af2b01f..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-12-00-17-29.gh-issue-151128.-LYO3a.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Cross-language keyword suggestions are now shown for :exc:`SyntaxError` messages.
-For example, ``switch x:`` suggests ``match``, ``delete x`` suggests ``del``,
-``function f():`` suggests ``def``. Contributed by Zang Langyan.
diff --git a/Misc/NEWS.d/next/Library/2026-06-12-07-20-08.gh-issue-151390.CmYN9EeJ.rst b/Misc/NEWS.d/next/Library/2026-06-12-07-20-08.gh-issue-151390.CmYN9EeJ.rst
deleted file mode 100644
index ff8de30599c6ad5..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-12-07-20-08.gh-issue-151390.CmYN9EeJ.rst
+++ /dev/null
@@ -1 +0,0 @@
-Colorize ``match`` in the :term:`REPL` when followed by a unary ``+`` or ``-`` operator. Patch by Bartosz Sławecki.
diff --git a/Misc/NEWS.d/next/Library/2026-06-12-22-46-31.gh-issue-151403.DalZWh.rst b/Misc/NEWS.d/next/Library/2026-06-12-22-46-31.gh-issue-151403.DalZWh.rst
deleted file mode 100644
index ca779ed684e7616..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-12-22-46-31.gh-issue-151403.DalZWh.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fixed a crash in :class:`subprocess.Popen` (and ``_posixsubprocess.fork_exec``)
-when an ``argv`` item's :meth:`~os.PathLike.__fspath__` concurrently mutates the
-``args`` sequence being converted.
diff --git a/Misc/NEWS.d/next/Library/2026-06-13-04-11-00.gh-issue-151426.f2V67e.rst b/Misc/NEWS.d/next/Library/2026-06-13-04-11-00.gh-issue-151426.f2V67e.rst
deleted file mode 100644
index 428302e5f847f36..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-13-04-11-00.gh-issue-151426.f2V67e.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Fix impossible stack traces (callers and callees cross called, orphans and
-incorrect lines) in the Tachyon profiler when caching frames, by snapshotting
-the stack chunks before walking the frame chain on a cache miss. Patch by
-Maurycy Pawłowski-Wieroński.
diff --git a/Misc/NEWS.d/next/Library/2026-06-13-11-57-48.gh-issue-151436.UEDowO.rst b/Misc/NEWS.d/next/Library/2026-06-13-11-57-48.gh-issue-151436.UEDowO.rst
deleted file mode 100644
index 6b10b03ba02fdf3..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-13-11-57-48.gh-issue-151436.UEDowO.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Fix skewed stack traces in the Tachyon profiler when caching is enabled and
-when generators and coroutines are profiled, by updating
-``tstate->last_profiled_frame`` at every frame-removal site. The issue resulted
-in total erasure of some callers. Patch by Maurycy Pawłowski-Wieroński.
diff --git a/Misc/NEWS.d/next/Library/2026-06-15-07-42-12.gh-issue-151485.NiYQPZ.rst b/Misc/NEWS.d/next/Library/2026-06-15-07-42-12.gh-issue-151485.NiYQPZ.rst
deleted file mode 100644
index 134499107ab2b78..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-15-07-42-12.gh-issue-151485.NiYQPZ.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fix command quoting in :exc:`subprocess.CalledProcessError`. Contributed by Benjy Wiener.
diff --git a/Misc/NEWS.d/next/Library/2026-06-15-15-32-36.gh-issue-151497.1cfmSV.rst b/Misc/NEWS.d/next/Library/2026-06-15-15-32-36.gh-issue-151497.1cfmSV.rst
deleted file mode 100644
index a4c03c9d71d7618..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-15-15-32-36.gh-issue-151497.1cfmSV.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Opening a :mod:`tarfile` archive no longer attempts to pre-allocate a huge
-buffer when a crafted or truncated member claims an oversized extended header
-(a GNU long name/link or a pax header). The extended header is now read in
-bounded chunks, so its size field can no longer trigger memory exhaustion.
diff --git a/Misc/NEWS.d/next/Library/2026-06-17-00-00-00.gh-issue-148660.odcopy.rst b/Misc/NEWS.d/next/Library/2026-06-17-00-00-00.gh-issue-148660.odcopy.rst
deleted file mode 100644
index 30c2e366ca2ba07..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-17-00-00-00.gh-issue-148660.odcopy.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix a crash in :meth:`!collections.OrderedDict.copy` when a key's
-``__eq__`` or a subclass method mutates the dict during the copy. Now
-raises :exc:`RuntimeError` instead, as iteration does.
diff --git a/Misc/NEWS.d/next/Library/2026-06-17-22-31-57.gh-issue-151613.n0nua1.rst b/Misc/NEWS.d/next/Library/2026-06-17-22-31-57.gh-issue-151613.n0nua1.rst
deleted file mode 100644
index fbf3ce47ff2739f..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-17-22-31-57.gh-issue-151613.n0nua1.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix another way the Tachyon profiler frame cache could produce impossible
-mixed stack traces when ``_PyInterpreterFrame`` addresses are reused, by
-validating cached frame anchors with a sequence counter.
diff --git a/Misc/NEWS.d/next/Library/2026-06-18-00-39-58.gh-issue-151615.PBsCE1.rst b/Misc/NEWS.d/next/Library/2026-06-18-00-39-58.gh-issue-151615.PBsCE1.rst
deleted file mode 100644
index 1d08dbacef1f79b..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-18-00-39-58.gh-issue-151615.PBsCE1.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix :mod:`asyncio` servers repeatedly logging and rescheduling on a single
-event loop iteration when ``accept()`` fails with a resource errors.
diff --git a/Misc/NEWS.d/next/Library/2026-06-18-12-48-03.gh-issue-151640.R4c3Fx.rst b/Misc/NEWS.d/next/Library/2026-06-18-12-48-03.gh-issue-151640.R4c3Fx.rst
deleted file mode 100644
index ef61a7d27dd07dd..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-18-12-48-03.gh-issue-151640.R4c3Fx.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix a data race in :class:`io.BytesIO` in free-threaded builds when
-whole-buffer reads or peeks, or :meth:`~io.BytesIO.getvalue`, share the
-internal buffer with concurrent writes.
diff --git a/Misc/NEWS.d/next/Library/2026-06-18-23-59-46.gh-issue-151596.5ma144.rst b/Misc/NEWS.d/next/Library/2026-06-18-23-59-46.gh-issue-151596.5ma144.rst
deleted file mode 100644
index 17ec1341142e93d..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-18-23-59-46.gh-issue-151596.5ma144.rst
+++ /dev/null
@@ -1 +0,0 @@
-Add missing ``size`` positional argument to the pure-Python implementation of :meth:`io.TextIOBase.readline`.
diff --git a/Misc/NEWS.d/next/Library/2026-06-19-07-26-20.gh-issue-151695.IBDlkN.rst b/Misc/NEWS.d/next/Library/2026-06-19-07-26-20.gh-issue-151695.IBDlkN.rst
deleted file mode 100644
index f44cb6b93071656..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-19-07-26-20.gh-issue-151695.IBDlkN.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Fix a use-after-free in the :mod:`curses` module. The encoding of the initial
-screen, used by :func:`curses.unctrl` and :func:`curses.ungetch` to encode
-non-ASCII characters, is now kept as a private copy instead of a borrowed
-pointer to a window object that may be deallocated.
diff --git a/Misc/NEWS.d/next/Library/2026-06-19-12-00-00.gh-issue-151674.FCYTvs.rst b/Misc/NEWS.d/next/Library/2026-06-19-12-00-00.gh-issue-151674.FCYTvs.rst
deleted file mode 100644
index 84e21d4cbc4bd72..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-19-12-00-00.gh-issue-151674.FCYTvs.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Add the :meth:`~tkinter.Text.edit_canundo` and :meth:`~tkinter.Text.edit_canredo`
-methods of :class:`!tkinter.Text`, wrapping the Tk ``edit canundo`` and
-``edit canredo`` subcommands.
diff --git a/Misc/NEWS.d/next/Library/2026-06-19-12-00-01.gh-issue-151675.acLD7L.rst b/Misc/NEWS.d/next/Library/2026-06-19-12-00-01.gh-issue-151675.acLD7L.rst
deleted file mode 100644
index 92bd69de6bdc0ec..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-19-12-00-01.gh-issue-151675.acLD7L.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Add the :meth:`~tkinter.Text.sync` and :meth:`~tkinter.Text.pendingsync`
-methods of :class:`!tkinter.Text`, wrapping the Tk ``sync`` and
-``pendingsync`` subcommands.
diff --git a/Misc/NEWS.d/next/Library/2026-06-19-12-19-30.gh-issue-90092.yBVc0C.rst b/Misc/NEWS.d/next/Library/2026-06-19-12-19-30.gh-issue-90092.yBVc0C.rst
deleted file mode 100644
index 41e0ce80ee8a069..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-19-12-19-30.gh-issue-90092.yBVc0C.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Add support for multiple terminals to the :mod:`curses` module: the new
-functions :func:`curses.newterm`, :func:`curses.set_term` and
-:func:`curses.new_prescr`, the corresponding :ref:`screen
-` object, and the :meth:`curses.window.use` method.
diff --git a/Misc/NEWS.d/next/Library/2026-06-19-18-40-00.gh-issue-151744.Kp7mNq.rst b/Misc/NEWS.d/next/Library/2026-06-19-18-40-00.gh-issue-151744.Kp7mNq.rst
deleted file mode 100644
index 24328a8f9f93427..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-19-18-40-00.gh-issue-151744.Kp7mNq.rst
+++ /dev/null
@@ -1 +0,0 @@
-Add :func:`curses.nofilter`, which undoes the effect of :func:`curses.filter`.
diff --git a/Misc/NEWS.d/next/Library/2026-06-20-02-14-55.gh-issue-151757.TP9A2x.rst b/Misc/NEWS.d/next/Library/2026-06-20-02-14-55.gh-issue-151757.TP9A2x.rst
deleted file mode 100644
index ee1aa3eff6f0c2f..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-20-02-14-55.gh-issue-151757.TP9A2x.rst
+++ /dev/null
@@ -1,9 +0,0 @@
-The :mod:`curses` character-cell window methods now accept a full character
-cell -- a spacing character optionally followed by combining characters -- in
-addition to a single integer or byte character. Add the wide-character read
-methods :meth:`curses.window.get_wstr` and :meth:`curses.window.in_wstr`, and
-the functions :func:`curses.erasewchar`, :func:`curses.killwchar` and
-:func:`curses.wunctrl`. On a narrow (non-ncursesw) build the character cell
-holds a single character without combining marks, representable as one byte in
-the window's encoding, and :meth:`curses.window.in_wstr` returns its decoded
-text.
diff --git a/Misc/NEWS.d/next/Library/2026-06-20-11-11-22.gh-issue-151774.O6nrvs.rst b/Misc/NEWS.d/next/Library/2026-06-20-11-11-22.gh-issue-151774.O6nrvs.rst
deleted file mode 100644
index 668b01ebfb8ad79..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-20-11-11-22.gh-issue-151774.O6nrvs.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-Add the :mod:`curses` functions :func:`curses.alloc_pair`,
-:func:`curses.find_pair`, :func:`curses.free_pair` and
-:func:`curses.reset_color_pairs` for dynamic color-pair management. They are
-only available when Python is built against a wide-character version of the
-underlying curses library with extended-color support.
diff --git a/Misc/NEWS.d/next/Library/2026-06-20-12-10-02.gh-issue-151776.BtsXIF.rst b/Misc/NEWS.d/next/Library/2026-06-20-12-10-02.gh-issue-151776.BtsXIF.rst
deleted file mode 100644
index 3eabc4a6bea82b5..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-20-12-10-02.gh-issue-151776.BtsXIF.rst
+++ /dev/null
@@ -1,12 +0,0 @@
-Add :mod:`curses` functions and window methods that report state which could
-previously only be set: the window methods :meth:`~curses.window.is_cleared`,
-:meth:`~curses.window.is_idcok`, :meth:`~curses.window.is_idlok`,
-:meth:`~curses.window.is_immedok`, :meth:`~curses.window.is_keypad`,
-:meth:`~curses.window.is_leaveok`, :meth:`~curses.window.is_nodelay`,
-:meth:`~curses.window.is_notimeout`, :meth:`~curses.window.is_pad`,
-:meth:`~curses.window.is_scrollok`, :meth:`~curses.window.is_subwin`,
-:meth:`~curses.window.is_syncok`, :meth:`~curses.window.getdelay`,
-:meth:`~curses.window.getparent` and :meth:`~curses.window.getscrreg`, and the
-functions :func:`curses.is_cbreak`, :func:`curses.is_echo`,
-:func:`curses.is_nl` and :func:`curses.is_raw`. They are only available when
-built against an ncurses with ``NCURSES_EXT_FUNCS``.
diff --git a/Misc/NEWS.d/next/Library/2026-06-20-15-00-00.gh-issue-151770.dtiso0.rst b/Misc/NEWS.d/next/Library/2026-06-20-15-00-00.gh-issue-151770.dtiso0.rst
deleted file mode 100644
index 10b3db8efa42b0f..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-20-15-00-00.gh-issue-151770.dtiso0.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix :meth:`datetime.datetime.fromisoformat` raising :exc:`AssertionError`
-instead of :exc:`ValueError` for an out-of-range month combined with a
-``24:00`` time.
diff --git a/Misc/NEWS.d/next/Library/2026-06-20-15-00-00.gh-issue-75666.Kt9xQ2.rst b/Misc/NEWS.d/next/Library/2026-06-20-15-00-00.gh-issue-75666.Kt9xQ2.rst
deleted file mode 100644
index d2b2b066837bb1f..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-20-15-00-00.gh-issue-75666.Kt9xQ2.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix a reference leak in :mod:`tkinter`: the Tcl commands created for event
-callbacks are now deleted when a binding is replaced or unbound.
diff --git a/Misc/NEWS.d/next/Library/2026-06-20-21-15-13.gh-issue-151814.OIbgsO.rst b/Misc/NEWS.d/next/Library/2026-06-20-21-15-13.gh-issue-151814.OIbgsO.rst
deleted file mode 100644
index 1365fb4d8edb1d2..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-20-21-15-13.gh-issue-151814.OIbgsO.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix unbounded memory growth in :class:`io.TextIOWrapper` when repeatedly
-writing an empty string.
diff --git a/Misc/NEWS.d/next/Library/2026-06-20-22-55-22.gh-issue-59396.kT9wPq.rst b/Misc/NEWS.d/next/Library/2026-06-20-22-55-22.gh-issue-59396.kT9wPq.rst
deleted file mode 100644
index 550620a9c8276cb..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-20-22-55-22.gh-issue-59396.kT9wPq.rst
+++ /dev/null
@@ -1,22 +0,0 @@
-The :mod:`tkinter.simpledialog` dialogs were modernized to match the look and
-feel of the native Tk dialogs.
-:class:`!tkinter.simpledialog.SimpleDialog` and the
-:func:`~tkinter.simpledialog.askinteger`,
-:func:`~tkinter.simpledialog.askfloat` and
-:func:`~tkinter.simpledialog.askstring` dialogs are now built from
-the themed :mod:`tkinter.ttk` widgets instead of the classic :mod:`tkinter`
-widgets; the :class:`!tkinter.simpledialog.Dialog` base class still defaults to
-the classic widgets for compatibility. Both :class:`!Dialog` and
-:class:`!SimpleDialog` gained a *use_ttk*
-parameter that selects between the classic Tk widgets and the themed ttk
-widgets. :class:`!SimpleDialog` also gained *bitmap* and *detail* parameters,
-draws the standard icons with themed images in the ttk version, and accepts
-mappings of button options as *buttons* entries, where an ``underline`` option
-adds an :kbd:`Alt` key accelerator.
-The font and wrap length of the message and the detail message are taken from
-the Tk option database and can be overridden by the application.
-The dialogs also follow the keyboard conventions of the Tk message box: the
-default ring follows the keyboard focus, the Return key activates the focused
-button, and the :class:`!Dialog` OK and Cancel buttons gained :kbd:`Alt` key
-accelerators.
-Several bugs were also fixed.
diff --git a/Misc/NEWS.d/next/Library/2026-06-21-15-50-24.gh-issue-86165.dyac1G.rst b/Misc/NEWS.d/next/Library/2026-06-21-15-50-24.gh-issue-86165.dyac1G.rst
deleted file mode 100644
index 0b630e9ae346834..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-21-15-50-24.gh-issue-86165.dyac1G.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix :func:`imaplib.Time2Internaldate` to use the local timezone offset for
-``time.struct_time`` values with ``tm_gmtoff`` set to ``None``, as returned by
-``datetime.datetime.timetuple()``. Contributed by Xiao Yuan.
diff --git a/Misc/NEWS.d/next/Library/2026-06-21-23-17-12.gh-issue-59396.Fd9Tk2.rst b/Misc/NEWS.d/next/Library/2026-06-21-23-17-12.gh-issue-59396.Fd9Tk2.rst
deleted file mode 100644
index 890a29cb7adf95d..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-21-23-17-12.gh-issue-59396.Fd9Tk2.rst
+++ /dev/null
@@ -1,14 +0,0 @@
-The :class:`!tkinter.filedialog.FileDialog` dialog and its
-:class:`!tkinter.filedialog.LoadFileDialog` and
-:class:`!tkinter.filedialog.SaveFileDialog` subclasses, which follow the layout
-of the classic Motif file selection dialog, were modernized to match its look
-and feel more closely.
-They are now built from the themed :mod:`tkinter.ttk` widgets instead of the
-classic :mod:`tkinter` widgets, and gained a *use_ttk* parameter that selects
-between the classic Tk widgets and the themed ttk widgets.
-The buttons and field labels gained :kbd:`Alt` key accelerators, the default
-ring follows the keyboard focus, and the :kbd:`Escape` key cancels the dialog.
-The directory and file lists gained a horizontal scrollbar and type-ahead
-selection.
-The dialog is now centered over its parent, and the overwrite confirmation of
-:class:`!SaveFileDialog` uses a themed message box.
diff --git a/Misc/NEWS.d/next/Library/2026-06-22-00-46-57.gh-issue-151874.8VtTrq.rst b/Misc/NEWS.d/next/Library/2026-06-22-00-46-57.gh-issue-151874.8VtTrq.rst
deleted file mode 100644
index 50a33f5be809871..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-22-00-46-57.gh-issue-151874.8VtTrq.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Add the :mod:`tkinter` methods :meth:`!Misc.winfo_isdark`,
-:meth:`!Wm.wm_iconbadge` and :meth:`!Wm.wm_stackorder`, wrapping the
-``winfo isdark``, ``wm iconbadge`` and ``wm stackorder`` Tk commands.
diff --git a/Misc/NEWS.d/next/Library/2026-06-22-00-55-07.gh-issue-151876.sVe0xx.rst b/Misc/NEWS.d/next/Library/2026-06-22-00-55-07.gh-issue-151876.sVe0xx.rst
deleted file mode 100644
index 9dc5f2327cf4155..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-22-00-55-07.gh-issue-151876.sVe0xx.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Add the :class:`tkinter.Canvas` methods :meth:`!rchars` and :meth:`!rotate`,
-wrapping the ``rchars`` and ``rotate`` Tk canvas commands.
diff --git a/Misc/NEWS.d/next/Library/2026-06-22-01-02-33.gh-issue-151878.IFIA5C.rst b/Misc/NEWS.d/next/Library/2026-06-22-01-02-33.gh-issue-151878.IFIA5C.rst
deleted file mode 100644
index af0d2c25136c452..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-22-01-02-33.gh-issue-151878.IFIA5C.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Add the :meth:`!validate` method to the :class:`tkinter.Entry` and
-:class:`tkinter.Spinbox` widgets, forcing an evaluation of the validation
-command.
diff --git a/Misc/NEWS.d/next/Library/2026-06-22-01-39-38.gh-issue-151881.ShACSZ.rst b/Misc/NEWS.d/next/Library/2026-06-22-01-39-38.gh-issue-151881.ShACSZ.rst
deleted file mode 100644
index 9ae939438e826f6..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-22-01-39-38.gh-issue-151881.ShACSZ.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Add the :meth:`tkinter.Menu.postcascade` method and the
-:meth:`!tkinter.Misc.tk_scaling` and :meth:`!tkinter.Misc.tk_inactive`
-methods, wrapping the ``postcascade``, ``tk scaling`` and ``tk inactive``
-Tk commands.
diff --git a/Misc/NEWS.d/next/Library/2026-06-22-01-51-06.gh-issue-151886.MsLlNz.rst b/Misc/NEWS.d/next/Library/2026-06-22-01-51-06.gh-issue-151886.MsLlNz.rst
deleted file mode 100644
index 7a454ab95f371f1..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-22-01-51-06.gh-issue-151886.MsLlNz.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Add the :meth:`!tkinter.Misc.tk_appname`,
-:meth:`!tkinter.Misc.tk_useinputmethods` and :meth:`!tkinter.Misc.tk_caret`
-methods, wrapping the ``tk appname``, ``tk useinputmethods`` and ``tk caret``
-Tk commands.
diff --git a/Misc/NEWS.d/next/Library/2026-06-22-01-57-55.gh-issue-151888.hO7mxi.rst b/Misc/NEWS.d/next/Library/2026-06-22-01-57-55.gh-issue-151888.hO7mxi.rst
deleted file mode 100644
index 8a2d5ed765d234e..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-22-01-57-55.gh-issue-151888.hO7mxi.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Add the :meth:`!tkinter.PhotoImage.redither` method, wrapping the photo image
-``redither`` Tk command.
diff --git a/Misc/NEWS.d/next/Library/2026-06-22-02-29-02.gh-issue-151890.gT6JwI.rst b/Misc/NEWS.d/next/Library/2026-06-22-02-29-02.gh-issue-151890.gT6JwI.rst
deleted file mode 100644
index 3e064aeeba8131c..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-22-02-29-02.gh-issue-151890.gT6JwI.rst
+++ /dev/null
@@ -1,6 +0,0 @@
-Add the *format* parameter to the :meth:`tkinter.PhotoImage.put` method, the
-*metadata* parameter to the :meth:`~tkinter.PhotoImage.put`,
-:meth:`~tkinter.PhotoImage.read`, :meth:`~tkinter.PhotoImage.write` and
-:meth:`~tkinter.PhotoImage.data` methods, and the *withalpha* parameter to the
-:meth:`~tkinter.PhotoImage.get` method. The *metadata* and *withalpha*
-parameters require Tcl/Tk 9.0 or newer.
diff --git a/Misc/NEWS.d/next/Library/2026-06-22-10-30-22.gh-issue-151910.ayi8xK.rst b/Misc/NEWS.d/next/Library/2026-06-22-10-30-22.gh-issue-151910.ayi8xK.rst
deleted file mode 100644
index 3e5647cbf835490..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-22-10-30-22.gh-issue-151910.ayi8xK.rst
+++ /dev/null
@@ -1,6 +0,0 @@
-Added :class:`tkinter.ttk.Treeview` methods wrapping the enhanced
-``ttk::treeview`` widget commands added in Tk 9.1 (and the ``detached`` query
-added in Tk 9.0): item navigation and queries, opening, hiding, sorting and
-searching of items, and cell focus, selection and tagging. The
-:meth:`~tkinter.ttk.Treeview.expand` and :meth:`~tkinter.ttk.Treeview.collapse`
-methods (without recursion) also work on Tk older than 9.1.
diff --git a/Misc/NEWS.d/next/Library/2026-06-22-12-00-00.gh-issue-95555.Pr0p18.rst b/Misc/NEWS.d/next/Library/2026-06-22-12-00-00.gh-issue-95555.Pr0p18.rst
deleted file mode 100644
index fa792cae5ec0761..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-22-12-00-00.gh-issue-95555.Pr0p18.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Regular expressions now support Unicode property escapes ``\p{...}`` and
-``\P{...}`` for properties that the engine can resolve without the unicodedata
-database: many ``General_Category`` values, a number of binary properties, the
-POSIX compatibility classes, and properties derivable from the code point.
diff --git a/Misc/NEWS.d/next/Library/2026-06-22-14-30-00.gh-issue-151920.Th3mSt.rst b/Misc/NEWS.d/next/Library/2026-06-22-14-30-00.gh-issue-151920.Th3mSt.rst
deleted file mode 100644
index 2c4a069a794b10e..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-22-14-30-00.gh-issue-151920.Th3mSt.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Add the :meth:`ttk.Style.theme_styles `
-method, wrapping the Tk ``ttk::style theme styles`` subcommand, which
-returns the list of styles defined in a theme.
diff --git a/Misc/NEWS.d/next/Library/2026-06-22-18-01-00.gh-issue-151955.6u5iwm.rst b/Misc/NEWS.d/next/Library/2026-06-22-18-01-00.gh-issue-151955.6u5iwm.rst
deleted file mode 100644
index 4cb5f04025327c4..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-22-18-01-00.gh-issue-151955.6u5iwm.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Allow more types to be used in the ``bound`` argument to
-:class:`typing.ParamSpec` and :class:`typing.TypeVarTuple`.
diff --git a/Misc/NEWS.d/next/Library/2026-06-23-11-00-03.gh-issue-143070.fV5w7s.rst b/Misc/NEWS.d/next/Library/2026-06-23-11-00-03.gh-issue-143070.fV5w7s.rst
deleted file mode 100644
index 51c2dc3d51bc865..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-23-11-00-03.gh-issue-143070.fV5w7s.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Automatically generated :mod:`tkinter` widget names now start with ``"+"``
-instead of ``"!"``, so that they can be used as tags in the
-:class:`!tkinter.Canvas` and :class:`!tkinter.Text` widgets.
diff --git a/Misc/NEWS.d/next/Library/2026-06-23-12-00-00.gh-issue-101284.Ab3Xy9.rst b/Misc/NEWS.d/next/Library/2026-06-23-12-00-00.gh-issue-101284.Ab3Xy9.rst
deleted file mode 100644
index 9afcf8dcf545ed5..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-23-12-00-00.gh-issue-101284.Ab3Xy9.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-:class:`tkinter.OptionMenu` now accepts arbitrary :class:`!tkinter.Menubutton`
-options as keyword arguments and uses them to override its default appearance.
diff --git a/Misc/NEWS.d/next/Library/2026-06-23-13-27-14.gh-issue-126219.kOfv2g.rst b/Misc/NEWS.d/next/Library/2026-06-23-13-27-14.gh-issue-126219.kOfv2g.rst
deleted file mode 100644
index 8cc8c64c719471d..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-23-13-27-14.gh-issue-126219.kOfv2g.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fixed a crash in :class:`tkinter.Tk` when *className* contains a non-BMP
-character and tkinter is built against Tcl/Tk 8.x. Such a name is now
-rejected with a :exc:`ValueError`.
diff --git a/Misc/NEWS.d/next/Library/2026-06-23-17-14-04.gh-issue-127802.nGSxo6.rst b/Misc/NEWS.d/next/Library/2026-06-23-17-14-04.gh-issue-127802.nGSxo6.rst
deleted file mode 100644
index 9484c9dbd23b2fa..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-23-17-14-04.gh-issue-127802.nGSxo6.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-The deprecated :class:`tkinter.Variable` methods :meth:`!trace_variable`,
-:meth:`!trace`, :meth:`!trace_vdelete` and :meth:`!trace_vinfo` are now
-scheduled for removal in Python 3.17.
diff --git a/Misc/NEWS.d/next/Library/2026-06-23-18-42-37.gh-issue-143990.o65v7O.rst b/Misc/NEWS.d/next/Library/2026-06-23-18-42-37.gh-issue-143990.o65v7O.rst
deleted file mode 100644
index c464f81a6bb2547..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-23-18-42-37.gh-issue-143990.o65v7O.rst
+++ /dev/null
@@ -1,6 +0,0 @@
-:class:`tkinter.font.Font` can now wrap a font description without creating a
-new named font, by passing it as *font* with ``exists=True`` and no *name*.
-This avoids a loss of precision in :meth:`~tkinter.font.Font.actual`,
-:meth:`~tkinter.font.Font.measure` and :meth:`~tkinter.font.Font.metrics`.
-Keyword options now override the corresponding settings of the given *font*
-instead of being ignored.
diff --git a/Misc/NEWS.d/next/Library/2026-06-23-22-15-00.gh-issue-152033.Ct1Egy.rst b/Misc/NEWS.d/next/Library/2026-06-23-22-15-00.gh-issue-152033.Ct1Egy.rst
deleted file mode 100644
index 7c54a6c16c1a145..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-23-22-15-00.gh-issue-152033.Ct1Egy.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-Optimize matching of character class escapes (``\d``, ``\D``, ``\s``,
-``\S``, ``\w`` and ``\W``) that occur outside a character set: they are now
-compiled to a single ``CATEGORY`` opcode instead of being wrapped in an
-``IN`` block. This speeds up patterns such as ``\d+`` and reduces the size
-of the compiled byte code.
diff --git a/Misc/NEWS.d/next/Library/2026-06-24-10-30-00.gh-issue-152056.Qk7mZ2.rst b/Misc/NEWS.d/next/Library/2026-06-24-10-30-00.gh-issue-152056.Qk7mZ2.rst
deleted file mode 100644
index 6e71d720cd19be2..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-24-10-30-00.gh-issue-152056.Qk7mZ2.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-Optimize matching of a character set that contains a single character
-category, such as ``[\d]`` or ``[^\s]``: it is now compiled to a single
-``CATEGORY`` opcode, the same as the corresponding ``\d`` or ``\S`` escape,
-instead of being wrapped in an ``IN`` block. This speeds up matching and
-reduces the size of the compiled byte code. Patch by Pieter Eendebak.
diff --git a/Misc/NEWS.d/next/Library/2026-06-24-10-46-35.gh-issue-152060.f2asrt.rst b/Misc/NEWS.d/next/Library/2026-06-24-10-46-35.gh-issue-152060.f2asrt.rst
deleted file mode 100644
index 6088a6b80829bb4..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-24-10-46-35.gh-issue-152060.f2asrt.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix :meth:`datetime.datetime.fromisoformat` raising :exc:`AssertionError`
-instead of :exc:`ValueError` for some malformed strings in the pure-Python
-implementation, matching the C implementation.
diff --git a/Misc/NEWS.d/next/Library/2026-06-24-12-00-00.gh-issue-152052.yBssDE.rst b/Misc/NEWS.d/next/Library/2026-06-24-12-00-00.gh-issue-152052.yBssDE.rst
deleted file mode 100644
index f9ffbbd342fc81a..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-24-12-00-00.gh-issue-152052.yBssDE.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-The :mod:`json` C accelerator now correctly reports an unterminated string for a
-``\uXXXX`` escape at the end of the input.
diff --git a/Misc/NEWS.d/next/Library/2026-06-24-12-00-00.gh-issue-152079.f1tzus.rst b/Misc/NEWS.d/next/Library/2026-06-24-12-00-00.gh-issue-152079.f1tzus.rst
deleted file mode 100644
index 492d00724f6a46e..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-24-12-00-00.gh-issue-152079.f1tzus.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix :meth:`datetime.datetime.fromisoformat` in the C implementation dropping
-the sub-second part of a UTC offset whose whole-second part is zero, matching
-the pure-Python implementation.
diff --git a/Misc/NEWS.d/next/Library/2026-06-24-12-00-00.gh-issue-152100.Set0ps.rst b/Misc/NEWS.d/next/Library/2026-06-24-12-00-00.gh-issue-152100.Set0ps.rst
deleted file mode 100644
index 848740ed7a56d31..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-24-12-00-00.gh-issue-152100.Set0ps.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Support set operations and nested sets in regular expression character
-classes, as described in Unicode Technical Standard #18: set difference
-(``[A--B]``), intersection (``[A&&B]``) and union (``[A||B]``).
diff --git a/Misc/NEWS.d/next/Library/2026-06-24-16-08-44.gh-issue-152074.PsbS-I.rst b/Misc/NEWS.d/next/Library/2026-06-24-16-08-44.gh-issue-152074.PsbS-I.rst
deleted file mode 100644
index 05e61670582dd8b..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-24-16-08-44.gh-issue-152074.PsbS-I.rst
+++ /dev/null
@@ -1 +0,0 @@
-Increase the buffer size to 256 KiB in :meth:`asyncio.loop.sendfile` method fallback.
diff --git a/Misc/NEWS.d/next/Library/2026-06-24-16-40-15.gh-issue-151378.iYWa_6.rst b/Misc/NEWS.d/next/Library/2026-06-24-16-40-15.gh-issue-151378.iYWa_6.rst
deleted file mode 100644
index 0b3eb860ba8d329..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-24-16-40-15.gh-issue-151378.iYWa_6.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix a bug in the binary collector in Tachyon that caused unbounded memory
-growth while profiling a thread that stayed asleep. Patch by Maurycy
-Pawłowski-Wieroński.
diff --git a/Misc/NEWS.d/next/Library/2026-06-24-22-16-35.gh-issue-105895.hRkuEw.rst b/Misc/NEWS.d/next/Library/2026-06-24-22-16-35.gh-issue-105895.hRkuEw.rst
deleted file mode 100644
index c69e6fa7d14f4dc..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-24-22-16-35.gh-issue-105895.hRkuEw.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Add :keyword:`match` and :keyword:`case` to the list of supported topics by
-:func:`help`.
diff --git a/Misc/NEWS.d/next/Library/2026-06-24-23-28-42.gh-issue-151669.tPUavQ.rst b/Misc/NEWS.d/next/Library/2026-06-24-23-28-42.gh-issue-151669.tPUavQ.rst
deleted file mode 100644
index d8e4850ba94e140..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-24-23-28-42.gh-issue-151669.tPUavQ.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-On Windows, when populating tar archives from filesystem content, to
-conform to the tar format standard, backslashes in symlink targets are
-be replaced by slashes.
diff --git a/Misc/NEWS.d/next/Library/2026-06-25-01-00-43.gh-issue-151763.wWeHBe.rst b/Misc/NEWS.d/next/Library/2026-06-25-01-00-43.gh-issue-151763.wWeHBe.rst
deleted file mode 100644
index 2f5e84027ad31bb..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-25-01-00-43.gh-issue-151763.wWeHBe.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix crash in :func:`!_interpqueues.create` whe :exc:`MemoryError`
-happens on queue creation.
diff --git a/Misc/NEWS.d/next/Library/2026-06-25-07-08-17.gh-issue-152157.dt5Ef0.rst b/Misc/NEWS.d/next/Library/2026-06-25-07-08-17.gh-issue-152157.dt5Ef0.rst
deleted file mode 100644
index 00e83b4af6be7a9..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-25-07-08-17.gh-issue-152157.dt5Ef0.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-The C implementations of :meth:`~datetime.datetime.fromisoformat` and :meth:`~datetime.time.fromisoformat`
-now reject a decimal separator that is not followed by any
-fractional digit before a timezone designator.
diff --git a/Misc/NEWS.d/next/Library/2026-06-25-10-07-54.gh-issue-152156.gscPU9.rst b/Misc/NEWS.d/next/Library/2026-06-25-10-07-54.gh-issue-152156.gscPU9.rst
deleted file mode 100644
index 30e561274dc50c2..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-25-10-07-54.gh-issue-152156.gscPU9.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix a possible crash in :func:`concurrent.interpreters.create` under limited
-memory conditions.
diff --git a/Misc/NEWS.d/next/Library/2026-06-25-12-00-00.gh-issue-152212.Zk7Qm2.rst b/Misc/NEWS.d/next/Library/2026-06-25-12-00-00.gh-issue-152212.Zk7Qm2.rst
deleted file mode 100644
index 2b1d272638b11ab..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-25-12-00-00.gh-issue-152212.Zk7Qm2.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix the pure-Python :mod:`zoneinfo` parser accepting a POSIX TZ string with a
-``std`` abbreviation but no offset. This is invalid per POSIX and now
-raises :exc:`ValueError`, matching the C accelerator. Patch by tonghuaroot.
diff --git a/Misc/NEWS.d/next/Library/2026-06-25-14-32-42.gh-issue-139145.kT9rmP.rst b/Misc/NEWS.d/next/Library/2026-06-25-14-32-42.gh-issue-139145.kT9rmP.rst
deleted file mode 100644
index 3fa639c5f727baa..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-25-14-32-42.gh-issue-139145.kT9rmP.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-Fix a busy loop in :mod:`tkinter` on interactive Python. When a Tcl command
-running its own event loop (such as ``vwait`` or :meth:`!wait_variable`) was
-active and input arrived on stdin, the event loop kept spinning at 100% CPU.
-The stdin file handler is now removed as soon as input is available. Based on
-a patch by Michiel de Hoon.
diff --git a/Misc/NEWS.d/next/Library/2026-06-25-14-32-43.gh-issue-139816.Lq2vXa.rst b/Misc/NEWS.d/next/Library/2026-06-25-14-32-43.gh-issue-139816.Lq2vXa.rst
deleted file mode 100644
index b180dee686caf8c..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-25-14-32-43.gh-issue-139816.Lq2vXa.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Fix a hang in :mod:`tkinter` on interactive Python built without
-:mod:`readline`. An exception raised in a callback no longer causes the
-event loop to stop and wait for the user to press Enter; pending callbacks
-now keep running until input is actually available on stdin.
diff --git a/Misc/NEWS.d/next/Library/2026-06-25-19-44-16.gh-issue-152219.ndj4Ib.rst b/Misc/NEWS.d/next/Library/2026-06-25-19-44-16.gh-issue-152219.ndj4Ib.rst
deleted file mode 100644
index e7ea6011cb7b50c..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-25-19-44-16.gh-issue-152219.ndj4Ib.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-Add the :mod:`curses` window methods :meth:`~curses.window.attr_get`,
-:meth:`~curses.window.attr_set`, :meth:`~curses.window.attr_on`,
-:meth:`~curses.window.attr_off` and :meth:`~curses.window.color_set`, which use
-a separate color pair argument instead of packing it into the attribute value,
-and the corresponding ``WA_*`` attribute constants.
diff --git a/Misc/NEWS.d/next/Library/2026-06-25-20-00-00.gh-issue-151496.kMnT3x.rst b/Misc/NEWS.d/next/Library/2026-06-25-20-00-00.gh-issue-151496.kMnT3x.rst
deleted file mode 100644
index 994e5dadcf2e8a0..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-25-20-00-00.gh-issue-151496.kMnT3x.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fixed ``profiling.sampling --gecko`` with ``--async-aware`` by flattening
-async task stacks before generating Gecko samples. ``--binary`` now rejects
-``--async-aware`` until the binary format supports async task data.
diff --git a/Misc/NEWS.d/next/Library/2026-06-25-22-19-04.gh-issue-152099.L7fKq9.rst b/Misc/NEWS.d/next/Library/2026-06-25-22-19-04.gh-issue-152099.L7fKq9.rst
deleted file mode 100644
index 05e760bcf6ed6d3..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-25-22-19-04.gh-issue-152099.L7fKq9.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-``asyncio``'s ``loop.sendfile(..., fallback=False)`` now consistently raises
-:exc:`asyncio.SendfileNotAvailableError` for fallback-only transports, such as
-SSL/TLS transports, when native sendfile cannot be used. Previously, this case
-raised :exc:`RuntimeError`.
diff --git a/Misc/NEWS.d/next/Library/2026-06-25-22-41-49.gh-issue-152233.pEhm3q.rst b/Misc/NEWS.d/next/Library/2026-06-25-22-41-49.gh-issue-152233.pEhm3q.rst
deleted file mode 100644
index 43895aafe6ce136..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-25-22-41-49.gh-issue-152233.pEhm3q.rst
+++ /dev/null
@@ -1,9 +0,0 @@
-Add the :class:`curses.complexchar` type, representing a styled character
-cell (text, attributes and color pair), and the :mod:`curses` window methods
-:meth:`~curses.window.in_wch` and :meth:`~curses.window.getbkgrnd` that return
-one. The character-cell methods (:meth:`~curses.window.addch`,
-:meth:`~curses.window.bkgd`, :meth:`~curses.window.border`,
-:meth:`~curses.window.hline` and others) now also accept a
-:class:`~curses.complexchar`. This works whether or not Python was built
-against a wide-character-aware curses library; on a narrow build a cell holds a
-single character representable as one byte in the window's encoding.
diff --git a/Misc/NEWS.d/next/Library/2026-06-26-11-20-00.gh-issue-152233.Kp7mQ2.rst b/Misc/NEWS.d/next/Library/2026-06-26-11-20-00.gh-issue-152233.Kp7mQ2.rst
deleted file mode 100644
index b905b512a8a12af..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-26-11-20-00.gh-issue-152233.Kp7mQ2.rst
+++ /dev/null
@@ -1,8 +0,0 @@
-Add the :class:`curses.complexstr` type, an immutable string of styled
-character cells (the counterpart of :class:`curses.complexchar`), and the
-:mod:`curses` window method :meth:`~curses.window.in_wchstr` that returns one.
-The string-cell methods :meth:`~curses.window.addstr`,
-:meth:`~curses.window.addnstr`, :meth:`~curses.window.insstr` and
-:meth:`~curses.window.insnstr` now also accept a :class:`~curses.complexstr`.
-Like :class:`curses.complexchar`, it works whether or not Python was built
-against a wide-character-aware curses library.
diff --git a/Misc/NEWS.d/next/Library/2026-06-26-12-50-26.gh-issue-152246.MfXMd1.rst b/Misc/NEWS.d/next/Library/2026-06-26-12-50-26.gh-issue-152246.MfXMd1.rst
deleted file mode 100644
index 0858199a9fa2798..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-26-12-50-26.gh-issue-152246.MfXMd1.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix the pure-Python :mod:`zoneinfo` parser accepting an invalid POSIX TZ
-transition rule with a non-period separator. Patch by tonghuaroot.
diff --git a/Misc/NEWS.d/next/Library/2026-06-26-13-10-00.gh-issue-80937.Hq3mNp.rst b/Misc/NEWS.d/next/Library/2026-06-26-13-10-00.gh-issue-80937.Hq3mNp.rst
deleted file mode 100644
index 4ea0179c6586d4f..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-26-13-10-00.gh-issue-80937.Hq3mNp.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Fix a memory leak in :mod:`tkinter` when a Tcl command created with
-``createcommand`` was not explicitly removed before the interpreter was
-deleted. The command no longer keeps the interpreter alive through a
-reference cycle.
diff --git a/Misc/NEWS.d/next/Library/2026-06-26-13-39-11.gh-issue-152248.N2Rmaf.rst b/Misc/NEWS.d/next/Library/2026-06-26-13-39-11.gh-issue-152248.N2Rmaf.rst
deleted file mode 100644
index 8921ad17349e975..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-26-13-39-11.gh-issue-152248.N2Rmaf.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Make the C and pure-Python :mod:`zoneinfo` parsers validate POSIX TZ
-abbreviations consistently, rejecting unquoted abbreviations with non-letter
-characters and empty quoted abbreviations. Patch by tonghuaroot.
diff --git a/Misc/NEWS.d/next/Library/2026-06-26-13-40-00.gh-issue-152258.Qe7Lm3.rst b/Misc/NEWS.d/next/Library/2026-06-26-13-40-00.gh-issue-152258.Qe7Lm3.rst
deleted file mode 100644
index b2a0e776ce9c41c..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-26-13-40-00.gh-issue-152258.Qe7Lm3.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Add the :mod:`curses` window method :meth:`~curses.window.dupwin`, which
-returns a new window that is an independent duplicate of an existing one.
diff --git a/Misc/NEWS.d/next/Library/2026-06-26-14-05-00.gh-issue-116946.Kp7raZ.rst b/Misc/NEWS.d/next/Library/2026-06-26-14-05-00.gh-issue-116946.Kp7raZ.rst
deleted file mode 100644
index 95957b7d9d9894e..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-26-14-05-00.gh-issue-116946.Kp7raZ.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-The internal :mod:`!_tkinter` ``tkapp`` and ``tktimertoken`` types now
-implement the garbage collector protocol, so reference cycles involving a
-Tcl interpreter or a timer handler can be collected.
diff --git a/Misc/NEWS.d/next/Library/2026-06-26-14-34-28.gh-issue-152263.5PHQP4.rst b/Misc/NEWS.d/next/Library/2026-06-26-14-34-28.gh-issue-152263.5PHQP4.rst
deleted file mode 100644
index 7367f84c6f474ce..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-26-14-34-28.gh-issue-152263.5PHQP4.rst
+++ /dev/null
@@ -1,9 +0,0 @@
-Add the soft-label-key functions to the :mod:`curses` module:
-:func:`~curses.slk_init`, :func:`~curses.slk_set`, :func:`~curses.slk_label`,
-:func:`~curses.slk_refresh`, :func:`~curses.slk_noutrefresh`,
-:func:`~curses.slk_clear`, :func:`~curses.slk_restore`,
-:func:`~curses.slk_touch`, :func:`~curses.slk_attron`,
-:func:`~curses.slk_attroff`, :func:`~curses.slk_attrset`,
-:func:`~curses.slk_attr`, :func:`~curses.slk_attr_on`,
-:func:`~curses.slk_attr_off`, :func:`~curses.slk_attr_set` and
-:func:`~curses.slk_color`.
diff --git a/Misc/NEWS.d/next/Library/2026-06-26-15-00-00.gh-issue-38464.yDPjKH.rst b/Misc/NEWS.d/next/Library/2026-06-26-15-00-00.gh-issue-38464.yDPjKH.rst
deleted file mode 100644
index c1c272b97d4b0a8..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-26-15-00-00.gh-issue-38464.yDPjKH.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-:meth:`!tkinter.Misc.nametowidget` now resolves the auto-generated names of
-cloned menus (a menu used as a menubar or a cascade) back to the original
-widget.
diff --git a/Misc/NEWS.d/next/Library/2026-06-26-15-10-00.gh-issue-152260.Rk4nP9.rst b/Misc/NEWS.d/next/Library/2026-06-26-15-10-00.gh-issue-152260.Rk4nP9.rst
deleted file mode 100644
index 8c396009815399d..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-26-15-10-00.gh-issue-152260.Rk4nP9.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Add the :mod:`curses` functions :func:`~curses.scr_dump`,
-:func:`~curses.scr_restore`, :func:`~curses.scr_init` and
-:func:`~curses.scr_set`, which dump the whole screen to a file and restore it.
diff --git a/Misc/NEWS.d/next/Library/2026-06-26-15-30-00.gh-issue-88758.Qw7nLp.rst b/Misc/NEWS.d/next/Library/2026-06-26-15-30-00.gh-issue-88758.Qw7nLp.rst
deleted file mode 100644
index 31d567194fb9031..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-26-15-30-00.gh-issue-88758.Qw7nLp.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-:meth:`!tkinter.Misc.focus_get`, :meth:`!focus_displayof`,
-:meth:`!focus_lastfor` and :meth:`!winfo_containing` now return ``None``
-instead of raising :exc:`KeyError` when the widget was not created by
-:mod:`tkinter` (for example a torn-off menu).
diff --git a/Misc/NEWS.d/next/Library/2026-06-26-15-41-34.gh-issue-152305.WnbbBc.rst b/Misc/NEWS.d/next/Library/2026-06-26-15-41-34.gh-issue-152305.WnbbBc.rst
deleted file mode 100644
index 4f27e2ed016d694..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-26-15-41-34.gh-issue-152305.WnbbBc.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix the pure-Python :meth:`datetime.time.strftime` implementation raising :exc:`AttributeError` for the
-year directives. Patch by tonghuaroot.
diff --git a/Misc/NEWS.d/next/Library/2026-06-26-16-30-00.gh-issue-83274.Kx9mQv.rst b/Misc/NEWS.d/next/Library/2026-06-26-16-30-00.gh-issue-83274.Kx9mQv.rst
deleted file mode 100644
index 3b722d2176be920..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-26-16-30-00.gh-issue-83274.Kx9mQv.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Deallocating a :mod:`tkinter` application from a thread other than the one it
-was created in no longer crashes the interpreter. The underlying Tcl
-interpreter is leaked instead, and a :exc:`RuntimeWarning` is reported.
diff --git a/Misc/NEWS.d/next/Library/2026-06-26-17-18-01.gh-issue-152275.V64zKa.rst b/Misc/NEWS.d/next/Library/2026-06-26-17-18-01.gh-issue-152275.V64zKa.rst
deleted file mode 100644
index ec33586df1a7381..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-26-17-18-01.gh-issue-152275.V64zKa.rst
+++ /dev/null
@@ -1,7 +0,0 @@
-The :mod:`curses` module now raises :exc:`OverflowError` instead of silently
-truncating an out-of-range value: :func:`curses.color_pair` rejects a color
-pair number that does not fit in the ``chtype`` color field, and the
-``attr`` argument of the character-cell and attribute methods
-(:meth:`~curses.window.addch`, :meth:`~curses.window.addstr`,
-:meth:`~curses.window.attron`, :meth:`~curses.window.attrset` and others) is
-checked against the ``chtype`` range.
diff --git a/Misc/NEWS.d/next/Library/2026-06-26-19-01-13.gh-issue-121249.p1SBW0.rst b/Misc/NEWS.d/next/Library/2026-06-26-19-01-13.gh-issue-121249.p1SBW0.rst
deleted file mode 100644
index 0e676e7774d1d7a..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-26-19-01-13.gh-issue-121249.p1SBW0.rst
+++ /dev/null
@@ -1 +0,0 @@
-Deprecate using ``'F'`` and ``'D'`` type codes in the :mod:`struct` module.
diff --git a/Misc/NEWS.d/next/Library/2026-06-26-21-30-00.gh-issue-152325.Km9xQr.rst b/Misc/NEWS.d/next/Library/2026-06-26-21-30-00.gh-issue-152325.Km9xQr.rst
deleted file mode 100644
index 655f61cbb530b12..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-26-21-30-00.gh-issue-152325.Km9xQr.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Add the :func:`curses.has_mouse` function and the
-:meth:`curses.window.mouse_trafo` method.
diff --git a/Misc/NEWS.d/next/Library/2026-06-26-22-06-07.gh-issue-87904.F71C70.rst b/Misc/NEWS.d/next/Library/2026-06-26-22-06-07.gh-issue-87904.F71C70.rst
deleted file mode 100644
index 09bd5a06836df7d..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-26-22-06-07.gh-issue-87904.F71C70.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-The :mod:`curses` types and exceptions now report their public module in
-:attr:`~type.__module__`, :func:`repr` and :func:`help` -- for example
-``curses.window`` instead of ``_curses.window`` and ``curses.panel.error``
-instead of ``_curses_panel.error``.
diff --git a/Misc/NEWS.d/next/Library/2026-06-26-22-15-00.gh-issue-152332.Lp3WqN.rst b/Misc/NEWS.d/next/Library/2026-06-26-22-15-00.gh-issue-152332.Lp3WqN.rst
deleted file mode 100644
index 32875cdac5c9d0c..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-26-22-15-00.gh-issue-152332.Lp3WqN.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Add the :func:`curses.term_attrs` function, the counterpart of
-:func:`curses.termattrs` for the ``WA_*`` attributes.
diff --git a/Misc/NEWS.d/next/Library/2026-06-26-22-50-00.gh-issue-152334.Mt7vQx.rst b/Misc/NEWS.d/next/Library/2026-06-26-22-50-00.gh-issue-152334.Mt7vQx.rst
deleted file mode 100644
index 8d24ebfde8f1eca..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-26-22-50-00.gh-issue-152334.Mt7vQx.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Add the :func:`curses.define_key`, :func:`curses.key_defined` and
-:func:`curses.keyok` key-management functions.
diff --git a/Misc/NEWS.d/next/Library/2026-06-26-23-56-40.gh-issue-71880.782D31.rst b/Misc/NEWS.d/next/Library/2026-06-26-23-56-40.gh-issue-71880.782D31.rst
deleted file mode 100644
index 5a12f428f2a8b6c..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-26-23-56-40.gh-issue-71880.782D31.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-:class:`curses.textpad.Textbox` now lets the lower-right cell of the window be
-edited. Writing it with :meth:`~curses.window.addch` would move the cursor
-past the end of the window, raising an error and scrolling a scrollable window,
-so it is now written with :meth:`~curses.window.insch`, which keeps the cursor
-in place.
diff --git a/Misc/NEWS.d/next/Library/2026-06-27-11-32-37.gh-issue-50409.Pw3Kq9.rst b/Misc/NEWS.d/next/Library/2026-06-27-11-32-37.gh-issue-50409.Pw3Kq9.rst
deleted file mode 100644
index 479a2a3a8e12527..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-27-11-32-37.gh-issue-50409.Pw3Kq9.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Deprecate the *tagOrId* parameter of
-:meth:`!tkinter.PanedWindow.paneconfigure` (and its :meth:`!paneconfig`
-alias) in favor of *child*, for consistency with the other pane methods;
-it will be removed in Python 3.18.
diff --git a/Misc/NEWS.d/next/Library/2026-06-27-12-00-00.gh-issue-43699.Zt46MI.rst b/Misc/NEWS.d/next/Library/2026-06-27-12-00-00.gh-issue-43699.Zt46MI.rst
deleted file mode 100644
index 93a9864d2445e94..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-27-12-00-00.gh-issue-43699.Zt46MI.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-The drag cursor in :mod:`tkinter.dnd` is now changed only once the pointer
-starts moving rather than on the initial button press, so that a plain
-click no longer flashes it.
diff --git a/Misc/NEWS.d/next/Library/2026-06-27-12-30-00.gh-issue-133031.Na8Bit.rst b/Misc/NEWS.d/next/Library/2026-06-27-12-30-00.gh-issue-133031.Na8Bit.rst
deleted file mode 100644
index 96e9efe20e42f04..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-27-12-30-00.gh-issue-133031.Na8Bit.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-:class:`curses.textpad.Textbox` now enters and reads back the non-ASCII
-characters of an 8-bit locale encoding, instead of mangling them with a 7-bit
-mask.
diff --git a/Misc/NEWS.d/next/Library/2026-06-27-12-45-00.gh-issue-133031.Wide00.rst b/Misc/NEWS.d/next/Library/2026-06-27-12-45-00.gh-issue-133031.Wide00.rst
deleted file mode 100644
index c33365910ae2896..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-27-12-45-00.gh-issue-133031.Wide00.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-:class:`curses.textpad.Textbox` now supports entering and reading back the full
-Unicode range, including combining characters, when curses is built with
-wide-character support.
diff --git a/Misc/NEWS.d/next/Library/2026-06-27-17-19-09.gh-issue-151126.huUyOM.rst b/Misc/NEWS.d/next/Library/2026-06-27-17-19-09.gh-issue-151126.huUyOM.rst
deleted file mode 100644
index 2e51fd45b595486..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-27-17-19-09.gh-issue-151126.huUyOM.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix two crashes in :mod:`tkinter` and :mod:`socket` modules initialization
-under a memory pressure. Sets missing :exc:`MemoryError`.
diff --git a/Misc/NEWS.d/next/Library/2026-06-27-19-02-17.gh-issue-103878.216fa7.rst b/Misc/NEWS.d/next/Library/2026-06-27-19-02-17.gh-issue-103878.216fa7.rst
deleted file mode 100644
index dd5b8c2545fe653..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-27-19-02-17.gh-issue-103878.216fa7.rst
+++ /dev/null
@@ -1,8 +0,0 @@
-The :mod:`tkinter.filedialog` functions that return a filename
-(:func:`~tkinter.filedialog.askopenfilename`,
-:func:`~tkinter.filedialog.asksaveasfilename` and
-:func:`~tkinter.filedialog.askdirectory`) now consistently return an empty
-string when the dialog is cancelled, instead of an empty tuple or ``b''``
-on some platforms. :func:`~tkinter.filedialog.askopenfilenames` likewise
-always returns an empty tuple, and :func:`~tkinter.filedialog.askopenfiles`
-an empty list.
diff --git a/Misc/NEWS.d/next/Library/2026-06-28-00-00-00.gh-issue-152431.Ja3K9m.rst b/Misc/NEWS.d/next/Library/2026-06-28-00-00-00.gh-issue-152431.Ja3K9m.rst
deleted file mode 100644
index bda2dfd7cd9d89b..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-28-00-00-00.gh-issue-152431.Ja3K9m.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix ``asyncio.StreamWriter.start_tls()`` to keep the linked
-``StreamReader`` transport in sync with the upgraded transport.
diff --git a/Misc/NEWS.d/next/Library/2026-06-28-11-00-40.gh-issue-78335.Kp3mWq.rst b/Misc/NEWS.d/next/Library/2026-06-28-11-00-40.gh-issue-78335.Kp3mWq.rst
deleted file mode 100644
index 641889cfa9ef41d..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-28-11-00-40.gh-issue-78335.Kp3mWq.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Update the docstrings of :mod:`tkinter` and :mod:`tkinter.ttk` widget classes
-to list all supported widget options, including options added in Tk 9.0 and
-9.1. ``tkinter.Menubutton`` and ``tkinter.Message`` previously had no option
-list at all.
diff --git a/Misc/NEWS.d/next/Library/2026-06-28-12-00-00.gh-issue-152470.Wn7Kp3.rst b/Misc/NEWS.d/next/Library/2026-06-28-12-00-00.gh-issue-152470.Wn7Kp3.rst
deleted file mode 100644
index 445e0a1b18f7dd7..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-28-12-00-00.gh-issue-152470.Wn7Kp3.rst
+++ /dev/null
@@ -1,9 +0,0 @@
-The wide-character :mod:`curses` functions and methods
-:meth:`curses.window.get_wch`, :meth:`curses.window.get_wstr`,
-:func:`curses.unget_wch`, :func:`curses.erasewchar`, :func:`curses.killwchar`
-and :func:`curses.wunctrl` now also work when Python is not built against a
-wide-character-aware curses library, on an 8-bit locale, where each character
-is a single byte in the relevant encoding. :func:`curses.ungetch` now also
-accepts a one-character string, like :func:`curses.unget_wch`; on a
-wide-character build it can be any character (previously a multibyte character
-raised :exc:`OverflowError`).
diff --git a/Misc/NEWS.d/next/Library/2026-06-28-12-45-09.gh-issue-152356.Dr4w2Q.rst b/Misc/NEWS.d/next/Library/2026-06-28-12-45-09.gh-issue-152356.Dr4w2Q.rst
deleted file mode 100644
index 6a4ceecbe9279e2..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-28-12-45-09.gh-issue-152356.Dr4w2Q.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix a hang in ``profiling.sampling run --blocking`` on Windows when the
-target process exits. The profiler now finalizes binary profiles instead of
-continuing to sample the exited process.
diff --git a/Misc/NEWS.d/next/Library/2026-06-28-16-20-07.gh-issue-152503.N55ose.rst b/Misc/NEWS.d/next/Library/2026-06-28-16-20-07.gh-issue-152503.N55ose.rst
deleted file mode 100644
index e97c5d74600c67f..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-28-16-20-07.gh-issue-152503.N55ose.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Fix :meth:`curses.window.in_wch`, :meth:`curses.window.in_wchstr` and
-:meth:`curses.window.getbkgrnd` returning garbage text when :mod:`curses` is
-built against a curses library that does not NUL-terminate the ``cchar_t``
-text array (such as NetBSD curses).
diff --git a/Misc/NEWS.d/next/Library/2026-06-29-01-08-53.gh-issue-110357.QGWdZQ.rst b/Misc/NEWS.d/next/Library/2026-06-29-01-08-53.gh-issue-110357.QGWdZQ.rst
deleted file mode 100644
index 7c2384ea76fe531..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-29-01-08-53.gh-issue-110357.QGWdZQ.rst
+++ /dev/null
@@ -1,6 +0,0 @@
-Importing :mod:`hashlib` no longer logs an error to stderr when a normally
-guaranteed hash algorithm is unavailable in the current runtime (for example
-under an OpenSSL FIPS configuration or a build using
-:option:`--without-builtin-hashlib-hashes <--with-builtin-hashlib-hashes>`).
-Code that actually uses the missing algorithm still gets a clear
-:exc:`ValueError`.
diff --git a/Misc/NEWS.d/next/Library/2026-06-29-09-45-00.gh-issue-152569.Kf7Lq2.rst b/Misc/NEWS.d/next/Library/2026-06-29-09-45-00.gh-issue-152569.Kf7Lq2.rst
deleted file mode 100644
index fb7e32a5260b39a..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-29-09-45-00.gh-issue-152569.Kf7Lq2.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix :func:`asyncio.wait` leaking waiting tasks via the await-graph when racing a
-future that never resolves. The waiting task is now discarded from every future's
-``awaited_by`` set once :func:`~asyncio.wait` returns, even for pending futures.
diff --git a/Misc/NEWS.d/next/Library/2026-06-29-12-50-28.gh-issue-152587.Lq8wVn.rst b/Misc/NEWS.d/next/Library/2026-06-29-12-50-28.gh-issue-152587.Lq8wVn.rst
deleted file mode 100644
index e3a9618c6480bc2..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-29-12-50-28.gh-issue-152587.Lq8wVn.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-In :mod:`tkinter`, the *name* parameter of the
-:meth:`~tkinter.Misc.wait_variable`, :meth:`~tkinter.Misc.setvar` and
-:meth:`~tkinter.Misc.getvar` methods and the *value* parameter of
-:meth:`!setvar` are now required. Their former default values
-(``'PY_VAR'`` and ``'1'``) were not meaningful.
diff --git a/Misc/NEWS.d/next/Library/2026-06-29-21-59-08.gh-issue-152638.92dpzo.rst b/Misc/NEWS.d/next/Library/2026-06-29-21-59-08.gh-issue-152638.92dpzo.rst
deleted file mode 100644
index 3fbffb03cb38961..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-29-21-59-08.gh-issue-152638.92dpzo.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Deprecate :func:`tkinter.filedialog.askopenfiles`. Opening several files at
-once is error-prone and the returned list cannot be used in a :keyword:`with`
-statement; iterate over the names returned by
-:func:`tkinter.filedialog.askopenfilenames` and open them one by one instead.
diff --git a/Misc/NEWS.d/next/Library/2026-06-29-22-16-57.gh-issue-50966.Tq5mLp.rst b/Misc/NEWS.d/next/Library/2026-06-29-22-16-57.gh-issue-50966.Tq5mLp.rst
deleted file mode 100644
index 96a0938c02d226b..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-29-22-16-57.gh-issue-50966.Tq5mLp.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix unbounded recursion in :mod:`turtle` when a mouse event handler that moves
-the turtle is reentered while the screen is being redrawn, for example with
-``screen.ondrag(turtle.goto)``. This could previously crash the interpreter.
diff --git a/Misc/NEWS.d/next/Library/2026-06-30-12-00-00.gh-issue-40038.qK7mGv.rst b/Misc/NEWS.d/next/Library/2026-06-30-12-00-00.gh-issue-40038.qK7mGv.rst
deleted file mode 100644
index 1f393d23266bcef..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-30-12-00-00.gh-issue-40038.qK7mGv.rst
+++ /dev/null
@@ -1,6 +0,0 @@
-:mod:`imaplib` now again quotes command arguments when necessary, for
-example mailbox names containing a space. Such quoting was inadvertently
-disabled when the module was ported to Python 3, and the arguments are now
-quoted according to the :rfc:`3501` grammar. For backward compatibility,
-an argument already enclosed in double quotes is left unchanged, so code
-that quotes arguments itself keeps working.
diff --git a/Misc/NEWS.d/next/Library/2026-06-30-13-00-00.gh-issue-151842.OOM31g.rst b/Misc/NEWS.d/next/Library/2026-06-30-13-00-00.gh-issue-151842.OOM31g.rst
deleted file mode 100644
index 8a2ecf3c40032f5..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-30-13-00-00.gh-issue-151842.OOM31g.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix a crash in :func:`!_interpreters.capture_exception` when
-:exc:`MemoryError` happens. Patch by Amrutha Modela.
diff --git a/Misc/NEWS.d/next/Library/2026-06-30-14-30-00.gh-issue-152502.Mq7Kx2.rst b/Misc/NEWS.d/next/Library/2026-06-30-14-30-00.gh-issue-152502.Mq7Kx2.rst
deleted file mode 100644
index 6f343f0ab0c162e..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-06-30-14-30-00.gh-issue-152502.Mq7Kx2.rst
+++ /dev/null
@@ -1,6 +0,0 @@
-Detect the :mod:`curses` mouse interface (:func:`~curses.getmouse`,
-:func:`~curses.has_mouse`, the ``BUTTON*`` constants, and others) and the
-window ``is_*`` state-query methods with configure capability probes or library
-macros instead of gating them on ncurses-specific macros. They are now also
-available with other curses implementations that provide them, such as NetBSD
-curses and PDCurses (the latter underpins ``windows-curses``).
diff --git a/Misc/NEWS.d/next/Library/2026-07-01-10-00-00.gh-issue-88574.Kz3wQm.rst b/Misc/NEWS.d/next/Library/2026-07-01-10-00-00.gh-issue-88574.Kz3wQm.rst
deleted file mode 100644
index 371f4d08bccd2e2..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-01-10-00-00.gh-issue-88574.Kz3wQm.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-:mod:`imaplib` no longer fails when a server sends a spurious blank line
-after the counted data of a literal, including after a literal that
-terminates a response (such as a mailbox name returned by ``LIST``).
-Such blank lines are now skipped without swallowing the following line.
diff --git a/Misc/NEWS.d/next/Library/2026-07-01-10-30-00.gh-issue-63121.Rm4tZp.rst b/Misc/NEWS.d/next/Library/2026-07-01-10-30-00.gh-issue-63121.Rm4tZp.rst
deleted file mode 100644
index a63b164ad7a627b..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-01-10-30-00.gh-issue-63121.Rm4tZp.rst
+++ /dev/null
@@ -1,7 +0,0 @@
-:mod:`imaplib` now refreshes the cached capability list after a successful
-:meth:`~imaplib.IMAP4.login` or :meth:`~imaplib.IMAP4.authenticate`, using
-the ``CAPABILITY`` response sent by the server or, if none was sent, by
-querying it, so that capabilities that become available only after
-authentication (such as ``ENABLE`` on Gmail) are recognized. Capabilities
-advertised in the server greeting are now also used, avoiding a redundant
-``CAPABILITY`` command.
diff --git a/Misc/NEWS.d/next/Library/2026-07-01-11-29-13.gh-issue-151126.eElGy5.rst b/Misc/NEWS.d/next/Library/2026-07-01-11-29-13.gh-issue-151126.eElGy5.rst
deleted file mode 100644
index d5ec1d254ef056e..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-01-11-29-13.gh-issue-151126.eElGy5.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix a crash caused by failing to set :exc:`MemoryError` on allocation failure
-when passing :class:`ctypes.Structure` or :class:`ctypes.Union` instances by
-value to ctypes foreign functions.
diff --git a/Misc/NEWS.d/next/Library/2026-07-01-12-00-00.gh-issue-108280.Nq8vTr.rst b/Misc/NEWS.d/next/Library/2026-07-01-12-00-00.gh-issue-108280.Nq8vTr.rst
deleted file mode 100644
index 487c9da67f1832b..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-01-12-00-00.gh-issue-108280.Nq8vTr.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Connecting :mod:`imaplib` to a server that does not send a valid IMAP4
-greeting (for example a POP3 server answering on the IMAP port) now raises
-an error reporting the server's response instead of
-``imaplib.IMAP4.error: None``.
diff --git a/Misc/NEWS.d/next/Library/2026-07-01-12-00-00.gh-issue-152718.pr0f1l.rst b/Misc/NEWS.d/next/Library/2026-07-01-12-00-00.gh-issue-152718.pr0f1l.rst
deleted file mode 100644
index 63d9d7f878cb07d..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-01-12-00-00.gh-issue-152718.pr0f1l.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix unbounded memory allocation in the :mod:`profiling.sampling` binary profile
-reader when a file declares more string or frame entries than it contains.
diff --git a/Misc/NEWS.d/next/Library/2026-07-01-14-00-00.gh-issue-49680.Lm5rQv.rst b/Misc/NEWS.d/next/Library/2026-07-01-14-00-00.gh-issue-49680.Lm5rQv.rst
deleted file mode 100644
index 6371df69e69077f..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-01-14-00-00.gh-issue-49680.Lm5rQv.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Add the *translate_line_endings* parameter to :meth:`imaplib.IMAP4.append`.
-By default line endings in the message are translated to CRLF, as before;
-passing ``False`` sends the message literal exactly as given, preserving
-bare CR or LF octets.
diff --git a/Misc/NEWS.d/next/Library/2026-07-01-15-30-00.gh-issue-77508.Bn2kXt.rst b/Misc/NEWS.d/next/Library/2026-07-01-15-30-00.gh-issue-77508.Bn2kXt.rst
deleted file mode 100644
index d6f1bd23be080a3..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-01-15-30-00.gh-issue-77508.Bn2kXt.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Add :meth:`imaplib.IMAP4.move`, a wrapper for the IMAP ``MOVE`` command
-(:rfc:`6851`), analogous to :meth:`~imaplib.IMAP4.copy`.
diff --git a/Misc/NEWS.d/next/Library/2026-07-01-22-59-25.gh-issue-152586.WuEae6.rst b/Misc/NEWS.d/next/Library/2026-07-01-22-59-25.gh-issue-152586.WuEae6.rst
deleted file mode 100644
index 6c800551c906f2e..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-01-22-59-25.gh-issue-152586.WuEae6.rst
+++ /dev/null
@@ -1 +0,0 @@
-:class:`!tempfile._TemporaryFileWrapper` has been renamed to the public :class:`tempfile.TemporaryFileWrapper`. The old private name is kept as a deprecated alias and will be removed in Python 3.21.
diff --git a/Misc/NEWS.d/next/Library/2026-07-01-23-17-27.gh-issue-152905.wLnGqR.rst b/Misc/NEWS.d/next/Library/2026-07-01-23-17-27.gh-issue-152905.wLnGqR.rst
deleted file mode 100644
index 99f20e65ad8e08f..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-01-23-17-27.gh-issue-152905.wLnGqR.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-On glibc, :func:`locale.nl_langinfo` now decodes the ``LC_TIME`` items (such
-as the month and day names) using the wide locale data, so the result no
-longer depends on the ``LC_CTYPE`` encoding.
diff --git a/Misc/NEWS.d/next/Library/2026-07-02-12-00-00.gh-issue-152847.PitKqc.rst b/Misc/NEWS.d/next/Library/2026-07-02-12-00-00.gh-issue-152847.PitKqc.rst
deleted file mode 100644
index 3f20d78a201e84c..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-02-12-00-00.gh-issue-152847.PitKqc.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Reject a POSIX TZ transition rule with non-digit characters in the
-day-of-year field in the pure-Python :mod:`zoneinfo` parser. Patch by
-tonghuaroot.
diff --git a/Misc/NEWS.d/next/Library/2026-07-02-13-30-00.gh-issue-152849.K9dRvP.rst b/Misc/NEWS.d/next/Library/2026-07-02-13-30-00.gh-issue-152849.K9dRvP.rst
deleted file mode 100644
index 053a5dfea3f3ff4..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-02-13-30-00.gh-issue-152849.K9dRvP.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Out-of-range float and integer timestamps now raise :exc:`OverflowError`
-with the same message. Patch by tonghuaroot.
diff --git a/Misc/NEWS.d/next/Library/2026-07-02-19-21-15.gh-issue-152068.ThsmJU.rst b/Misc/NEWS.d/next/Library/2026-07-02-19-21-15.gh-issue-152068.ThsmJU.rst
deleted file mode 100644
index 9ec8413b4ac424c..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-02-19-21-15.gh-issue-152068.ThsmJU.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fixes a bug when a line was split (particularly on macOS Terminal.app) in the middle of a colorized keyword, causing the ANSI Color Reset sequence (ESC0m) to not be properly printed, causing the output to be colored when it shouldn't
diff --git a/Misc/NEWS.d/next/Library/2026-07-02-22-19-53.gh-issue-150880.vPZ7jK.rst b/Misc/NEWS.d/next/Library/2026-07-02-22-19-53.gh-issue-150880.vPZ7jK.rst
deleted file mode 100644
index a7bf210f8e1ca9c..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-02-22-19-53.gh-issue-150880.vPZ7jK.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Normalize non-extended Windows paths before appending the wildcard used by
-``os.listdir()`` and ``os.scandir()``, making paths with trailing spaces
-behave consistently with other filesystem APIs.
diff --git a/Misc/NEWS.d/next/Library/2026-07-03-14-54-33.gh-issue-152951.u8tPCI.rst b/Misc/NEWS.d/next/Library/2026-07-03-14-54-33.gh-issue-152951.u8tPCI.rst
deleted file mode 100644
index c3d56c6d59c91b3..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-03-14-54-33.gh-issue-152951.u8tPCI.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-:class:`collections.deque` prevent rare crash when calling ``extend`` under
-high memory pressure conditions.
diff --git a/Misc/NEWS.d/next/Library/2026-07-03-17-29-34.gh-issue-150579.0tLpQukIU.rst b/Misc/NEWS.d/next/Library/2026-07-03-17-29-34.gh-issue-150579.0tLpQukIU.rst
deleted file mode 100644
index 7aff384431edc77..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-03-17-29-34.gh-issue-150579.0tLpQukIU.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-:mod:`concurrent.futures` now uses lazy imports for its executor submodules
-instead of a module ``__getattr__`` hook.
diff --git a/Misc/NEWS.d/next/Library/2026-07-03-18-30-00.gh-issue-119592.mQr3Vx.rst b/Misc/NEWS.d/next/Library/2026-07-03-18-30-00.gh-issue-119592.mQr3Vx.rst
deleted file mode 100644
index f718c877c8ed22b..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-03-18-30-00.gh-issue-119592.mQr3Vx.rst
+++ /dev/null
@@ -1,11 +0,0 @@
-Fix :class:`concurrent.futures.ProcessPoolExecutor` stranding submitted
-work forever when a worker process exited upon reaching its
-*max_tasks_per_child* limit after
-:meth:`~concurrent.futures.Executor.shutdown` was called with
-``wait=False``: a replacement worker is now spawned and the remaining work
-executed as documented. If the executor has instead been garbage collected
-without ``shutdown()`` (:gh:`152967`), or a replacement worker cannot be
-started, the remaining futures now fail with
-:exc:`~concurrent.futures.process.BrokenProcessPool` instead of never
-resolving. A worker exit racing ``shutdown(wait=False)`` can also no
-longer crash the executor management thread.
diff --git a/Misc/NEWS.d/next/Library/2026-07-03-19-51-47.gh-issue-152997.i1ErzB.rst b/Misc/NEWS.d/next/Library/2026-07-03-19-51-47.gh-issue-152997.i1ErzB.rst
deleted file mode 100644
index 9983f1b8313f73f..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-03-19-51-47.gh-issue-152997.i1ErzB.rst
+++ /dev/null
@@ -1,6 +0,0 @@
-On platforms providing the C library's :manpage:`iconv(3)` function,
-the :mod:`codecs` module now exposes every encoding known to ``iconv``
-for which Python has no built-in codec.
-Such an encoding can be used by its name (for example ``"cp1133"``)
-or, to force the ``iconv``-based engine even when a built-in codec exists,
-with an ``"iconv:"`` prefix (for example ``"iconv:latin1"``).
diff --git a/Misc/NEWS.d/next/Library/2026-07-03-21-10-00.gh-issue-54930.hq09Er.rst b/Misc/NEWS.d/next/Library/2026-07-03-21-10-00.gh-issue-54930.hq09Er.rst
deleted file mode 100644
index 1cfc0212c609a69..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-03-21-10-00.gh-issue-54930.hq09Er.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-Error responses of :class:`http.server.BaseHTTPRequestHandler` to malformed
-request lines now include a status line and headers instead of being sent in
-the bare HTTP/0.9 style.
-Only a valid HTTP/0.9 request (a two-word ``GET`` request line) now receives
-an HTTP/0.9 style response.
diff --git a/Misc/NEWS.d/next/Library/2026-07-04-11-14-06.gh-issue-152851.diYvTf.rst b/Misc/NEWS.d/next/Library/2026-07-04-11-14-06.gh-issue-152851.diYvTf.rst
deleted file mode 100644
index aab033ebeed6954..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-04-11-14-06.gh-issue-152851.diYvTf.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Prevent a crash when allocation fails while copying a :func:`BLAKE-2s/2b
-` object. Patch by Bénédikt Tran.
diff --git a/Misc/NEWS.d/next/Library/2026-07-04-11-26-24.gh-issue-153009.KGl-nQ.rst b/Misc/NEWS.d/next/Library/2026-07-04-11-26-24.gh-issue-153009.KGl-nQ.rst
deleted file mode 100644
index a8a74caa41042ac..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-04-11-26-24.gh-issue-153009.KGl-nQ.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix compilation of :mod:`curses` on platforms that define the ``stdscr``
-macro. Patch by Bénédikt Tran.
diff --git a/Misc/NEWS.d/next/Library/2026-07-04-13-00-00.gh-issue-135661.CIkADG.rst b/Misc/NEWS.d/next/Library/2026-07-04-13-00-00.gh-issue-135661.CIkADG.rst
deleted file mode 100644
index 26a912a6f3a1949..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-04-13-00-00.gh-issue-135661.CIkADG.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix :class:`html.parser.HTMLParser`: an abruptly closed empty comment
-(```` or ````) no longer extends up to a later ``-->`` in the same
-:meth:`~html.parser.HTMLParser.feed` call.
diff --git a/Misc/NEWS.d/next/Library/2026-07-04-20-28-51.gh-issue-153037.XUSp_g.rst b/Misc/NEWS.d/next/Library/2026-07-04-20-28-51.gh-issue-153037.XUSp_g.rst
deleted file mode 100644
index cbfc62f75184706..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-04-20-28-51.gh-issue-153037.XUSp_g.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix :class:`~compression.zstd.ZstdFile` raising :exc:`AttributeError`
-instead of :exc:`io.UnsupportedOperation` when iterating over a file that
-is not open for reading.
diff --git a/Misc/NEWS.d/next/Library/2026-07-05-10-24-30.gh-issue-143921.wQx3Tn.rst b/Misc/NEWS.d/next/Library/2026-07-05-10-24-30.gh-issue-143921.wQx3Tn.rst
deleted file mode 100644
index 04e8bd6d6f9d6cb..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-05-10-24-30.gh-issue-143921.wQx3Tn.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Narrow the control character check in :mod:`imaplib` commands: only NUL, CR
-and LF are now rejected. Other control characters are valid in quoted
-strings and can occur in mailbox names returned by the server, so they are
-now accepted and sent quoted.
diff --git a/Misc/NEWS.d/next/Library/2026-07-05-11-36-51.gh-issue-59396.Apl7sI.rst b/Misc/NEWS.d/next/Library/2026-07-05-11-36-51.gh-issue-59396.Apl7sI.rst
deleted file mode 100644
index d4c0473ef372e81..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-05-11-36-51.gh-issue-59396.Apl7sI.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-:class:`tkinter.scrolledtext.ScrolledText` gained a *use_ttk* parameter to use
-the themed :mod:`tkinter.ttk` frame and scroll bar instead of the classic
-:mod:`tkinter` widgets.
diff --git a/Misc/NEWS.d/next/Library/2026-07-05-12-00-00.gh-issue-153056.tMpLat.rst b/Misc/NEWS.d/next/Library/2026-07-05-12-00-00.gh-issue-153056.tMpLat.rst
deleted file mode 100644
index a2bc89f25a53c19..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-05-12-00-00.gh-issue-153056.tMpLat.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Fix :class:`string.Template` raising a spurious :exc:`ValueError` when the
-*pattern* attribute is a compiled regular expression object, which the
-documentation allows. On the free-threaded build this also occurred as a data
-race on the first concurrent use.
diff --git a/Misc/NEWS.d/next/Library/2026-07-05-14-30-00.gh-issue-153062.teeFT1.rst b/Misc/NEWS.d/next/Library/2026-07-05-14-30-00.gh-issue-153062.teeFT1.rst
deleted file mode 100644
index ed1aaa15d37bd9c..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-05-14-30-00.gh-issue-153062.teeFT1.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix a crash when concurrently iterating an :func:`itertools.tee` iterator on
-the free-threaded build.
diff --git a/Misc/NEWS.d/next/Library/2026-07-05-16-09-31.gh-issue-153068.huY9Jh.rst b/Misc/NEWS.d/next/Library/2026-07-05-16-09-31.gh-issue-153068.huY9Jh.rst
deleted file mode 100644
index accf6e99cd6434d..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-05-16-09-31.gh-issue-153068.huY9Jh.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix :meth:`!cProfile.Profile.enable` to no longer overwrite errors from
-:mod:`sys.monitoring`.
diff --git a/Misc/NEWS.d/next/Library/2026-07-05-17-39-16.gh-issue-153133.kKSH7g.rst b/Misc/NEWS.d/next/Library/2026-07-05-17-39-16.gh-issue-153133.kKSH7g.rst
deleted file mode 100644
index a7a68158ac895e3..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-05-17-39-16.gh-issue-153133.kKSH7g.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix a socket leak in :meth:`asyncio.loop.create_connection` when the
-transport cannot be created.
diff --git a/Misc/NEWS.d/next/Library/2026-07-05-20-15-00.gh-issue-98092.iDcmd1.rst b/Misc/NEWS.d/next/Library/2026-07-05-20-15-00.gh-issue-98092.iDcmd1.rst
deleted file mode 100644
index 9854e996a942a53..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-05-20-15-00.gh-issue-98092.iDcmd1.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Add :meth:`imaplib.IMAP4.id`, a wrapper for the IMAP ``ID`` command
-(:rfc:`2971`).
diff --git a/Misc/NEWS.d/next/Library/2026-07-05-21-40-00.gh-issue-89869.XG7aHz.rst b/Misc/NEWS.d/next/Library/2026-07-05-21-40-00.gh-issue-89869.XG7aHz.rst
deleted file mode 100644
index 4bf319f7f681525..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-05-21-40-00.gh-issue-89869.XG7aHz.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Add :meth:`imaplib.IMAP4.login_plain`, which authenticates using the
-``PLAIN`` SASL mechanism (:rfc:`4616`). Unlike :meth:`~imaplib.IMAP4.login`,
-it supports non-ASCII user names and passwords.
diff --git a/Misc/NEWS.d/next/Library/2026-07-05-22-30-00.gh-issue-66788.tM7pQ2.rst b/Misc/NEWS.d/next/Library/2026-07-05-22-30-00.gh-issue-66788.tM7pQ2.rst
deleted file mode 100644
index 29bd36ebd6295fe..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-05-22-30-00.gh-issue-66788.tM7pQ2.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Add the ``utf-7-imap`` codec, implementing the modified UTF-7 encoding
-used for international IMAP4 mailbox names (:rfc:`3501`, section 5.1.3).
diff --git a/Misc/NEWS.d/next/Library/2026-07-06-12-00-00.gh-issue-153200.isqrtLt.rst b/Misc/NEWS.d/next/Library/2026-07-06-12-00-00.gh-issue-153200.isqrtLt.rst
deleted file mode 100644
index a27ac73fe31a70a..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-06-12-00-00.gh-issue-153200.isqrtLt.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix :func:`math.isqrt` returning an incorrect result for arguments not
-less than 2**64 that are instances of an :class:`int` subclass with an
-overridden comparison operator.
diff --git a/Misc/NEWS.d/next/Library/2026-07-06-13-42-17.gh-issue-72880.fcXhWr.rst b/Misc/NEWS.d/next/Library/2026-07-06-13-42-17.gh-issue-72880.fcXhWr.rst
deleted file mode 100644
index 688464c9435d3a9..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-06-13-42-17.gh-issue-72880.fcXhWr.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Added the :mod:`tkinter.fontchooser` module which provides the
-:class:`~tkinter.fontchooser.FontChooser` class as an interface to the
-native font selection dialog.
diff --git a/Misc/NEWS.d/next/Library/2026-07-06-14-05-40.gh-issue-153259.sysTr1.rst b/Misc/NEWS.d/next/Library/2026-07-06-14-05-40.gh-issue-153259.sysTr1.rst
deleted file mode 100644
index 2355826ab4b2de2..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-06-14-05-40.gh-issue-153259.sysTr1.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Added the :mod:`tkinter.systray` module which provides the
-:class:`~tkinter.systray.SysTrayIcon` class as an interface to the system
-tray icon and the :func:`~tkinter.systray.notify` function which sends a
-desktop notification. They require Tk 8.7/9.0 or newer.
diff --git a/Misc/NEWS.d/next/Library/2026-07-06-14-18-33.gh-issue-153256.tkPrnt.rst b/Misc/NEWS.d/next/Library/2026-07-06-14-18-33.gh-issue-153256.tkPrnt.rst
deleted file mode 100644
index db61bdb7f7b97d9..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-06-14-18-33.gh-issue-153256.tkPrnt.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Added the :meth:`!tk_print` method to :class:`tkinter.Canvas` and
-:class:`tkinter.Text` which prints the contents of the widget using the
-native print dialog. It requires Tk 8.7/9.0 or newer.
diff --git a/Misc/NEWS.d/next/Library/2026-07-06-14-30-00.gh-issue-153521.iMaP47.rst b/Misc/NEWS.d/next/Library/2026-07-06-14-30-00.gh-issue-153521.iMaP47.rst
deleted file mode 100644
index 93edb1532d5d41b..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-06-14-30-00.gh-issue-153521.iMaP47.rst
+++ /dev/null
@@ -1,7 +0,0 @@
-Add support for structured arguments in :mod:`imaplib` command methods. A
-*message_set* and lists of flags or other atoms can now be passed as
-sequences instead of preformatted strings, and the
-:meth:`~imaplib.IMAP4.search`, :meth:`~imaplib.IMAP4.fetch`,
-:meth:`~imaplib.IMAP4.sort`, :meth:`~imaplib.IMAP4.thread` and
-:meth:`~imaplib.IMAP4.uid` methods accept a *params* keyword argument that
-substitutes and quotes ``?`` placeholders.
diff --git a/Misc/NEWS.d/next/Library/2026-07-06-14-38-02.gh-issue-145578.aX11yQ.rst b/Misc/NEWS.d/next/Library/2026-07-06-14-38-02.gh-issue-145578.aX11yQ.rst
new file mode 100644
index 000000000000000..d32d6a80238fdd3
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-07-06-14-38-02.gh-issue-145578.aX11yQ.rst
@@ -0,0 +1,7 @@
+Added :mod:`tkinter` support for the Tk 9.1 accessibility API: the
+:attr:`~tkinter.Misc.accessible` property of widgets returns an
+:class:`~tkinter.Accessible` object whose attributes are exposed to
+assistive technologies such as screen readers and whose methods register
+custom widgets with the platform accessibility API, and the
+:meth:`~tkinter.Misc.tk_check_screenreader` method reports whether a
+screen reader is running.
diff --git a/Misc/NEWS.d/next/Library/2026-07-07-02-26-43.gh-issue-153210.LUXIcm.rst b/Misc/NEWS.d/next/Library/2026-07-07-02-26-43.gh-issue-153210.LUXIcm.rst
deleted file mode 100644
index d5d4b7c1b8c0ed4..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-07-02-26-43.gh-issue-153210.LUXIcm.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fix crash on :mod:`array` import under a memory pressure.
diff --git a/Misc/NEWS.d/next/Library/2026-07-07-13-31-52.gh-issue-148286.-qu-em.rst b/Misc/NEWS.d/next/Library/2026-07-07-13-31-52.gh-issue-148286.-qu-em.rst
deleted file mode 100644
index 60cd49020c954a4..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-07-13-31-52.gh-issue-148286.-qu-em.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix undefined behavior in
-:attr:`compression.zstd.ZstdDecompressor.unused_data` when a complete frame
-was decompressed in a single call.
diff --git a/Misc/NEWS.d/next/Library/2026-07-07-17-50-54.gh-issue-143990.FoNtCf.rst b/Misc/NEWS.d/next/Library/2026-07-07-17-50-54.gh-issue-143990.FoNtCf.rst
deleted file mode 100644
index a78dcccf482ab59..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-07-17-50-54.gh-issue-143990.FoNtCf.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-A :class:`tkinter.font.Font` created from a named font,
-including by :meth:`~tkinter.font.Font.copy`,
-now copies its configured options rather than the options resolved by Tcl's ``font actual``,
-preserving a size specified in pixels (a negative size).
diff --git a/Misc/NEWS.d/next/Library/2026-07-07-22-06-52.gh-issue-153293.0DvYdc.rst b/Misc/NEWS.d/next/Library/2026-07-07-22-06-52.gh-issue-153293.0DvYdc.rst
deleted file mode 100644
index ac358bb7fc0a507..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-07-22-06-52.gh-issue-153293.0DvYdc.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix the live sampling profiler TUI keeping stale aggregated opcode
-statistics after a stats reset.
diff --git a/Misc/NEWS.d/next/Library/2026-07-08-01-03-17.gh-issue-153292.oHDt3l.rst b/Misc/NEWS.d/next/Library/2026-07-08-01-03-17.gh-issue-153292.oHDt3l.rst
deleted file mode 100644
index dc363e160074302..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-08-01-03-17.gh-issue-153292.oHDt3l.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fix data race in repr of :class:`threading.RLock` in free-threading build.
diff --git a/Misc/NEWS.d/next/Library/2026-07-08-01-47-15.gh-issue-153083.XbKZCp.rst b/Misc/NEWS.d/next/Library/2026-07-08-01-47-15.gh-issue-153083.XbKZCp.rst
deleted file mode 100644
index b6d96851e17342f..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-08-01-47-15.gh-issue-153083.XbKZCp.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Defer GC tracking of an :class:`array.array` to the end of its construction.
-Patch by Donghee Na.
diff --git a/Misc/NEWS.d/next/Library/2026-07-08-09-05-01.gh-issue-153309.g94LSO.rst b/Misc/NEWS.d/next/Library/2026-07-08-09-05-01.gh-issue-153309.g94LSO.rst
new file mode 100644
index 000000000000000..9245c1442b06f87
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-07-08-09-05-01.gh-issue-153309.g94LSO.rst
@@ -0,0 +1 @@
+:mod:`http`: Add the HTTP QUERY method (:rfc:`10008`) to :class:`~http.HTTPMethod`.
diff --git a/Misc/NEWS.d/next/Library/2026-07-08-21-15-00.gh-issue-153333.Kp3mZq.rst b/Misc/NEWS.d/next/Library/2026-07-08-21-15-00.gh-issue-153333.Kp3mZq.rst
deleted file mode 100644
index 6fcbd590d0d9d38..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-08-21-15-00.gh-issue-153333.Kp3mZq.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-The ``readprofile`` method of :class:`tkinter.Tk` now reads the user's
-profile scripts using the encoding declared in the file, instead of the
-locale encoding.
diff --git a/Misc/NEWS.d/next/Library/2026-07-09-00-00-00.gh-issue-153406.vyMmB6.rst b/Misc/NEWS.d/next/Library/2026-07-09-00-00-00.gh-issue-153406.vyMmB6.rst
deleted file mode 100644
index c09575754e33804..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-09-00-00-00.gh-issue-153406.vyMmB6.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-:func:`email.utils.parsedate_to_datetime` now raises :exc:`ValueError`
-instead of :exc:`OverflowError` when the parsed year or timezone offset is
-out of range, matching its documented behavior.
diff --git a/Misc/NEWS.d/next/Library/2026-07-09-10-14-08.gh-issue-153395.N8FuG3.rst b/Misc/NEWS.d/next/Library/2026-07-09-10-14-08.gh-issue-153395.N8FuG3.rst
deleted file mode 100644
index 1c44219f710640d..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-09-10-14-08.gh-issue-153395.N8FuG3.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-:mod:`curses.ascii` predicates and the :func:`~curses.ascii.ctrl` and
-:func:`~curses.ascii.unctrl` functions now accept a :class:`curses.complexchar`.
-:func:`~curses.ascii.ctrl` now returns a non-ASCII argument unchanged instead
-of masking it to a control character.
diff --git a/Misc/NEWS.d/next/Library/2026-07-09-12-00-00.gh-issue-49555.Ka9Lm2.rst b/Misc/NEWS.d/next/Library/2026-07-09-12-00-00.gh-issue-49555.Ka9Lm2.rst
deleted file mode 100644
index 56860e53db88627..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-09-12-00-00.gh-issue-49555.Ka9Lm2.rst
+++ /dev/null
@@ -1,7 +0,0 @@
-:mod:`imaplib` now encodes non-ASCII mailbox names as modified UTF-7
-(:rfc:`3501`, section 5.1.3) in the default mode, so international mailbox
-names can be passed as ordinary :class:`str`; under ``UTF8=ACCEPT`` they are
-sent as UTF-8 instead. A name that is not valid modified UTF-7, such as one
-with a bare ``&``, is now encoded correctly instead of being sent as is.
-A ``str`` that is already valid modified UTF-7, or a :class:`bytes` object,
-is sent unchanged.
diff --git a/Misc/NEWS.d/next/Library/2026-07-09-12-35-19.gh-issue-153422.tKb0Xq.rst b/Misc/NEWS.d/next/Library/2026-07-09-12-35-19.gh-issue-153422.tKb0Xq.rst
deleted file mode 100644
index 16bd5c9a22fbdef..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-09-12-35-19.gh-issue-153422.tKb0Xq.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-:meth:`!winfo_exists`, :meth:`!winfo_ismapped` and :meth:`!winfo_viewable`
-methods of :mod:`tkinter` widgets and :meth:`!edit_modified` of
-:class:`tkinter.Text` now return a :class:`bool` instead of an integer or,
-depending on ``wantobjects``, a string.
diff --git a/Misc/NEWS.d/next/Library/2026-07-09-14-00-00.gh-issue-153417.Bw7Rq2.rst b/Misc/NEWS.d/next/Library/2026-07-09-14-00-00.gh-issue-153417.Bw7Rq2.rst
deleted file mode 100644
index ebc36fa7c228d08..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-09-14-00-00.gh-issue-153417.Bw7Rq2.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Error messages from :meth:`imaplib.IMAP4.select` and :meth:`imaplib.IMAP4.uid`
-no longer raise :exc:`BytesWarning` under :option:`!-bb`
-when the mailbox or command argument is :class:`bytes`.
diff --git a/Misc/NEWS.d/next/Library/2026-07-09-15-18-23.gh-issue-151292.f4NQSW.rst b/Misc/NEWS.d/next/Library/2026-07-09-15-18-23.gh-issue-151292.f4NQSW.rst
deleted file mode 100644
index 4165893fc474574..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-09-15-18-23.gh-issue-151292.f4NQSW.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-Store the sample count in :mod:`profiling.sampling` binary format, as a
-64-bit integer, widening from previously used 32-bit integer. This breaks
-the existing recordings. Long or thread-heavy profiling sessions will no
-longer fail because of :exc:`OverflowError`. Patch by Maurycy
-Pawłowski-Wieroński.
diff --git a/Misc/NEWS.d/next/Library/2026-07-09-16-35-47.gh-issue-153404.daRkes.rst b/Misc/NEWS.d/next/Library/2026-07-09-16-35-47.gh-issue-153404.daRkes.rst
deleted file mode 100644
index 0746d3f12149d52..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-09-16-35-47.gh-issue-153404.daRkes.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-:class:`urllib.robotparser.RobotFileParser` now silently ignores a
-``Crawl-delay`` or ``Request-rate`` value written with non-decimal digits
-(such as ``U+00B2 SUPERSCRIPT TWO``) instead of raising :exc:`ValueError`
-and aborting the parse of the whole ``robots.txt`` file.
diff --git a/Misc/NEWS.d/next/Library/2026-07-10-12-33-30.gh-issue-153513.GxrPuY.rst b/Misc/NEWS.d/next/Library/2026-07-10-12-33-30.gh-issue-153513.GxrPuY.rst
deleted file mode 100644
index a374355d2d4c591..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-10-12-33-30.gh-issue-153513.GxrPuY.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-Values of several Tcl object types returned by :mod:`tkinter` are now
-converted to the corresponding Python type instead of being wrapped in a
-:class:`!_tkinter.Tcl_Obj`: ``index``, ``window``, ``nsName`` and
-``parsedVarName`` objects to :class:`str`, and ``pixel`` screen distances
-with no unit suffix to :class:`int` or :class:`float`.
diff --git a/Misc/NEWS.d/next/Library/2026-07-10-16-00-00.gh-issue-153494.qCh8rT.rst b/Misc/NEWS.d/next/Library/2026-07-10-16-00-00.gh-issue-153494.qCh8rT.rst
deleted file mode 100644
index 6e83940efcc180d..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-10-16-00-00.gh-issue-153494.qCh8rT.rst
+++ /dev/null
@@ -1,8 +0,0 @@
-:meth:`imaplib.IMAP4.search`, :meth:`~imaplib.IMAP4.sort`
-and :meth:`~imaplib.IMAP4.thread` (and the corresponding ``uid`` commands)
-now encode :class:`str` search criteria to the declared *charset*,
-so international search text can be passed as ordinary :class:`str`.
-When *charset* is ``None`` (as it must be under ``UTF8=ACCEPT``),
-the criteria are sent using the connection encoding instead.
-A criterion passed as :class:`bytes` is sent unchanged,
-for use with a charset that Python has no codec for.
diff --git a/Misc/NEWS.d/next/Library/2026-07-10-18-30-00.gh-issue-153502.uIdKw0.rst b/Misc/NEWS.d/next/Library/2026-07-10-18-30-00.gh-issue-153502.uIdKw0.rst
deleted file mode 100644
index 7717c8487cf6436..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-10-18-30-00.gh-issue-153502.uIdKw0.rst
+++ /dev/null
@@ -1,6 +0,0 @@
-:meth:`imaplib.IMAP4.copy`, :meth:`~imaplib.IMAP4.move`,
-:meth:`~imaplib.IMAP4.fetch`, :meth:`~imaplib.IMAP4.store`,
-:meth:`~imaplib.IMAP4.search`, :meth:`~imaplib.IMAP4.sort`,
-:meth:`~imaplib.IMAP4.thread` and :meth:`~imaplib.IMAP4.expunge` now accept a
-keyword-only *uid* argument that selects the corresponding ``UID`` command, as
-a more convenient alternative to :meth:`~imaplib.IMAP4.uid`.
diff --git a/Misc/NEWS.d/next/Library/2026-07-12-00-00-00.gh-issue-85943.8f906e.rst b/Misc/NEWS.d/next/Library/2026-07-12-00-00-00.gh-issue-85943.8f906e.rst
deleted file mode 100644
index 0a93bf2e7b803e3..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-12-00-00-00.gh-issue-85943.8f906e.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Fix :mod:`struct` functions raising :exc:`BytesWarning` under the ``-bb``
-command line option when a :class:`str` format is used after an equal
-:class:`bytes` format (or vice versa). The internal format cache no longer
-mixes :class:`str` and :class:`bytes` keys.
diff --git a/Misc/NEWS.d/next/Library/2026-07-12-10-00-00.gh-issue-98078.fA3lRt.rst b/Misc/NEWS.d/next/Library/2026-07-12-10-00-00.gh-issue-98078.fA3lRt.rst
deleted file mode 100644
index de710283c17b8e5..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-12-10-00-00.gh-issue-98078.fA3lRt.rst
+++ /dev/null
@@ -1,6 +0,0 @@
-Fix :mod:`asyncio` SSL transports not sending the fatal TLS alert to the
-peer when the TLS handshake fails or when receiving corrupted data, and
-not sending the ``close_notify`` alert to the peer when the TLS shutdown
-fails. The peer can now tell why the connection was dropped (for example,
-certificate verification failure or no TLS version in common) instead of
-seeing the connection abruptly closed.
diff --git a/Misc/NEWS.d/next/Library/2026-07-13-10-27-08.gh-issue-153658.A6o4n5.rst b/Misc/NEWS.d/next/Library/2026-07-13-10-27-08.gh-issue-153658.A6o4n5.rst
deleted file mode 100644
index 06385bb7754b127..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-13-10-27-08.gh-issue-153658.A6o4n5.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix :meth:`sqlite3.Connection.iterdump` raising :exc:`sqlite3.OperationalError`
-when a table name contains a single quote. Patch by tonghuaroot.
diff --git a/Misc/NEWS.d/next/Library/2026-07-14-19-45-21.gh-issue-153695.UYdZJZ.rst b/Misc/NEWS.d/next/Library/2026-07-14-19-45-21.gh-issue-153695.UYdZJZ.rst
deleted file mode 100644
index 43d7feebf97d6f2..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-14-19-45-21.gh-issue-153695.UYdZJZ.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Hashing a :class:`sqlite3.Row` that contains an unhashable value now raises
-:exc:`TypeError` instead of :exc:`SystemError`. Patch by tonghuaroot.
diff --git a/Misc/NEWS.d/next/Library/2026-07-15-14-24-18.gh-issue-153761.8jqs67.rst b/Misc/NEWS.d/next/Library/2026-07-15-14-24-18.gh-issue-153761.8jqs67.rst
deleted file mode 100644
index 68e007e66e0396c..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-15-14-24-18.gh-issue-153761.8jqs67.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fix cancelling :meth:`asyncio.loop.sock_accept` dropping a pending connection.
diff --git a/Misc/NEWS.d/next/Library/2026-07-15-15-19-08.gh-issue-104533.pQJxCk.rst b/Misc/NEWS.d/next/Library/2026-07-15-15-19-08.gh-issue-104533.pQJxCk.rst
deleted file mode 100644
index adb08a8f79c1092..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-15-15-19-08.gh-issue-104533.pQJxCk.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Add :func:`ctypes.util.struct` and :class:`ctypes.util.CFieldInfo` for
-generating structure types using annotations.
diff --git a/Misc/NEWS.d/next/Library/2026-07-17-14-00-00.gh-issue-153840.FgXs3e.rst b/Misc/NEWS.d/next/Library/2026-07-17-14-00-00.gh-issue-153840.FgXs3e.rst
new file mode 100644
index 000000000000000..43316035d9b2c27
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-07-17-14-00-00.gh-issue-153840.FgXs3e.rst
@@ -0,0 +1,3 @@
+Escape special characters in ``profiling.sampling`` flamegraph function
+names to prevent markup injection in the generated HTML report. Patch by
+tonghuaroot.
diff --git a/Misc/NEWS.d/next/Library/2026-07-17-14-30-00.gh-issue-153844.pYs7Kq.rst b/Misc/NEWS.d/next/Library/2026-07-17-14-30-00.gh-issue-153844.pYs7Kq.rst
deleted file mode 100644
index cf46eec8513f673..000000000000000
--- a/Misc/NEWS.d/next/Library/2026-07-17-14-30-00.gh-issue-153844.pYs7Kq.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-:func:`symtable.symtable` now accepts an AST object,
-like the builtin :func:`compile`.
diff --git a/Misc/NEWS.d/next/Library/2026-07-20-09-35-32.gh-issue-153144.0a2AoO.rst b/Misc/NEWS.d/next/Library/2026-07-20-09-35-32.gh-issue-153144.0a2AoO.rst
new file mode 100644
index 000000000000000..0d0aac646285e79
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-07-20-09-35-32.gh-issue-153144.0a2AoO.rst
@@ -0,0 +1,4 @@
+:func:`math.atan2` and :func:`math.atan2pi` no longer raise :exc:`ValueError`.
+:func:`cmath.phase` no longer raises :exc:`OverflowError` or :exc:`ValueError`,
+and the values of ``math.atan2(b, a)`` and ``cmath.phase(complex(a, b))`` always
+match. Contributed by High Performance Kernels LLC.
diff --git a/Misc/NEWS.d/next/Library/2026-07-29-12-20-39.gh-issue-127172.Kf3Xa9.rst b/Misc/NEWS.d/next/Library/2026-07-29-12-20-39.gh-issue-127172.Kf3Xa9.rst
new file mode 100644
index 000000000000000..c4bf1f07a2ea577
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-07-29-12-20-39.gh-issue-127172.Kf3Xa9.rst
@@ -0,0 +1,4 @@
+Creating a virtual environment with :mod:`venv` now writes the activation
+scripts using permissions derived from the process umask (and any default
+ACL), consistent with the other files it creates, instead of a fixed mode
+copied from the packaged templates. Patch by tonghuaroot.
diff --git a/Misc/NEWS.d/next/Library/2026-08-01-10-54-39.gh-issue-155031.sTB_n8.rst b/Misc/NEWS.d/next/Library/2026-08-01-10-54-39.gh-issue-155031.sTB_n8.rst
new file mode 100644
index 000000000000000..954e4cc2e54ac04
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-08-01-10-54-39.gh-issue-155031.sTB_n8.rst
@@ -0,0 +1,2 @@
+Propagate to user any permission errors from subprocess attach commands in
+Tachyon
diff --git a/Misc/NEWS.d/next/Library/2026-08-02-08-43-20.gh-issue-155003.VVy9Z_.rst b/Misc/NEWS.d/next/Library/2026-08-02-08-43-20.gh-issue-155003.VVy9Z_.rst
new file mode 100644
index 000000000000000..c41ce1879488b78
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-08-02-08-43-20.gh-issue-155003.VVy9Z_.rst
@@ -0,0 +1,5 @@
+Fix :class:`multiprocessing.shared_memory.SharedMemory` leaking its file
+descriptor and printing an ignored :exc:`BufferError` when garbage collected
+while its :attr:`~multiprocessing.shared_memory.SharedMemory.buf` was still in
+use, for example by a NumPy array. :attr:`!buf` now also stays usable after
+the :class:`!SharedMemory` object is garbage collected.
diff --git a/Misc/NEWS.d/next/Library/2026-08-02-19-08-17.gh-issue-155074.Vj8qL2.rst b/Misc/NEWS.d/next/Library/2026-08-02-19-08-17.gh-issue-155074.Vj8qL2.rst
new file mode 100644
index 000000000000000..70489c9d62f526b
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-08-02-19-08-17.gh-issue-155074.Vj8qL2.rst
@@ -0,0 +1,2 @@
+Fix the pure Python implementation of ``BufferedReader.readinto()`` raising
+:exc:`ValueError` after partially filling the destination buffer.
diff --git a/Misc/NEWS.d/next/Library/2026-08-05-20-30-00.gh-issue-75221.runpyM.rst b/Misc/NEWS.d/next/Library/2026-08-05-20-30-00.gh-issue-75221.runpyM.rst
new file mode 100644
index 000000000000000..77326f3f98bf94a
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-08-05-20-30-00.gh-issue-75221.runpyM.rst
@@ -0,0 +1,4 @@
+:func:`runpy.run_path` and the execution of a directory or a zipfile now
+search the ``__main__`` module only in that directory or zipfile. Previously
+an existing ``__main__`` module located elsewhere on :data:`sys.path` could be
+executed instead.
diff --git a/Misc/NEWS.d/next/Library/2026-08-08-23-30-00.gh-issue-85681.ntabs.rst b/Misc/NEWS.d/next/Library/2026-08-08-23-30-00.gh-issue-85681.ntabs.rst
new file mode 100644
index 000000000000000..b673a69a70620b9
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-08-08-23-30-00.gh-issue-85681.ntabs.rst
@@ -0,0 +1,3 @@
+:func:`!ntpath.abspath` on non-Windows platforms now strips trailing dots and
+spaces like the Windows path normalization does. This makes
+:func:`!ntpath.relpath` and other functions based on it platform independent.
diff --git a/Misc/NEWS.d/next/Library/2026-08-17-06-07-49.gh-issue-155935.lbMPKW.rst b/Misc/NEWS.d/next/Library/2026-08-17-06-07-49.gh-issue-155935.lbMPKW.rst
new file mode 100644
index 000000000000000..21d7ba6a4f758c4
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-08-17-06-07-49.gh-issue-155935.lbMPKW.rst
@@ -0,0 +1 @@
+Fix :meth:`!importlib.machinery.FileFinder.discover` looping forever when the underlying directory scan keeps failing with :exc:`OSError`. A failing scan now ends the listing instead of being retried.
diff --git a/Misc/NEWS.d/next/Library/2026-08-25-09-15-00.gh-issue-154923.tKcr8Q.rst b/Misc/NEWS.d/next/Library/2026-08-25-09-15-00.gh-issue-154923.tKcr8Q.rst
new file mode 100644
index 000000000000000..54c04dcc1ecc7b0
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-08-25-09-15-00.gh-issue-154923.tKcr8Q.rst
@@ -0,0 +1,2 @@
+Fix a crash when creating Tcl interpreters concurrently in different
+threads in the :term:`free-threaded build`.
diff --git a/Misc/NEWS.d/next/Library/2026-09-11-12-43-04.gh-issue-157299.HQ3I4F.rst b/Misc/NEWS.d/next/Library/2026-09-11-12-43-04.gh-issue-157299.HQ3I4F.rst
new file mode 100644
index 000000000000000..fe9483325829c44
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-09-11-12-43-04.gh-issue-157299.HQ3I4F.rst
@@ -0,0 +1,4 @@
+Fix eagerly started :class:`asyncio.Task` objects missing their awaited-by
+edge during the first step. During that step, even a plain
+:func:`asyncio.create_task` call reports the creating task as an awaiter.
+Patch by Timofey Ivankov.
diff --git a/Misc/NEWS.d/next/Library/2026-09-15-10-30-00.gh-issue-92810.Kx3abc.rst b/Misc/NEWS.d/next/Library/2026-09-15-10-30-00.gh-issue-92810.Kx3abc.rst
new file mode 100644
index 000000000000000..45fc06791f6950f
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-09-15-10-30-00.gh-issue-92810.Kx3abc.rst
@@ -0,0 +1,4 @@
+Speed up :func:`isinstance` and :func:`issubclass` checks against
+:class:`abc.ABCMeta` classes, fix quadratic time and memory usage for large
+class hierarchies, and improve their scaling across threads in the
+free-threaded build. Patch by Kumar Aditya.
diff --git a/Misc/NEWS.d/next/Library/2026-09-23-21-15-00.gh-issue-158032.k4nT9p.rst b/Misc/NEWS.d/next/Library/2026-09-23-21-15-00.gh-issue-158032.k4nT9p.rst
new file mode 100644
index 000000000000000..0e0a565519fa8e6
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-09-23-21-15-00.gh-issue-158032.k4nT9p.rst
@@ -0,0 +1,2 @@
+Fix a crash in :meth:`xml.etree.ElementTree.Element.iter` when a tag's
+equality comparison replaces that tag.
diff --git a/Misc/NEWS.d/next/Library/2026-09-26-09-44-59.gh-issue-158166.lVGCsI.rst b/Misc/NEWS.d/next/Library/2026-09-26-09-44-59.gh-issue-158166.lVGCsI.rst
new file mode 100644
index 000000000000000..528160a6709369a
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-09-26-09-44-59.gh-issue-158166.lVGCsI.rst
@@ -0,0 +1 @@
+Fix the type of the ``msg`` attribute of :exc:`xml.etree.ElementTree.ParseError` in the pure Python implementation: it is now a string, as in the C implementation.
diff --git a/Misc/NEWS.d/next/Library/2026-09-27-13-04-02.gh-issue-42550.sqYlvB.rst b/Misc/NEWS.d/next/Library/2026-09-27-13-04-02.gh-issue-42550.sqYlvB.rst
new file mode 100644
index 000000000000000..af8fe2630ba440f
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-09-27-13-04-02.gh-issue-42550.sqYlvB.rst
@@ -0,0 +1,3 @@
+:class:`http.client.HTTPConnection` now waits for a ``100 Continue``
+response before sending body content if the ``Expect: 100-Continue`` header
+is set.
diff --git a/Misc/NEWS.d/next/Library/2026-10-02-22-32-10.gh-issue-156145.9l_tZb.rst b/Misc/NEWS.d/next/Library/2026-10-02-22-32-10.gh-issue-156145.9l_tZb.rst
new file mode 100644
index 000000000000000..b29e6b8be6dc882
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-10-02-22-32-10.gh-issue-156145.9l_tZb.rst
@@ -0,0 +1,3 @@
+The following functions no longer set ``errno`` to zero: :func:`cmath.phase`,
+:func:`math.atan2`, :func:`math.atan2pi`, and :func:`math.copysign`.
+Contributed by High Performance Kernels LLC.
diff --git a/Misc/NEWS.d/next/Library/2026-10-07-21-54-29.gh-issue-158955.Ey4Iei.rst b/Misc/NEWS.d/next/Library/2026-10-07-21-54-29.gh-issue-158955.Ey4Iei.rst
new file mode 100644
index 000000000000000..e7e613ec77e6945
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-10-07-21-54-29.gh-issue-158955.Ey4Iei.rst
@@ -0,0 +1 @@
+Fixed PyREPL rendering on WSL by avoiding the unnecessary INS terminal sequence when appending a character at the end of a line. INS remains used for true mid-line insertions, with regression coverage added.
diff --git a/Misc/NEWS.d/next/Library/2026-10-08-01-33-46.gh-issue-158986.iXoUCo.rst b/Misc/NEWS.d/next/Library/2026-10-08-01-33-46.gh-issue-158986.iXoUCo.rst
new file mode 100644
index 000000000000000..f234a601a97103d
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-10-08-01-33-46.gh-issue-158986.iXoUCo.rst
@@ -0,0 +1,4 @@
+Fix :mod:`profiling.sampling` reporting modules in a ``site-packages``
+directory located inside the standard library directory as standard library
+modules. The heatmap now lists them under "Site Packages" and flamegraph
+labels no longer start with ``site-packages.``.
diff --git a/Misc/NEWS.d/next/Library/2026-10-10-13-35-08.gh-issue-149584.Yq2bF7.rst b/Misc/NEWS.d/next/Library/2026-10-10-13-35-08.gh-issue-149584.Yq2bF7.rst
new file mode 100644
index 000000000000000..7f92a1b19877cd4
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-10-10-13-35-08.gh-issue-149584.Yq2bF7.rst
@@ -0,0 +1,2 @@
+Improve the performance of the Tachyon profiler by avoiding unnecessary remote
+reads of the base frame sentinel. Patch by Maurycy Pawłowski-Wieroński.
diff --git a/Misc/NEWS.d/next/Library/2026-10-10-18-56-26.gh-issue-159130.3AIHqh.rst b/Misc/NEWS.d/next/Library/2026-10-10-18-56-26.gh-issue-159130.3AIHqh.rst
new file mode 100644
index 000000000000000..f4ff555a25e7010
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-10-10-18-56-26.gh-issue-159130.3AIHqh.rst
@@ -0,0 +1,2 @@
+Fix :mod:`!_remote_debugging` returning a different thread when the selected
+thread does not match the profiling mode with ``only_active_thread=True``.
diff --git a/Misc/NEWS.d/next/Library/2026-10-13-11-54-07.gh-issue-159301.Kq3Vx8.rst b/Misc/NEWS.d/next/Library/2026-10-13-11-54-07.gh-issue-159301.Kq3Vx8.rst
new file mode 100644
index 000000000000000..067d1d5eac553cf
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-10-13-11-54-07.gh-issue-159301.Kq3Vx8.rst
@@ -0,0 +1,3 @@
+Add symbolic constants for Tk option values which were missing in
+:mod:`!tkinter.constants`, such as ``READONLY``, ``TABULAR``,
+``DETERMINATE``, ``MENUBAR`` and the names of the themed widget states.
diff --git a/Misc/NEWS.d/next/Library/2026-10-18-19-18-20.gh-issue-159645.IOXcpT.rst b/Misc/NEWS.d/next/Library/2026-10-18-19-18-20.gh-issue-159645.IOXcpT.rst
new file mode 100644
index 000000000000000..fde97e6f131cb54
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-10-18-19-18-20.gh-issue-159645.IOXcpT.rst
@@ -0,0 +1,2 @@
+Fix :mod:`profiling.sampling` ``--async-aware`` profiles showing event loop
+frames under tasks. Patch by Timofei Ivankov.
diff --git a/Misc/NEWS.d/next/Library/2026-10-20-12-00-00.gh-issue-87027.PrEvNw.rst b/Misc/NEWS.d/next/Library/2026-10-20-12-00-00.gh-issue-87027.PrEvNw.rst
new file mode 100644
index 000000000000000..504cd054ca464c7
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-10-20-12-00-00.gh-issue-87027.PrEvNw.rst
@@ -0,0 +1,2 @@
+Add :meth:`~ipaddress.IPv4Network.prev_network` and
+:meth:`~ipaddress.IPv6Network.prev_network`. Patch by Faisal Mahmood.
diff --git a/Misc/NEWS.d/next/Library/2026-10-20-12-49-32.gh-issue-159207.Lccezg.rst b/Misc/NEWS.d/next/Library/2026-10-20-12-49-32.gh-issue-159207.Lccezg.rst
new file mode 100644
index 000000000000000..a96098fd211abc6
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-10-20-12-49-32.gh-issue-159207.Lccezg.rst
@@ -0,0 +1,3 @@
+The :mod:`profiling.sampling` binary output format now stores samples in
+independent blocks. This is a breaking format change: Python 3.16 does not
+support reading profiles written in the previous format.
diff --git a/Misc/NEWS.d/next/Library/2026-10-20-23-30-00.gh-issue-159973.Ks9nLm.rst b/Misc/NEWS.d/next/Library/2026-10-20-23-30-00.gh-issue-159973.Ks9nLm.rst
new file mode 100644
index 000000000000000..506c71ca82bdbae
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-10-20-23-30-00.gh-issue-159973.Ks9nLm.rst
@@ -0,0 +1,3 @@
+Fix soft keyword highlighting after blank lines, comment-only lines, and
+dedents in the :ref:`interactive shell `. Patch by Bartosz
+Sławecki.
diff --git a/Misc/NEWS.d/next/Library/2026-10-22-05-23-04.gh-issue-161104.rvNPjJ.rst b/Misc/NEWS.d/next/Library/2026-10-22-05-23-04.gh-issue-161104.rvNPjJ.rst
new file mode 100644
index 000000000000000..acae526043a2979
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-10-22-05-23-04.gh-issue-161104.rvNPjJ.rst
@@ -0,0 +1,4 @@
+Fix :meth:`http.client.HTTPConnection.set_tunnel` accepting a tunnel host
+containing a non-ASCII character that IDNA encoding maps to a space, such as
+U+00A0 NO-BREAK SPACE. Connecting now raises :exc:`ValueError`, as it already
+does for an ASCII space.
diff --git a/Misc/NEWS.d/next/Library/2026-10-22-21-19-51.gh-issue-160397.E-RwgUgm.rst b/Misc/NEWS.d/next/Library/2026-10-22-21-19-51.gh-issue-160397.E-RwgUgm.rst
new file mode 100644
index 000000000000000..bd880cfe1eaff32
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-10-22-21-19-51.gh-issue-160397.E-RwgUgm.rst
@@ -0,0 +1,5 @@
+The C implementation of :mod:`warnings` no longer takes the warnings lock
+when emitting a warning, so user code such as a custom
+:func:`~warnings.showwarning` no longer runs with the lock held. On the
+:term:`free-threaded build`, the filter search and the registry updates use
+per-object critical sections instead.
diff --git a/Misc/NEWS.d/next/Library/2026-10-24-18-00-00.gh-issue-160601.Utf8Bin.rst b/Misc/NEWS.d/next/Library/2026-10-24-18-00-00.gh-issue-160601.Utf8Bin.rst
new file mode 100644
index 000000000000000..b0b5264ea341c4c
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-10-24-18-00-00.gh-issue-160601.Utf8Bin.rst
@@ -0,0 +1,3 @@
+Fix a :exc:`UnicodeEncodeError` in :mod:`profiling.sampling` binary mode
+when a sampled filename or function name contains surrogate characters.
+These characters are now written as backslash escapes in the binary file.
diff --git a/Misc/NEWS.d/next/Library/2026-10-26-21-14-17.gh-issue-160735.IIUifI.rst b/Misc/NEWS.d/next/Library/2026-10-26-21-14-17.gh-issue-160735.IIUifI.rst
new file mode 100644
index 000000000000000..cf64610a9e62590
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-10-26-21-14-17.gh-issue-160735.IIUifI.rst
@@ -0,0 +1,2 @@
+Fix Tachyon's Gecko export closing open markers too early when replaying a
+binary profile whose thread samples arrive out of time order.
diff --git a/Misc/NEWS.d/next/Library/2026-10-30-19-04-37.gh-issue-160900.007288.rst b/Misc/NEWS.d/next/Library/2026-10-30-19-04-37.gh-issue-160900.007288.rst
new file mode 100644
index 000000000000000..4bc5737ccaf8bd5
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-10-30-19-04-37.gh-issue-160900.007288.rst
@@ -0,0 +1 @@
+Allow :func:`fnmatch.filter` and :func:`fnmatch.filterfalse` to accept :term:`path-like objects `.
diff --git a/Misc/NEWS.d/next/Library/2026-10-30-23-05-00.gh-issue-160976.GeCk0P.rst b/Misc/NEWS.d/next/Library/2026-10-30-23-05-00.gh-issue-160976.GeCk0P.rst
new file mode 100644
index 000000000000000..142d56140b0ce16
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-10-30-23-05-00.gh-issue-160976.GeCk0P.rst
@@ -0,0 +1,2 @@
+Fix the Gecko reporter (``--gecko``) in :mod:`profiling.sampling` to record
+full source file paths.
diff --git a/Misc/NEWS.d/next/Library/2026-11-01-05-05-38.gh-issue-161060.YOZsVl.rst b/Misc/NEWS.d/next/Library/2026-11-01-05-05-38.gh-issue-161060.YOZsVl.rst
new file mode 100644
index 000000000000000..8d55e0162c452ed
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-01-05-05-38.gh-issue-161060.YOZsVl.rst
@@ -0,0 +1,5 @@
+Fix a crash in :mod:`xml.parsers.expat` when a handler raises an exception,
+or the :meth:`~xml.parsers.expat.xmlparser.DefaultHandler` or
+:meth:`~xml.parsers.expat.xmlparser.DefaultHandlerExpand` handler is unset,
+while a token longer than 1024 bytes, such as a comment, is being reported to
+the default handler from a document that is not encoded in UTF-8.
diff --git a/Misc/NEWS.d/next/Library/2026-11-03-08-21-06.gh-issue-161184.PIhcD9.rst b/Misc/NEWS.d/next/Library/2026-11-03-08-21-06.gh-issue-161184.PIhcD9.rst
new file mode 100644
index 000000000000000..3b15925773b99ec
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-03-08-21-06.gh-issue-161184.PIhcD9.rst
@@ -0,0 +1,6 @@
+Speed up attribute access on instances of :mod:`io` classes and their
+subclasses by storing instance attributes and weak references in the object
+pre-header. The ``__dictoffset__`` and ``__weakrefoffset__`` attributes
+of these classes now report the managed offsets, and C extension types that
+subclass an :mod:`io` class can no longer declare their own ``__dictoffset__``
+or ``__weaklistoffset__`` member.
diff --git a/Misc/NEWS.d/next/Library/2026-11-03-17-54-07.gh-issue-159637.0p15UL.rst b/Misc/NEWS.d/next/Library/2026-11-03-17-54-07.gh-issue-159637.0p15UL.rst
new file mode 100644
index 000000000000000..cd820a2868f52ec
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-03-17-54-07.gh-issue-159637.0p15UL.rst
@@ -0,0 +1,4 @@
+Fix :meth:`Document.renameNode() ` in
+:mod:`xml.dom.minidom` rejecting a valid rename of an attribute to a
+prefixed name, and removing the attribute from its element when a rename
+is rejected.
diff --git a/Misc/NEWS.d/next/Library/2026-11-05-22-26-44.gh-issue-161452.YfFfjq.rst b/Misc/NEWS.d/next/Library/2026-11-05-22-26-44.gh-issue-161452.YfFfjq.rst
new file mode 100644
index 000000000000000..7ac5f49096c5401
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-05-22-26-44.gh-issue-161452.YfFfjq.rst
@@ -0,0 +1,3 @@
+Fix the :mod:`random` :ref:`command-line interface `
+printing a random float for a zero or negative integer input instead of
+failing like ``--integer`` does.
diff --git a/Misc/NEWS.d/next/Library/2026-11-06-12-00-00.gh-issue-160978.Kx7mQa.rst b/Misc/NEWS.d/next/Library/2026-11-06-12-00-00.gh-issue-160978.Kx7mQa.rst
new file mode 100644
index 000000000000000..be5cc945f4eb61d
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-06-12-00-00.gh-issue-160978.Kx7mQa.rst
@@ -0,0 +1,3 @@
+Fix :mod:`ctypes` handing out distinct array types for the same item type
+and length when the array type is created concurrently from several
+threads.
diff --git a/Misc/NEWS.d/next/Library/2026-11-06-20-12-44.gh-issue-161502.rYZtwK.rst b/Misc/NEWS.d/next/Library/2026-11-06-20-12-44.gh-issue-161502.rYZtwK.rst
new file mode 100644
index 000000000000000..f284c37bd738945
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-06-20-12-44.gh-issue-161502.rYZtwK.rst
@@ -0,0 +1,3 @@
+Fix missing tasks in ``python -m asyncio pstree`` output when tasks are
+connected through an intermediate :class:`asyncio.Future`. Patch by Timofei
+Ivankov
diff --git a/Misc/NEWS.d/next/Library/2026-11-07-12-00-00.gh-issue-51540.Tunn07.rst b/Misc/NEWS.d/next/Library/2026-11-07-12-00-00.gh-issue-51540.Tunn07.rst
new file mode 100644
index 000000000000000..9efd6dd0cca7db7
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-07-12-00-00.gh-issue-51540.Tunn07.rst
@@ -0,0 +1,8 @@
+:class:`urllib.request.ProxyBasicAuthHandler` and
+:class:`urllib.request.ProxyDigestAuthHandler` now handle a ``407 Proxy
+Authentication Required`` response to the CONNECT request for an ``https``
+URL. :mod:`http.client` raises the new :exc:`~http.client.ProxyTunnelError`,
+a subclass of :exc:`OSError`, when a proxy rejects a CONNECT request.
+For such a proxy, :class:`~urllib.request.ProxyDigestAuthHandler` computes
+the digest over the CONNECT request (``CONNECT host:port``) instead of the
+request sent to the origin server.
diff --git a/Misc/NEWS.d/next/Library/2026-11-07-20-26-52.gh-issue-161571.qQ8OhA.rst b/Misc/NEWS.d/next/Library/2026-11-07-20-26-52.gh-issue-161571.qQ8OhA.rst
new file mode 100644
index 000000000000000..804b8a494ca4320
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-07-20-26-52.gh-issue-161571.qQ8OhA.rst
@@ -0,0 +1,3 @@
+Fix a crash in :func:`curses.tparm` for capabilities with parameters
+that they format as strings, such as ``Ms`` of xterm.
+Bytes objects are now accepted for these parameters.
diff --git a/Misc/NEWS.d/next/Library/2026-11-08-19-29-54.gh-issue-141998.8vum0w.rst b/Misc/NEWS.d/next/Library/2026-11-08-19-29-54.gh-issue-141998.8vum0w.rst
new file mode 100644
index 000000000000000..633c27d55175a3d
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-08-19-29-54.gh-issue-141998.8vum0w.rst
@@ -0,0 +1,2 @@
+Do not syntax highlight text typed in response to :func:`input` in the
+:term:`REPL`.
diff --git a/Misc/NEWS.d/next/Library/2026-11-10-13-28-10.gh-issue-161746.HxgY9R.rst b/Misc/NEWS.d/next/Library/2026-11-10-13-28-10.gh-issue-161746.HxgY9R.rst
new file mode 100644
index 000000000000000..293bf5fb27a7550
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-10-13-28-10.gh-issue-161746.HxgY9R.rst
@@ -0,0 +1,3 @@
+Speed up :meth:`datetime.datetime.fromordinal` by about 15% (30% in the
+pure-Python implementation) by using the `Neri–Schneider algorithm
+`__.
diff --git a/Misc/NEWS.d/next/Library/2026-11-10-23-51-25.gh-issue-161788.J8vQmK.rst b/Misc/NEWS.d/next/Library/2026-11-10-23-51-25.gh-issue-161788.J8vQmK.rst
new file mode 100644
index 000000000000000..34d3cff85123c79
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-10-23-51-25.gh-issue-161788.J8vQmK.rst
@@ -0,0 +1 @@
+:func:`shutil.which` now accepts path-like objects for the command.
diff --git a/Misc/NEWS.d/next/Library/2026-11-11-12-00-00.gh-issue-135893.cTyp3s.rst b/Misc/NEWS.d/next/Library/2026-11-11-12-00-00.gh-issue-135893.cTyp3s.rst
new file mode 100644
index 000000000000000..bddd3d817ab1cbf
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-11-12-00-00.gh-issue-135893.cTyp3s.rst
@@ -0,0 +1,3 @@
+Fix a regression where importing :mod:`ctypes` could leave an extra file
+descriptor open on some Linux systems, or hang in x86-64 macOS applications
+signed with the hardened runtime.
diff --git a/Misc/NEWS.d/next/Library/2026-11-11-14-29-41.gh-issue-161808.S9dK2p.rst b/Misc/NEWS.d/next/Library/2026-11-11-14-29-41.gh-issue-161808.S9dK2p.rst
new file mode 100644
index 000000000000000..76626ca60b5b5a9
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-11-14-29-41.gh-issue-161808.S9dK2p.rst
@@ -0,0 +1,2 @@
+Raise :exc:`SyntaxError` instead of :exc:`KeyError` for unsupported XPath
+tokens in :mod:`xml.etree.ElementTree` path searches.
diff --git a/Misc/NEWS.d/next/Library/2026-11-11-20-50-03.gh-issue-156812.nqPw30.rst b/Misc/NEWS.d/next/Library/2026-11-11-20-50-03.gh-issue-156812.nqPw30.rst
new file mode 100644
index 000000000000000..741a2d9d42cf166
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-11-20-50-03.gh-issue-156812.nqPw30.rst
@@ -0,0 +1,10 @@
+Serializing a document type declaration, a comment or a processing
+instruction in :mod:`xml.dom.minidom` now checks the structural rules of XML.
+A system literal is now quoted with the quote which it does not contain,
+and :exc:`ValueError` is raised for an invalid public identifier,
+for a literal containing both quotes,
+for a public identifier without a system identifier,
+for a comment ending with ``-``,
+and for a processing instruction containing ``?>`` in the data
+or using the reserved target ``xml``.
+The characters are still not checked.
diff --git a/Misc/NEWS.d/next/Library/2026-11-12-08-38-09.gh-issue-161840.YcEVjO.rst b/Misc/NEWS.d/next/Library/2026-11-12-08-38-09.gh-issue-161840.YcEVjO.rst
new file mode 100644
index 000000000000000..f1e63af06fef87c
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-12-08-38-09.gh-issue-161840.YcEVjO.rst
@@ -0,0 +1,3 @@
+Propagate exceptions raised while getting the length of the assigned value
+in :mod:`ctypes` array slice assignment instead of replacing them with a
+:exc:`ValueError`.
diff --git a/Misc/NEWS.d/next/Library/2026-11-12-17-53-13.gh-issue-161861.Kf7Qm2.rst b/Misc/NEWS.d/next/Library/2026-11-12-17-53-13.gh-issue-161861.Kf7Qm2.rst
new file mode 100644
index 000000000000000..febea87b27d5a1b
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-12-17-53-13.gh-issue-161861.Kf7Qm2.rst
@@ -0,0 +1,2 @@
+Preserve the active request's ``continue_timeout`` when a second
+:meth:`~http.client.HTTPConnection.putrequest` call is rejected.
diff --git a/Misc/NEWS.d/next/Library/2026-11-13-09-49-13.gh-issue-152845.ZipFlags.rst b/Misc/NEWS.d/next/Library/2026-11-13-09-49-13.gh-issue-152845.ZipFlags.rst
new file mode 100644
index 000000000000000..70cf5134d3fe9f9
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-13-09-49-13.gh-issue-152845.ZipFlags.rst
@@ -0,0 +1,3 @@
+Fix :mod:`zipfile` dropping the UTF-8 (EFS) flag for existing entries
+when rewriting an archive in append mode, and honor an explicitly set
+flag on new entries. Patch by Kasra Ghodsi.
diff --git a/Misc/NEWS.d/next/Library/2026-11-13-12-01-53.gh-issue-161945.X8oFTq.rst b/Misc/NEWS.d/next/Library/2026-11-13-12-01-53.gh-issue-161945.X8oFTq.rst
new file mode 100644
index 000000000000000..95adcdb8c25ba17
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-13-12-01-53.gh-issue-161945.X8oFTq.rst
@@ -0,0 +1,3 @@
+:meth:`zipfile.ZipFile.open` now raises :exc:`~zipfile.BadZipFile` when a
+member's compression method differs between the central directory and the
+local file header.
diff --git a/Misc/NEWS.d/next/Library/2026-11-14-21-04-56.gh-issue-161996.35uL2d.rst b/Misc/NEWS.d/next/Library/2026-11-14-21-04-56.gh-issue-161996.35uL2d.rst
new file mode 100644
index 000000000000000..561bb62d6537073
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-14-21-04-56.gh-issue-161996.35uL2d.rst
@@ -0,0 +1,2 @@
+Fix a crash in :meth:`concurrent.interpreters.Interpreter.exec` when the
+uncaught exception's ``__str__`` raises.
diff --git a/Misc/NEWS.d/next/Library/2026-11-15-02-06-21.gh-issue-162028.jAnDAg.rst b/Misc/NEWS.d/next/Library/2026-11-15-02-06-21.gh-issue-162028.jAnDAg.rst
new file mode 100644
index 000000000000000..a52a970039d3df0
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-15-02-06-21.gh-issue-162028.jAnDAg.rst
@@ -0,0 +1,2 @@
+Fix the position reported by the pure Python :mod:`json` decoder for an
+invalid escape. It now points to the backslash, like the C decoder.
diff --git a/Misc/NEWS.d/next/Library/2026-11-15-03-10-31.gh-issue-162031.2k-3CG.rst b/Misc/NEWS.d/next/Library/2026-11-15-03-10-31.gh-issue-162031.2k-3CG.rst
new file mode 100644
index 000000000000000..01f1311c735d9b1
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-15-03-10-31.gh-issue-162031.2k-3CG.rst
@@ -0,0 +1,3 @@
+Fix :meth:`io.BufferedIOBase.readinto` and :meth:`~io.BufferedIOBase.readinto1`
+raising :exc:`TypeError` instead of returning ``None`` when called on a
+non-blocking stream with no data available.
diff --git a/Misc/NEWS.d/next/Library/2026-11-15-17-30-00.gh-issue-162016.pNbStd.rst b/Misc/NEWS.d/next/Library/2026-11-15-17-30-00.gh-issue-162016.pNbStd.rst
new file mode 100644
index 000000000000000..5fa107c8c64271f
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-15-17-30-00.gh-issue-162016.pNbStd.rst
@@ -0,0 +1,4 @@
+Fix :meth:`subprocess.Popen.communicate` hanging or blocking past its
+*timeout* while writing to the child's stdin on macOS and FreeBSD. This
+works around a kernel bug most likely seen on loaded hosts with many pipes
+in active use at once.
diff --git a/Misc/NEWS.d/next/Library/2026-11-16-16-10-42.gh-issue-157579.6choQ_.rst b/Misc/NEWS.d/next/Library/2026-11-16-16-10-42.gh-issue-157579.6choQ_.rst
new file mode 100644
index 000000000000000..1bd89a77b5995c1
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-16-16-10-42.gh-issue-157579.6choQ_.rst
@@ -0,0 +1,3 @@
+The error handler :class:`~tempfile.TemporaryDirectory` uses to clean up
+unreadable and inaccessible files no longer fails for temporary directories
+created using :class:`bytes` paths.
diff --git a/Misc/NEWS.d/next/Library/2026-11-18-12-18-53.gh-issue-149584.rDchNk.rst b/Misc/NEWS.d/next/Library/2026-11-18-12-18-53.gh-issue-149584.rDchNk.rst
new file mode 100644
index 000000000000000..2d0e9d203cf6b3e
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-18-12-18-53.gh-issue-149584.rDchNk.rst
@@ -0,0 +1,3 @@
+Read stack chunks directly in :mod:`profiling.sampling`, without the page
+cache. This removes a redundant retry on macOS that can read a replacement
+chunk after the target process reuses the same address.
diff --git a/Misc/NEWS.d/next/Library/2026-11-18-18-28-37.gh-issue-162230.ezR86S.rst b/Misc/NEWS.d/next/Library/2026-11-18-18-28-37.gh-issue-162230.ezR86S.rst
new file mode 100644
index 000000000000000..00b96c972ece6f6
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-18-18-28-37.gh-issue-162230.ezR86S.rst
@@ -0,0 +1,3 @@
+Speed up :meth:`!io.BufferedRWPair.readline`. If a non-blocking read would
+block, return the bytes read so far (possibly ``b''``). Previously, it raised
+:exc:`OSError`.
diff --git a/Misc/NEWS.d/next/Library/2026-11-19-17-55-31.gh-issue-162282.1WW-xb.rst b/Misc/NEWS.d/next/Library/2026-11-19-17-55-31.gh-issue-162282.1WW-xb.rst
new file mode 100644
index 000000000000000..0d72db13e0c2bec
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-19-17-55-31.gh-issue-162282.1WW-xb.rst
@@ -0,0 +1 @@
+Fix quadratic-time cost in :meth:`urllib.robotparser.RobotFileParser.parse` when a single group contains many identical ``User-agent:`` lines.
diff --git a/Misc/NEWS.d/next/Library/2026-11-19-19-44-33.gh-issue-162285.wnH4aQ.rst b/Misc/NEWS.d/next/Library/2026-11-19-19-44-33.gh-issue-162285.wnH4aQ.rst
new file mode 100644
index 000000000000000..ff955a30053d273
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-19-19-44-33.gh-issue-162285.wnH4aQ.rst
@@ -0,0 +1,3 @@
+Fix quadratic memory use in :mod:`xmlrpc.client` when decoding malformed
+XML-RPC packets containing nested string elements. This can cause ``loads()``
+to raise on malformed packets that were previously silently accepted.
diff --git a/Misc/NEWS.d/next/Library/2026-11-19-22-01-29.gh-issue-162246.y3L8nP.rst b/Misc/NEWS.d/next/Library/2026-11-19-22-01-29.gh-issue-162246.y3L8nP.rst
new file mode 100644
index 000000000000000..702b38215ed6efb
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-19-22-01-29.gh-issue-162246.y3L8nP.rst
@@ -0,0 +1,2 @@
+Fix :class:`io.BufferedRWPair` losing buffered writes on deallocation when the
+reader and writer share a raw stream.
diff --git a/Misc/NEWS.d/next/Library/2026-11-20-09-30-00.gh-issue-162217.wC7sHd.rst b/Misc/NEWS.d/next/Library/2026-11-20-09-30-00.gh-issue-162217.wC7sHd.rst
new file mode 100644
index 000000000000000..be12568cb8f7fec
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-20-09-30-00.gh-issue-162217.wC7sHd.rst
@@ -0,0 +1,4 @@
+Fix :exc:`asyncio.InvalidStateError` being logged when the standard input of
+an :mod:`asyncio` subprocess is closed after a task waiting in
+:meth:`proc.stdin.wait_closed() ` was
+cancelled.
diff --git a/Misc/NEWS.d/next/Library/2026-11-21-11-11-34.gh-issue-162246.jN-ORE.rst b/Misc/NEWS.d/next/Library/2026-11-21-11-11-34.gh-issue-162246.jN-ORE.rst
new file mode 100644
index 000000000000000..d596bd87ad31e95
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-21-11-11-34.gh-issue-162246.jN-ORE.rst
@@ -0,0 +1,2 @@
+Fix a reference leak in :class:`io.BufferedRWPair` when :meth:`~object.__init__`
+is called more than once: the previous reader and writer are now released.
diff --git a/Misc/NEWS.d/next/Library/2026-11-21-13-50-09.gh-issue-162061.UbvZxJ.rst b/Misc/NEWS.d/next/Library/2026-11-21-13-50-09.gh-issue-162061.UbvZxJ.rst
new file mode 100644
index 000000000000000..db5b2e79b5b2db0
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-21-13-50-09.gh-issue-162061.UbvZxJ.rst
@@ -0,0 +1,2 @@
+Fix the asyncio call graph to show which task awaits :func:`asyncio.gather`.
+Patch by Timofei Ivankov.
diff --git a/Misc/NEWS.d/next/Library/2026-11-21-20-51-29.gh-issue-162395.l8Vlxo.rst b/Misc/NEWS.d/next/Library/2026-11-21-20-51-29.gh-issue-162395.l8Vlxo.rst
new file mode 100644
index 000000000000000..563686f8561aa78
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-21-20-51-29.gh-issue-162395.l8Vlxo.rst
@@ -0,0 +1,2 @@
+Fix the asyncio call graph to show which task awaits the future returned by
+:func:`asyncio.shield`. Patch by Timofei Ivankov.
diff --git a/Misc/NEWS.d/next/Library/2026-11-22-15-53-58.gh-issue-162350.2xG9ZI.rst b/Misc/NEWS.d/next/Library/2026-11-22-15-53-58.gh-issue-162350.2xG9ZI.rst
new file mode 100644
index 000000000000000..df101c5386cb45e
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-22-15-53-58.gh-issue-162350.2xG9ZI.rst
@@ -0,0 +1,3 @@
+Add ``@vectorcall`` for :class:`asyncio.Future` and :class:`asyncio.Task`
+constructors. The performance boost is 33% for the future creation and 15%
+for the task.
diff --git a/Misc/NEWS.d/next/Library/2026-11-22-15-56-36.gh-issue-162282.QjKIag.rst b/Misc/NEWS.d/next/Library/2026-11-22-15-56-36.gh-issue-162282.QjKIag.rst
new file mode 100644
index 000000000000000..70f534e8f9215ed
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-22-15-56-36.gh-issue-162282.QjKIag.rst
@@ -0,0 +1,3 @@
+Fix quadratic-time cost in :mod:`urllib.robotparser` when many groups share
+a ``User-agent:``, and when a group with many user agents is checked for
+a user agent that is not listed explicitly.
diff --git a/Misc/NEWS.d/next/Library/2026-11-23-02-10-10.gh-issue-162467.6hMRI-.rst b/Misc/NEWS.d/next/Library/2026-11-23-02-10-10.gh-issue-162467.6hMRI-.rst
new file mode 100644
index 000000000000000..fccff39902eb5e5
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-23-02-10-10.gh-issue-162467.6hMRI-.rst
@@ -0,0 +1,3 @@
+Speed up :meth:`datetime.timedelta.total_seconds` and
+:meth:`datetime.datetime.timestamp` on aware datetimes. Patch by Maurycy
+Pawłowski-Wieroński.
diff --git a/Misc/NEWS.d/next/Library/2026-11-24-12-31-49.gh-issue-159865.aB3eGx.rst b/Misc/NEWS.d/next/Library/2026-11-24-12-31-49.gh-issue-159865.aB3eGx.rst
new file mode 100644
index 000000000000000..aea5534e1dffc1a
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-24-12-31-49.gh-issue-159865.aB3eGx.rst
@@ -0,0 +1,2 @@
+Fix :mod:`profiling.sampling` dropping exception-mode samples when a thread
+blocks inside an exception handler.
diff --git a/Misc/NEWS.d/next/Library/2026-11-24-15-30-00.gh-issue-84256.Fz7Rk2.rst b/Misc/NEWS.d/next/Library/2026-11-24-15-30-00.gh-issue-84256.Fz7Rk2.rst
new file mode 100644
index 000000000000000..85b5245b68f7e50
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-24-15-30-00.gh-issue-84256.Fz7Rk2.rst
@@ -0,0 +1,3 @@
+Fix a crash in :mod:`tkinter` on Windows when a Tk event handler, such as
+a ```` binding, is called while another event loop is running,
+for example when the window is resized while a native dialog is shown.
diff --git a/Misc/NEWS.d/next/Library/2026-11-24-17-00-00.gh-issue-140488.Bw4tIq.rst b/Misc/NEWS.d/next/Library/2026-11-24-17-00-00.gh-issue-140488.Bw4tIq.rst
new file mode 100644
index 000000000000000..ad13320d20a82d2
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-24-17-00-00.gh-issue-140488.Bw4tIq.rst
@@ -0,0 +1,3 @@
+The :mod:`tkinter` event loop running at the interactive prompt no longer
+polls on Unix if Tcl is threaded. It now waits for events or input, so the
+process does not wake up every few milliseconds while idle.
diff --git a/Misc/NEWS.d/next/Library/2026-11-24-17-56-46.gh-issue-159207.3PCgei.rst b/Misc/NEWS.d/next/Library/2026-11-24-17-56-46.gh-issue-159207.3PCgei.rst
new file mode 100644
index 000000000000000..b80c2f7d2a3e93d
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-24-17-56-46.gh-issue-159207.3PCgei.rst
@@ -0,0 +1,4 @@
+Reduce the memory used by :mod:`profiling.sampling` when replaying binary
+profiles on Linux and Windows. Sample data is now read one block at a time
+instead of being loaded into memory in full, so the memory used for samples
+stays small even for very long captures.
diff --git a/Misc/NEWS.d/next/Library/2026-11-24-19-00-00.gh-issue-153020.Hk2vTs.rst b/Misc/NEWS.d/next/Library/2026-11-24-19-00-00.gh-issue-153020.Hk2vTs.rst
new file mode 100644
index 000000000000000..7c2a81de7cf8bb2
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-24-19-00-00.gh-issue-153020.Hk2vTs.rst
@@ -0,0 +1,6 @@
+Fix a crash in :mod:`tkinter` at the interactive prompt if the first Tcl
+interpreter was created in a thread which has since exited. The event hook
+which runs Tcl events while waiting for input is also no longer removed when
+an interpreter is deleted in other thread while other interpreters still
+exist, and its state no longer has data races in the :term:`free-threaded
+build`.
diff --git a/Misc/NEWS.d/next/Library/2026-11-25-20-49-22.gh-issue-162622.qAs2pK.rst b/Misc/NEWS.d/next/Library/2026-11-25-20-49-22.gh-issue-162622.qAs2pK.rst
new file mode 100644
index 000000000000000..1f6c1b8cf6fe3e2
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-25-20-49-22.gh-issue-162622.qAs2pK.rst
@@ -0,0 +1,2 @@
+Preserve literal braces in f-string and t-string format specifiers when
+using :func:`ast.unparse`.
diff --git a/Misc/NEWS.d/next/Library/2026-11-25-21-00-00.gh-issue-162647.Qm4Tsx.rst b/Misc/NEWS.d/next/Library/2026-11-25-21-00-00.gh-issue-162647.Qm4Tsx.rst
new file mode 100644
index 000000000000000..cf069c8985d8710
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-25-21-00-00.gh-issue-162647.Qm4Tsx.rst
@@ -0,0 +1,4 @@
+Fix :mod:`tkinter` when Tcl interpreters run :meth:`!mainloop` in different
+threads. :meth:`!quit` no longer stops the main loop of other interpreter,
+and stops the main loop even if it waits for events. An exception raised in
+a callback is no longer raised by the main loop in other thread.
diff --git a/Misc/NEWS.d/next/Library/2026-11-26-12-00-00.gh-issue-162650.Nm8Dsq.rst b/Misc/NEWS.d/next/Library/2026-11-26-12-00-00.gh-issue-162650.Nm8Dsq.rst
new file mode 100644
index 000000000000000..0f4108e07b76a51
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-26-12-00-00.gh-issue-162650.Nm8Dsq.rst
@@ -0,0 +1,3 @@
+Fix :mod:`tkinter` calls from other threads failing with :exc:`RuntimeError`
+after a nested :meth:`!mainloop` exited, for example after
+:meth:`!SimpleDialog.go` returned.
diff --git a/Misc/NEWS.d/next/Library/2026-11-26-14-05-07.gh-issue-138121.-AVsWv.rst b/Misc/NEWS.d/next/Library/2026-11-26-14-05-07.gh-issue-138121.-AVsWv.rst
new file mode 100644
index 000000000000000..7348b5cb23a1943
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-26-14-05-07.gh-issue-138121.-AVsWv.rst
@@ -0,0 +1,2 @@
+:meth:`asyncio.Lock.locked` now returns ``True`` when it has active waiters.
+Contributed by Emerson Beckwith.
diff --git a/Misc/NEWS.d/next/Library/README.rst b/Misc/NEWS.d/next/Library/README.rst
index 178ac664cc0be1d..6d2d30eca0fd050 100644
--- a/Misc/NEWS.d/next/Library/README.rst
+++ b/Misc/NEWS.d/next/Library/README.rst
@@ -1,3 +1 @@
-Put news entry `blurb`_ files for the *Library* section in this directory.
-
-.. _blurb: https://pypi.org/project/blurb/
+Put news entry ``blurb`` files for the *Library* section in this directory.
diff --git a/Misc/NEWS.d/next/Security/2026-01-16-11-58-19.gh-issue-143927.aviFeG.rst b/Misc/NEWS.d/next/Security/2026-01-16-11-58-19.gh-issue-143927.aviFeG.rst
deleted file mode 100644
index ca554997e5c3963..000000000000000
--- a/Misc/NEWS.d/next/Security/2026-01-16-11-58-19.gh-issue-143927.aviFeG.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Normalize all line endings (CR, CRLF, and LF) to LF+TAB when writing
-multi-line configparser values.
diff --git a/Misc/NEWS.d/next/Security/2026-04-26-19-30-45.gh-issue-149018.a9SqWb.rst b/Misc/NEWS.d/next/Security/2026-04-26-19-30-45.gh-issue-149018.a9SqWb.rst
deleted file mode 100644
index d1b5b368684e6a5..000000000000000
--- a/Misc/NEWS.d/next/Security/2026-04-26-19-30-45.gh-issue-149018.a9SqWb.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Improved protection against XML hash-flooding attacks in
-:mod:`xml.parsers.expat` and :mod:`xml.etree.ElementTree` when Python is
-compiled with libExpat 2.8.0 or later.
diff --git a/Misc/NEWS.d/next/Security/2026-04-27-16-36-11.gh-issue-149079.vKl-LM.rst b/Misc/NEWS.d/next/Security/2026-04-27-16-36-11.gh-issue-149079.vKl-LM.rst
deleted file mode 100644
index 4ed22b58f7405f5..000000000000000
--- a/Misc/NEWS.d/next/Security/2026-04-27-16-36-11.gh-issue-149079.vKl-LM.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-Fix a potential denial of service in :func:`unicodedata.normalize`. The
-canonical ordering step of Unicode normalization used a quadratic-time insertion
-sort for reordering combining characters, which could be exploited with
-crafted input containing many combining characters in non-canonical order.
-Replaced with a linear-time counting sort for long runs.
diff --git a/Misc/NEWS.d/next/Security/2026-05-03-21-00-00.gh-issue-149486.tarflt.rst b/Misc/NEWS.d/next/Security/2026-05-03-21-00-00.gh-issue-149486.tarflt.rst
deleted file mode 100644
index 7c69edb683cf80a..000000000000000
--- a/Misc/NEWS.d/next/Security/2026-05-03-21-00-00.gh-issue-149486.tarflt.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-:func:`tarfile.data_filter` now validates link targets using the same
-normalised value that is written to disk, strips trailing separators from
-the member name when resolving a symlink's directory, and rejects link
-members that would replace the destination directory itself. This closes
-several path-traversal bypasses of the ``data`` extraction filter.
diff --git a/Misc/NEWS.d/next/Security/2026-05-08-02-18-54.gh-issue-149474.ujQ-mu.rst b/Misc/NEWS.d/next/Security/2026-05-08-02-18-54.gh-issue-149474.ujQ-mu.rst
deleted file mode 100644
index 48e718b95ebe3ae..000000000000000
--- a/Misc/NEWS.d/next/Security/2026-05-08-02-18-54.gh-issue-149474.ujQ-mu.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix the binary writer in :mod:`profiling.sampling` not firing the audit
-(:pep:`578`) when creating the output file. The writer and the reader now
-accept any path-like object. Patch by Maurycy Pawłowski-Wieroński.
diff --git a/Misc/NEWS.d/next/Security/2026-05-10-18-05-32.gh-issue-87451.XkKB6M.rst b/Misc/NEWS.d/next/Security/2026-05-10-18-05-32.gh-issue-87451.XkKB6M.rst
deleted file mode 100644
index 21a79c3e0e7db74..000000000000000
--- a/Misc/NEWS.d/next/Security/2026-05-10-18-05-32.gh-issue-87451.XkKB6M.rst
+++ /dev/null
@@ -1,6 +0,0 @@
-The :mod:`ftplib` module's undocumented ``ftpcp`` function no longer trusts
-the IPv4 address value returned from the source server in response to the
-``PASV`` command by default, completing the fix for CVE-2021-4189. As with
-:class:`ftplib.FTP`, the former behavior can be re-enabled by setting the
-``trust_server_pasv_ipv4_address`` attribute on the source :class:`ftplib.FTP`
-instance to ``True``. Thanks to Qi Deng at Aurascape AI for the report.
diff --git a/Misc/NEWS.d/next/Security/2026-05-11-21-15-07.gh-issue-149698.OudOcW.rst b/Misc/NEWS.d/next/Security/2026-05-11-21-15-07.gh-issue-149698.OudOcW.rst
deleted file mode 100644
index 3c8671b9a5adc43..000000000000000
--- a/Misc/NEWS.d/next/Security/2026-05-11-21-15-07.gh-issue-149698.OudOcW.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Update bundled `libexpat `_ to version 2.8.1
-for the fix for :cve:`2026-45186`.
diff --git a/Misc/NEWS.d/next/Security/2026-05-18-17-46-00.gh-issue-149835.EebFlk.rst b/Misc/NEWS.d/next/Security/2026-05-18-17-46-00.gh-issue-149835.EebFlk.rst
deleted file mode 100644
index 20cab736552486d..000000000000000
--- a/Misc/NEWS.d/next/Security/2026-05-18-17-46-00.gh-issue-149835.EebFlk.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-:func:`shutil.move` now resolves symlinks via :func:`os.path.realpath`
-when checking whether the destination is inside the source directory,
-preventing a symlink-based bypass of that guard.
diff --git a/Misc/NEWS.d/next/Security/2026-05-30-00-00-00.gh-issue-150743.httpdos.rst b/Misc/NEWS.d/next/Security/2026-05-30-00-00-00.gh-issue-150743.httpdos.rst
deleted file mode 100644
index abc07d91c63fcaf..000000000000000
--- a/Misc/NEWS.d/next/Security/2026-05-30-00-00-00.gh-issue-150743.httpdos.rst
+++ /dev/null
@@ -1,7 +0,0 @@
-:mod:`http.client` now limits the number of chunked-response trailer lines
-it will read to :attr:`~http.client.HTTPConnection.max_response_headers`
-(100 by default), and the number of interim (1xx) responses it will skip
-to 100. A malicious or broken server could previously stream trailer
-lines or ``100 Continue`` responses forever, hanging the client even when
-a socket timeout was in use.
-Reported by ``@YLChen-007`` via GHSA-w4q2-g22w-6fr4.
diff --git a/Misc/NEWS.d/next/Security/2026-05-30-09-36-20.gh-issue-150599.nlHqU-.rst b/Misc/NEWS.d/next/Security/2026-05-30-09-36-20.gh-issue-150599.nlHqU-.rst
deleted file mode 100644
index a37d86cf423f820..000000000000000
--- a/Misc/NEWS.d/next/Security/2026-05-30-09-36-20.gh-issue-150599.nlHqU-.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fix a possible stack buffer overflow in :mod:`bz2` when a
-:class:`bz2.BZ2Decompressor` is reused after a decompression error.
-The decompressor now becomes unusable after libbz2 reports an error.
diff --git a/Misc/NEWS.d/next/Security/2026-06-09-10-23-57.gh-issue-151159.91GpWQ.rst b/Misc/NEWS.d/next/Security/2026-06-09-10-23-57.gh-issue-151159.91GpWQ.rst
deleted file mode 100644
index 735164c1a65ec33..000000000000000
--- a/Misc/NEWS.d/next/Security/2026-06-09-10-23-57.gh-issue-151159.91GpWQ.rst
+++ /dev/null
@@ -1 +0,0 @@
-Update Android and iOS installers to use OpenSSL 3.5.7.
diff --git a/Misc/NEWS.d/next/Security/2026-06-09-23-38-08.gh-issue-151159.ds-9f8.rst b/Misc/NEWS.d/next/Security/2026-06-09-23-38-08.gh-issue-151159.ds-9f8.rst
deleted file mode 100644
index d9251a93b40b2cc..000000000000000
--- a/Misc/NEWS.d/next/Security/2026-06-09-23-38-08.gh-issue-151159.ds-9f8.rst
+++ /dev/null
@@ -1 +0,0 @@
-Update macOS installer to use OpenSSL 3.5.7.
diff --git a/Misc/NEWS.d/next/Security/2026-06-10-13-08-19.gh-issue-151558.mL74i2.rst b/Misc/NEWS.d/next/Security/2026-06-10-13-08-19.gh-issue-151558.mL74i2.rst
deleted file mode 100644
index 74459d5680e21a3..000000000000000
--- a/Misc/NEWS.d/next/Security/2026-06-10-13-08-19.gh-issue-151558.mL74i2.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fixed an vulnerability in the :mod:`tarfile` ``data`` and ``tar`` extraction
-filters where crafted archives could create a symlink pointing outside the
-destination directory. This was a bypass of :cve:`2025-4330`.
diff --git a/Misc/NEWS.d/next/Security/2026-06-16-14-58-02.gh-issue-151544._bexVy.rst b/Misc/NEWS.d/next/Security/2026-06-16-14-58-02.gh-issue-151544._bexVy.rst
deleted file mode 100644
index 418e3b4b9677943..000000000000000
--- a/Misc/NEWS.d/next/Security/2026-06-16-14-58-02.gh-issue-151544._bexVy.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-:file:`Modules/Setup.local` is no longer used as a landmark to discover
-whether Python is running in a source tree, as it could potentially affect
-actual installs. The :file:`pybuilddir.txt` file is now the sole indicator
-of running in a source tree.
diff --git a/Misc/NEWS.d/next/Security/2026-06-23-13-28-16.gh-issue-151981.xBHEcU.rst b/Misc/NEWS.d/next/Security/2026-06-23-13-28-16.gh-issue-151981.xBHEcU.rst
deleted file mode 100644
index 2123ab8e081b1d9..000000000000000
--- a/Misc/NEWS.d/next/Security/2026-06-23-13-28-16.gh-issue-151981.xBHEcU.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-In :mod:`tarfile`, seeking a stream now stops when end of the stream is
-reached.
diff --git a/Misc/NEWS.d/next/Security/2026-06-23-14-19-30.gh-issue-151987.8mNIMf.rst b/Misc/NEWS.d/next/Security/2026-06-23-14-19-30.gh-issue-151987.8mNIMf.rst
deleted file mode 100644
index 9eea7b32c4d2b4f..000000000000000
--- a/Misc/NEWS.d/next/Security/2026-06-23-14-19-30.gh-issue-151987.8mNIMf.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-The :meth:`tarfile.TarFile.extract` method now applies the given filter when
-it extracts a link target from the archive as a fallback.
diff --git a/Misc/NEWS.d/next/Security/2026-06-25-20-44-20.gh-issue-152216.VxiK5y.rst b/Misc/NEWS.d/next/Security/2026-06-25-20-44-20.gh-issue-152216.VxiK5y.rst
deleted file mode 100644
index 2769048e001d694..000000000000000
--- a/Misc/NEWS.d/next/Security/2026-06-25-20-44-20.gh-issue-152216.VxiK5y.rst
+++ /dev/null
@@ -1 +0,0 @@
-Update bundled `libexpat `_ to version 2.8.2.
diff --git a/Misc/NEWS.d/next/Security/2026-07-04-17-00-00.gh-issue-153030.RovkP6.rst b/Misc/NEWS.d/next/Security/2026-07-04-17-00-00.gh-issue-153030.RovkP6.rst
deleted file mode 100644
index d1d60593f4ba7d2..000000000000000
--- a/Misc/NEWS.d/next/Security/2026-07-04-17-00-00.gh-issue-153030.RovkP6.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Fixed quadratic complexity in incremental parsing of long unterminated
-constructs (such as tags or comments) in :class:`html.parser.HTMLParser`,
-which could be exploited for a denial of service.
diff --git a/Misc/NEWS.d/next/Security/2026-10-07-13-30-00.gh-issue-158907.k4Qm2p.rst b/Misc/NEWS.d/next/Security/2026-10-07-13-30-00.gh-issue-158907.k4Qm2p.rst
new file mode 100644
index 000000000000000..67bbd3da1cbbe8d
--- /dev/null
+++ b/Misc/NEWS.d/next/Security/2026-10-07-13-30-00.gh-issue-158907.k4Qm2p.rst
@@ -0,0 +1,5 @@
+:class:`~urllib.request.ProxyBasicAuthHandler` and
+:class:`~urllib.request.ProxyDigestAuthHandler` no longer send credentials
+in response to ``407`` from a direct origin. A scheme-less lookup against
+the origin host could match passwords stored for an HTTPS URL and retry
+the cleartext request with ``Proxy-Authorization``.
diff --git a/Misc/NEWS.d/next/Security/2026-11-09-17-19-29.gh-issue-161707.xWzwqQ.rst b/Misc/NEWS.d/next/Security/2026-11-09-17-19-29.gh-issue-161707.xWzwqQ.rst
new file mode 100644
index 000000000000000..63731daafff41ef
--- /dev/null
+++ b/Misc/NEWS.d/next/Security/2026-11-09-17-19-29.gh-issue-161707.xWzwqQ.rst
@@ -0,0 +1,5 @@
+.. cve: CVE-2026-16052
+
+:mod:`http.cookies` now raises :exc:`~http.cookies.CookieError` on any attempt
+to set a value string that contains the reserved separator character ``;`` to
+any attribute except :attr:`~http.cookies.Morsel.comment`.
diff --git a/Misc/NEWS.d/next/Security/2026-11-23-19-30-04.gh-issue-162493.QeSfGU.rst b/Misc/NEWS.d/next/Security/2026-11-23-19-30-04.gh-issue-162493.QeSfGU.rst
new file mode 100644
index 000000000000000..79314ee2650da67
--- /dev/null
+++ b/Misc/NEWS.d/next/Security/2026-11-23-19-30-04.gh-issue-162493.QeSfGU.rst
@@ -0,0 +1,3 @@
+Update bundled `libexpat `_ to version 2.11.0
+for the fixes to :cve:`2026-124317`, :cve:`2026-128241`, and
+:cve:`2026-134703`.
diff --git a/Misc/NEWS.d/next/Security/2026-11-24-11-39-37.gh-issue-162577.kgsLAF.rst b/Misc/NEWS.d/next/Security/2026-11-24-11-39-37.gh-issue-162577.kgsLAF.rst
new file mode 100644
index 000000000000000..ea55b58ddec910d
--- /dev/null
+++ b/Misc/NEWS.d/next/Security/2026-11-24-11-39-37.gh-issue-162577.kgsLAF.rst
@@ -0,0 +1,2 @@
+Update ``zstd`` to v1.6.0 in Android, iOS, and Windows builds to address
+:cve:`2026-124851`.
diff --git a/Misc/NEWS.d/next/Security/README.rst b/Misc/NEWS.d/next/Security/README.rst
index 9ea371df667a430..84c1a3a6ed7a07c 100644
--- a/Misc/NEWS.d/next/Security/README.rst
+++ b/Misc/NEWS.d/next/Security/README.rst
@@ -1,3 +1 @@
-Put news entry `blurb`_ files for the *Security* section in this directory.
-
-.. _blurb: https://pypi.org/project/blurb/
+Put news entry ``blurb`` files for the *Security* section in this directory.
diff --git a/Misc/NEWS.d/next/Tests/2023-09-03-12-53-53.gh-issue-108828.zoWIyX.rst b/Misc/NEWS.d/next/Tests/2023-09-03-12-53-53.gh-issue-108828.zoWIyX.rst
new file mode 100644
index 000000000000000..2b9fbdd48dd4505
--- /dev/null
+++ b/Misc/NEWS.d/next/Tests/2023-09-03-12-53-53.gh-issue-108828.zoWIyX.rst
@@ -0,0 +1,9 @@
+Add support of labels in tests. The ``@test.support.mark('label')``
+decorator adds a label to a test method or class.
+``test.support.mark_module('label')`` adds a label to the whole module.
+Many :mod:`test.support` decorators like :func:`~test.support.requires_resource`,
+:func:`~test.support.cpython_only` or :func:`~test.support.bigmemtest` add
+labels automatically. A label can have a value (``True`` by default). Tests
+which have or have not the specified label can be filtered by options
+``--label`` and ``--no-label``; ``--label name=value`` matches a specific
+value, while ``--label name`` matches any value.
diff --git a/Misc/NEWS.d/next/Tests/2026-04-24-01-38-56.gh-issue-148853._uM4_Q.rst b/Misc/NEWS.d/next/Tests/2026-04-24-01-38-56.gh-issue-148853._uM4_Q.rst
deleted file mode 100644
index 9d3fbc2590dc7a2..000000000000000
--- a/Misc/NEWS.d/next/Tests/2026-04-24-01-38-56.gh-issue-148853._uM4_Q.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix tests failing on FreeBSD in test.support's
-in_systemd_nspawn_sync_suppressed() due to unreadable /run directory.
diff --git a/Misc/NEWS.d/next/Tests/2026-05-13-14-53-23.gh-issue-149776.orqgsn.rst b/Misc/NEWS.d/next/Tests/2026-05-13-14-53-23.gh-issue-149776.orqgsn.rst
deleted file mode 100644
index e86a9130ff9bfb6..000000000000000
--- a/Misc/NEWS.d/next/Tests/2026-05-13-14-53-23.gh-issue-149776.orqgsn.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix test_socket on Linux kernel 7.1 and newer: skip UDP Lite tests if it's
-not supported. Patch by Victor Stinner.
diff --git a/Misc/NEWS.d/next/Tests/2026-05-22-16-41-45.gh-issue-150114.UdMikH.rst b/Misc/NEWS.d/next/Tests/2026-05-22-16-41-45.gh-issue-150114.UdMikH.rst
deleted file mode 100644
index a140bf921972ed9..000000000000000
--- a/Misc/NEWS.d/next/Tests/2026-05-22-16-41-45.gh-issue-150114.UdMikH.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-On Linux, regrtest now logs the total memory usage of all Python processes.
-Read the private memory in ``/proc/pid/smaps``. Patch by Victor Stinner.
diff --git a/Misc/NEWS.d/next/Tests/2026-05-25-15-39-53.gh-issue-150387.yzZ7jq.rst b/Misc/NEWS.d/next/Tests/2026-05-25-15-39-53.gh-issue-150387.yzZ7jq.rst
deleted file mode 100644
index 663a357a1792042..000000000000000
--- a/Misc/NEWS.d/next/Tests/2026-05-25-15-39-53.gh-issue-150387.yzZ7jq.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-Fix hang in
-``test.test_profiling.test_sampling_profiler.test_live_collector_ui.TestLiveModeErrors.test_run_failed_script_live``
-on slow buildbots. The test now always queues a final ``q`` keystroke so the
-live TUI loop exits even when the profiler collects enough samples to enter
-the post-finished input loop.
diff --git a/Misc/NEWS.d/next/Tests/2026-06-06-16-22-00.gh-issue-150966.7N9x5Q.rst b/Misc/NEWS.d/next/Tests/2026-06-06-16-22-00.gh-issue-150966.7N9x5Q.rst
deleted file mode 100644
index 3bbb471163d64e1..000000000000000
--- a/Misc/NEWS.d/next/Tests/2026-06-06-16-22-00.gh-issue-150966.7N9x5Q.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Avoid prematurely terminating failing live sampling profiler test targets,
-which made stderr assertions flaky on ASAN buildbots.
diff --git a/Misc/NEWS.d/next/Tests/2026-06-09-11-52-52.gh-issue-151130.1vslPH.rst b/Misc/NEWS.d/next/Tests/2026-06-09-11-52-52.gh-issue-151130.1vslPH.rst
deleted file mode 100644
index 0333e66446ce161..000000000000000
--- a/Misc/NEWS.d/next/Tests/2026-06-09-11-52-52.gh-issue-151130.1vslPH.rst
+++ /dev/null
@@ -1 +0,0 @@
-Add more tests for ``PyWeakref_*`` C API.
diff --git a/Misc/NEWS.d/next/Tests/2026-06-16-05-11-38.gh-issue-151096.Kq3Lp9.rst b/Misc/NEWS.d/next/Tests/2026-06-16-05-11-38.gh-issue-151096.Kq3Lp9.rst
deleted file mode 100644
index 3251c6fb094723b..000000000000000
--- a/Misc/NEWS.d/next/Tests/2026-06-16-05-11-38.gh-issue-151096.Kq3Lp9.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Fix ``test_embed`` failing when CPython is configured with a split exec prefix
-(``--exec-prefix`` differing from ``--prefix``).
diff --git a/Misc/NEWS.d/next/Tests/2026-06-22-19-45-00.gh-issue-151626.K9pZ2x.rst b/Misc/NEWS.d/next/Tests/2026-06-22-19-45-00.gh-issue-151626.K9pZ2x.rst
deleted file mode 100644
index 9858415018ae1ba..000000000000000
--- a/Misc/NEWS.d/next/Tests/2026-06-22-19-45-00.gh-issue-151626.K9pZ2x.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-Fix several tests in ``test.test_inspect``, ``test.test_import``,
-``test.test_importlib``, ``test.test_py_compile`` and
-``test.test_compileall`` that failed when the test suite was run with
-:envvar:`PYTHONPYCACHEPREFIX` set. These tests now neutralize the pycache
-prefix where they assume the default ``__pycache__`` bytecode layout.
diff --git a/Misc/NEWS.d/next/Tests/2026-09-16-14-37-28.gh-issue-126253.9FOKPp.rst b/Misc/NEWS.d/next/Tests/2026-09-16-14-37-28.gh-issue-126253.9FOKPp.rst
new file mode 100644
index 000000000000000..370d822f883aa9a
--- /dev/null
+++ b/Misc/NEWS.d/next/Tests/2026-09-16-14-37-28.gh-issue-126253.9FOKPp.rst
@@ -0,0 +1 @@
+Fix ``test_os.test_attributes()`` on Windows NTFS: ignore unknown file attributes.
diff --git a/Misc/NEWS.d/next/Tests/2026-11-10-14-49-01.gh-issue-161739.NZTbYC.rst b/Misc/NEWS.d/next/Tests/2026-11-10-14-49-01.gh-issue-161739.NZTbYC.rst
new file mode 100644
index 000000000000000..a480b9788f7574e
--- /dev/null
+++ b/Misc/NEWS.d/next/Tests/2026-11-10-14-49-01.gh-issue-161739.NZTbYC.rst
@@ -0,0 +1,2 @@
+``test_hashlibtest_pbkdf2_hmac_c`` from ``test_haslib`` no longer fails with
+``ValueError: [Provider routines] invalid salt length`` with FIPS enabled.
diff --git a/Misc/NEWS.d/next/Tests/2026-11-15-09-43-15.gh-issue-162034.egx5QV.rst b/Misc/NEWS.d/next/Tests/2026-11-15-09-43-15.gh-issue-162034.egx5QV.rst
new file mode 100644
index 000000000000000..1b7d2c4ad5f27c6
--- /dev/null
+++ b/Misc/NEWS.d/next/Tests/2026-11-15-09-43-15.gh-issue-162034.egx5QV.rst
@@ -0,0 +1,2 @@
+The Apple testbed projects now build when the path of the project contains a
+space.
diff --git a/Misc/NEWS.d/next/Tests/2026-11-17-00-39-51.gh-issue-162034.FmiuNi.rst b/Misc/NEWS.d/next/Tests/2026-11-17-00-39-51.gh-issue-162034.FmiuNi.rst
new file mode 100644
index 000000000000000..1764fa2a458e599
--- /dev/null
+++ b/Misc/NEWS.d/next/Tests/2026-11-17-00-39-51.gh-issue-162034.FmiuNi.rst
@@ -0,0 +1,2 @@
+Fix the Apple testbed's extension module processing for an XCframework or
+package path with a space, or a build path with brackets or a backslash.
diff --git a/Misc/NEWS.d/next/Tests/2026-11-17-15-57-41.gh-issue-162144.pL5k29.rst b/Misc/NEWS.d/next/Tests/2026-11-17-15-57-41.gh-issue-162144.pL5k29.rst
new file mode 100644
index 000000000000000..bbd4a9cf54752e0
--- /dev/null
+++ b/Misc/NEWS.d/next/Tests/2026-11-17-15-57-41.gh-issue-162144.pL5k29.rst
@@ -0,0 +1,3 @@
+Skip ``@support.nomemtest`` tests when using a thread sanitizer (TSan).
+``set_nomemory()`` and ``call_with_nomemory()`` functions of the
+:mod:`!_testcapi` extension are not thread safe. Patch by Victor Stinner.
diff --git a/Misc/NEWS.d/next/Tests/README.rst b/Misc/NEWS.d/next/Tests/README.rst
index 8ea9b4ceb277bf5..d2e50e43d847905 100644
--- a/Misc/NEWS.d/next/Tests/README.rst
+++ b/Misc/NEWS.d/next/Tests/README.rst
@@ -1,3 +1 @@
-Put news entry `blurb`_ files for the *Tests* section in this directory.
-
-.. _blurb: https://pypi.org/project/blurb/
+Put news entry ``blurb`` files for the *Tests* section in this directory.
diff --git a/Misc/NEWS.d/next/Tools-Demos/2024-06-17-13-52-04.gh-issue-111501.syFLAV.rst b/Misc/NEWS.d/next/Tools-Demos/2024-06-17-13-52-04.gh-issue-111501.syFLAV.rst
deleted file mode 100644
index 2989d4b81b1dd39..000000000000000
--- a/Misc/NEWS.d/next/Tools-Demos/2024-06-17-13-52-04.gh-issue-111501.syFLAV.rst
+++ /dev/null
@@ -1 +0,0 @@
-PS1 is no longer exported by venv activate script
diff --git a/Misc/NEWS.d/next/Tools-Demos/2026-05-22-18-51-09.gh-issue-150258.dh8GVK.rst b/Misc/NEWS.d/next/Tools-Demos/2026-05-22-18-51-09.gh-issue-150258.dh8GVK.rst
deleted file mode 100644
index 02cad6c4f53d928..000000000000000
--- a/Misc/NEWS.d/next/Tools-Demos/2026-05-22-18-51-09.gh-issue-150258.dh8GVK.rst
+++ /dev/null
@@ -1 +0,0 @@
-Update the tooltip on the Tachyon flame graph to show both absolute and relative percentages.
diff --git a/Misc/NEWS.d/next/Tools-Demos/2026-07-10-14-38-31.gh-issue-152384.uaPADM.rst b/Misc/NEWS.d/next/Tools-Demos/2026-07-10-14-38-31.gh-issue-152384.uaPADM.rst
deleted file mode 100644
index 08b94d5486f64d8..000000000000000
--- a/Misc/NEWS.d/next/Tools-Demos/2026-07-10-14-38-31.gh-issue-152384.uaPADM.rst
+++ /dev/null
@@ -1,8 +0,0 @@
-The CPython Pixi packages are now all accessible at the same
-``Tools/pixi-packages`` subdirectory, rather than at
-``Tools/pixi-packages/{variant}`` as before. Variants are now selected not
-via subdirectory but via ``flags``; see
-https://pixi.prefix.dev/latest/concepts/package_specifications/#extras-and-flags
-for usage instructions. The ``tsan-freethreading`` variant has been renamed
-to ``tsan_freethreading``, while the ``default``, ``asan``, and
-``freethreading`` variants retain their previous names.
diff --git a/Misc/NEWS.d/next/Tools-Demos/README.rst b/Misc/NEWS.d/next/Tools-Demos/README.rst
index 9f03d79b208653a..357f82862cb51a8 100644
--- a/Misc/NEWS.d/next/Tools-Demos/README.rst
+++ b/Misc/NEWS.d/next/Tools-Demos/README.rst
@@ -1,3 +1 @@
-Put news entry `blurb`_ files for the *Tools/Demos* section in this directory.
-
-.. _blurb: https://pypi.org/project/blurb/
+Put news entry ``blurb`` files for the *Tools/Demos* section in this directory.
diff --git a/Misc/NEWS.d/next/Unsupported_platforms/README.rst b/Misc/NEWS.d/next/Unsupported_platforms/README.rst
new file mode 100644
index 000000000000000..348b80cb4c7f111
--- /dev/null
+++ b/Misc/NEWS.d/next/Unsupported_platforms/README.rst
@@ -0,0 +1 @@
+Put news entry ``blurb`` files for the *Unsupported platforms* section in this directory.
diff --git a/Misc/NEWS.d/next/WASI/README.rst b/Misc/NEWS.d/next/WASI/README.rst
new file mode 100644
index 000000000000000..ee55e287aed51e6
--- /dev/null
+++ b/Misc/NEWS.d/next/WASI/README.rst
@@ -0,0 +1 @@
+Put news entry ``blurb`` files for the *WASI* section in this directory.
diff --git a/Misc/NEWS.d/next/Windows/2026-04-21-16-07-11.gh-issue-140146.TAcUHA.rst b/Misc/NEWS.d/next/Windows/2026-04-21-16-07-11.gh-issue-140146.TAcUHA.rst
deleted file mode 100644
index 2d3e42c86fd521f..000000000000000
--- a/Misc/NEWS.d/next/Windows/2026-04-21-16-07-11.gh-issue-140146.TAcUHA.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-Prevent :mod:`tkinter` from hanging on Windows if stdin is redirected to a pipe in an
-interactive session. This is helpful for testing interactive usage of
-tkinter from a script, for example as part of the cpython test suite.
diff --git a/Misc/NEWS.d/next/Windows/2026-04-29-14-44-51.gh-issue-138489.234aj6.rst b/Misc/NEWS.d/next/Windows/2026-04-29-14-44-51.gh-issue-138489.234aj6.rst
deleted file mode 100644
index 4afb8f737b692e8..000000000000000
--- a/Misc/NEWS.d/next/Windows/2026-04-29-14-44-51.gh-issue-138489.234aj6.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Windows distributions now include a :file:`build-details.json` file (see
-:pep:`739`). The legacy installer does not install it, but all other
-distributions from python.org and all preset configurations in the
-``PC\layout`` script will include one.
diff --git a/Misc/NEWS.d/next/Windows/2026-05-06-21-36-53.gh-issue-124111.m4OBX8.rst b/Misc/NEWS.d/next/Windows/2026-05-06-21-36-53.gh-issue-124111.m4OBX8.rst
deleted file mode 100644
index 9a57536f1dc96b6..000000000000000
--- a/Misc/NEWS.d/next/Windows/2026-05-06-21-36-53.gh-issue-124111.m4OBX8.rst
+++ /dev/null
@@ -1 +0,0 @@
-Updated Windows builds to use Tcl/Tk 9.0.3.
diff --git a/Misc/NEWS.d/next/Windows/2026-05-14-22-09-46.gh-issue-149786.UI-HZM.rst b/Misc/NEWS.d/next/Windows/2026-05-14-22-09-46.gh-issue-149786.UI-HZM.rst
deleted file mode 100644
index 64ca91a01f41afc..000000000000000
--- a/Misc/NEWS.d/next/Windows/2026-05-14-22-09-46.gh-issue-149786.UI-HZM.rst
+++ /dev/null
@@ -1 +0,0 @@
-Fixes virtual environment launchers on Windows free-threaded builds.
diff --git a/Misc/NEWS.d/next/Windows/2026-06-04-18-53-18.gh-issue-150836.Wci7bZ.rst b/Misc/NEWS.d/next/Windows/2026-06-04-18-53-18.gh-issue-150836.Wci7bZ.rst
deleted file mode 100644
index 6497b7927db7da3..000000000000000
--- a/Misc/NEWS.d/next/Windows/2026-06-04-18-53-18.gh-issue-150836.Wci7bZ.rst
+++ /dev/null
@@ -1 +0,0 @@
-Make installed tkinter work with Tcl/Tk 9 builds that embed the Tk script library in the Tk DLL on Windows.
diff --git a/Misc/NEWS.d/next/Windows/2026-06-09-11-40-48.gh-issue-151159.JKVfme.rst b/Misc/NEWS.d/next/Windows/2026-06-09-11-40-48.gh-issue-151159.JKVfme.rst
deleted file mode 100644
index ad1be115db5ce8f..000000000000000
--- a/Misc/NEWS.d/next/Windows/2026-06-09-11-40-48.gh-issue-151159.JKVfme.rst
+++ /dev/null
@@ -1 +0,0 @@
-Updated bundled version of OpenSSL to 3.5.7.
diff --git a/Misc/NEWS.d/next/Windows/2026-06-09-11-55-41.gh-issue-151163.oizZYV.rst b/Misc/NEWS.d/next/Windows/2026-06-09-11-55-41.gh-issue-151163.oizZYV.rst
deleted file mode 100644
index 580a87400862c52..000000000000000
--- a/Misc/NEWS.d/next/Windows/2026-06-09-11-55-41.gh-issue-151163.oizZYV.rst
+++ /dev/null
@@ -1 +0,0 @@
-Updated Windows builds to include SQLite version 3.53.2.
diff --git a/Misc/NEWS.d/next/Windows/2026-06-28-13-03-57.gh-issue-152433.jUXFwC.rst b/Misc/NEWS.d/next/Windows/2026-06-28-13-03-57.gh-issue-152433.jUXFwC.rst
deleted file mode 100644
index 348bfa4ee9c278c..000000000000000
--- a/Misc/NEWS.d/next/Windows/2026-06-28-13-03-57.gh-issue-152433.jUXFwC.rst
+++ /dev/null
@@ -1 +0,0 @@
-Use the Windows API ``GetFileSizeEx()`` for memory mapped files, rather than the older ``GetFileSize()``.
diff --git a/Misc/NEWS.d/next/Windows/2026-06-29-16-29-50.gh-issue-152433._nhCjt.rst b/Misc/NEWS.d/next/Windows/2026-06-29-16-29-50.gh-issue-152433._nhCjt.rst
deleted file mode 100644
index 0c420c124c2981f..000000000000000
--- a/Misc/NEWS.d/next/Windows/2026-06-29-16-29-50.gh-issue-152433._nhCjt.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Restores the ``mmap`` module when CPython is built from source for specific
-Windows API sets.
diff --git a/Misc/NEWS.d/next/Windows/2026-07-01-16-38-24.gh-issue-152433.jvEiHh.rst b/Misc/NEWS.d/next/Windows/2026-07-01-16-38-24.gh-issue-152433.jvEiHh.rst
deleted file mode 100644
index d5aead5fbe0b9e2..000000000000000
--- a/Misc/NEWS.d/next/Windows/2026-07-01-16-38-24.gh-issue-152433.jvEiHh.rst
+++ /dev/null
@@ -1 +0,0 @@
-:mod:`ssl`: improve UWP build compatibility.
diff --git a/Misc/NEWS.d/next/Windows/2026-07-29-13-05-00.gh-issue-140774.wA3ttr.rst b/Misc/NEWS.d/next/Windows/2026-07-29-13-05-00.gh-issue-140774.wA3ttr.rst
new file mode 100644
index 000000000000000..aaf120efb992e79
--- /dev/null
+++ b/Misc/NEWS.d/next/Windows/2026-07-29-13-05-00.gh-issue-140774.wA3ttr.rst
@@ -0,0 +1,3 @@
+Fix :func:`os.chmod` with ``follow_symlinks=True``, :func:`os.fchmod` and
+:meth:`pathlib.Path.chmod` on Windows: clearing the read-only attribute of a
+file which has no other attribute set is no longer silently ignored.
diff --git a/Misc/NEWS.d/next/Windows/2026-09-30-00-00-00.gh-issue-157917.48oa0L.rst b/Misc/NEWS.d/next/Windows/2026-09-30-00-00-00.gh-issue-157917.48oa0L.rst
new file mode 100644
index 000000000000000..2d5e6a14a31d53f
--- /dev/null
+++ b/Misc/NEWS.d/next/Windows/2026-09-30-00-00-00.gh-issue-157917.48oa0L.rst
@@ -0,0 +1,9 @@
+Fix :attr:`sys.prefix`, :attr:`sys.exec_prefix` and :attr:`sys.executable`
+retaining the ``\\?\`` extended-length path prefix in a virtual environment
+when the interpreter is invoked through such a path on Windows. The venv
+launcher reports its own path through ``GetModuleFileNameW``, which preserves
+the prefix, and that value was used verbatim. Windows does not resolve
+relative path components in extended-length paths, so the leaked prefix made
+tools that join ``..`` components onto :mod:`sysconfig` paths fail with
+``OSError: [Errno 22]``. The prefix is now stripped again, except for paths
+that are still too long to be used without it.
diff --git a/Misc/NEWS.d/next/Windows/2026-09-30-01-12-58.gh-issue-158414.738yJa.rst b/Misc/NEWS.d/next/Windows/2026-09-30-01-12-58.gh-issue-158414.738yJa.rst
new file mode 100644
index 000000000000000..dba12665deddd93
--- /dev/null
+++ b/Misc/NEWS.d/next/Windows/2026-09-30-01-12-58.gh-issue-158414.738yJa.rst
@@ -0,0 +1 @@
+Fix a hang when writing an incomplete UTF-8 sequence to the Windows console.
diff --git a/Misc/NEWS.d/next/Windows/2026-11-11-10-44-20.gh-issue-161735.MZLRnD.rst b/Misc/NEWS.d/next/Windows/2026-11-11-10-44-20.gh-issue-161735.MZLRnD.rst
new file mode 100644
index 000000000000000..a824533a8caa9d6
--- /dev/null
+++ b/Misc/NEWS.d/next/Windows/2026-11-11-10-44-20.gh-issue-161735.MZLRnD.rst
@@ -0,0 +1 @@
+Updated bundled version of ``zlib-ng`` to v2.2.5.
diff --git a/Misc/NEWS.d/next/Windows/README.rst b/Misc/NEWS.d/next/Windows/README.rst
index 7dbc5805e3f99fa..1e65de35f0ad97b 100644
--- a/Misc/NEWS.d/next/Windows/README.rst
+++ b/Misc/NEWS.d/next/Windows/README.rst
@@ -1,3 +1 @@
-Put news entry `blurb`_ files for the *Windows* section in this directory.
-
-.. _blurb: https://pypi.org/project/blurb/
+Put news entry ``blurb`` files for the *Windows* section in this directory.
diff --git a/Misc/NEWS.d/next/iOS/README.rst b/Misc/NEWS.d/next/iOS/README.rst
new file mode 100644
index 000000000000000..c91d954958d32b0
--- /dev/null
+++ b/Misc/NEWS.d/next/iOS/README.rst
@@ -0,0 +1 @@
+Put news entry ``blurb`` files for the *iOS* section in this directory.
diff --git a/Misc/NEWS.d/next/macOS/2026-05-31-10-40-00.gh-issue-150644.zLWyjj.rst b/Misc/NEWS.d/next/macOS/2026-05-31-10-40-00.gh-issue-150644.zLWyjj.rst
deleted file mode 100644
index 7452a7c765c0a86..000000000000000
--- a/Misc/NEWS.d/next/macOS/2026-05-31-10-40-00.gh-issue-150644.zLWyjj.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-When system logging is enabled (with ``config.use_system_logger``, messages
-are now tagged as public. This allows the macOS 26 system logger to view
-messages without special configuration.
diff --git a/Misc/NEWS.d/next/macOS/2026-06-09-11-52-35.gh-issue-151163.RlPXHq.rst b/Misc/NEWS.d/next/macOS/2026-06-09-11-52-35.gh-issue-151163.RlPXHq.rst
deleted file mode 100644
index 7e9bf6f4587974e..000000000000000
--- a/Misc/NEWS.d/next/macOS/2026-06-09-11-52-35.gh-issue-151163.RlPXHq.rst
+++ /dev/null
@@ -1 +0,0 @@
-Updated macOS installer to include SQLite version 3.53.2.
diff --git a/Misc/NEWS.d/next/macOS/2026-07-17-23-20-27.gh-issue-152023.QAAgdj.rst b/Misc/NEWS.d/next/macOS/2026-07-17-23-20-27.gh-issue-152023.QAAgdj.rst
deleted file mode 100644
index afabb3d52249708..000000000000000
--- a/Misc/NEWS.d/next/macOS/2026-07-17-23-20-27.gh-issue-152023.QAAgdj.rst
+++ /dev/null
@@ -1,2 +0,0 @@
-Update macOS installer builds to SQLite 3.53.3. Enable median() and
-percentile() functions.
diff --git a/Misc/NEWS.d/next/macOS/2026-07-17-23-35-36.gh-issue-124111.dmM4lk.rst b/Misc/NEWS.d/next/macOS/2026-07-17-23-35-36.gh-issue-124111.dmM4lk.rst
deleted file mode 100644
index 48ab66407831a86..000000000000000
--- a/Misc/NEWS.d/next/macOS/2026-07-17-23-35-36.gh-issue-124111.dmM4lk.rst
+++ /dev/null
@@ -1 +0,0 @@
-Update macOS installer to use Tcl/Tk 9.0.4.
diff --git a/Misc/NEWS.d/next/macOS/README.rst b/Misc/NEWS.d/next/macOS/README.rst
index 563766928cf9441..a3adb59b62631e8 100644
--- a/Misc/NEWS.d/next/macOS/README.rst
+++ b/Misc/NEWS.d/next/macOS/README.rst
@@ -1,3 +1 @@
-Put news entry `blurb`_ files for the *macOS* section in this directory.
-
-.. _blurb: https://pypi.org/project/blurb/
+Put news entry ``blurb`` files for the *macOS* section in this directory.
diff --git a/Misc/externals.spdx.json b/Misc/externals.spdx.json
index 523d20259adaaa9..b35ed3720943aba 100644
--- a/Misc/externals.spdx.json
+++ b/Misc/externals.spdx.json
@@ -70,84 +70,84 @@
"checksums": [
{
"algorithm": "SHA256",
- "checksumValue": "ca94e7c6c223d9caf77bb51aac5949186379608ea2a0cad3aa8bdf31856912e9"
+ "checksumValue": "d6cf0d9a651f25fe506f6b3dc133a80b9b79a0bc565f570dcf8fdbd597551485"
}
],
- "downloadLocation": "https://github.com/python/cpython-source-deps/archive/refs/tags/openssl-3.5.7.tar.gz",
+ "downloadLocation": "https://github.com/python/cpython-source-deps/archive/refs/tags/openssl-3.5.9.tar.gz",
"externalRefs": [
{
"referenceCategory": "SECURITY",
- "referenceLocator": "cpe:2.3:a:openssl:openssl:3.5.7:*:*:*:*:*:*:*",
+ "referenceLocator": "cpe:2.3:a:openssl:openssl:3.5.9:*:*:*:*:*:*:*",
"referenceType": "cpe23Type"
}
],
"licenseConcluded": "NOASSERTION",
"name": "openssl",
"primaryPackagePurpose": "SOURCE",
- "versionInfo": "3.5.7"
+ "versionInfo": "3.5.9"
},
{
"SPDXID": "SPDXRef-PACKAGE-sqlite",
"checksums": [
{
"algorithm": "SHA256",
- "checksumValue": "53f8711811090cc4d9ffc624c360f81e7b409763b145ab2e948998f1a0d6a612"
+ "checksumValue": "acc27a72ca7745781bb902269370303e778736a090585cc13acd2ea9ab785666"
}
],
- "downloadLocation": "https://github.com/python/cpython-source-deps/archive/refs/tags/sqlite-3.53.2.0.tar.gz",
+ "downloadLocation": "https://github.com/python/cpython-source-deps/archive/refs/tags/sqlite-3.53.4.0.tar.gz",
"externalRefs": [
{
"referenceCategory": "SECURITY",
- "referenceLocator": "cpe:2.3:a:sqlite:sqlite:3.53.2.0:*:*:*:*:*:*:*",
+ "referenceLocator": "cpe:2.3:a:sqlite:sqlite:3.53.4.0:*:*:*:*:*:*:*",
"referenceType": "cpe23Type"
}
],
"licenseConcluded": "NOASSERTION",
"name": "sqlite",
"primaryPackagePurpose": "SOURCE",
- "versionInfo": "3.53.2.0"
+ "versionInfo": "3.53.4.0"
},
{
"SPDXID": "SPDXRef-PACKAGE-tcl",
"checksums": [
{
"algorithm": "SHA256",
- "checksumValue": "7a1d1f3a2b8f4484a9c2a027a157963c18f85a81785e85fcb5d1e3df6b6a4fd4"
+ "checksumValue": "3ac2acd65ddaaac0b2b8df321b558419d21da20bf67ab39149b8248c85f0d214"
}
],
- "downloadLocation": "https://github.com/python/cpython-source-deps/archive/refs/tags/tcl-9.0.3.0.tar.gz",
+ "downloadLocation": "https://github.com/python/cpython-source-deps/archive/refs/tags/tcl-9.0.4.0.tar.gz",
"externalRefs": [
{
"referenceCategory": "SECURITY",
- "referenceLocator": "cpe:2.3:a:tcl_tk:tcl_tk:9.0.3.0:*:*:*:*:*:*:*",
+ "referenceLocator": "cpe:2.3:a:tcl_tk:tcl_tk:9.0.4.0:*:*:*:*:*:*:*",
"referenceType": "cpe23Type"
}
],
"licenseConcluded": "NOASSERTION",
"name": "tcl",
"primaryPackagePurpose": "SOURCE",
- "versionInfo": "9.0.3.0"
+ "versionInfo": "9.0.4.0"
},
{
"SPDXID": "SPDXRef-PACKAGE-tk",
"checksums": [
{
"algorithm": "SHA256",
- "checksumValue": "54fb59df12c489c6264f5b7d3d7444b150d1e3d6561fd59cdb11483440cec000"
+ "checksumValue": "66048966cfa88989333ff1632f454e10e9248516bb45efda7b4d2ae5a61642cb"
}
],
- "downloadLocation": "https://github.com/python/cpython-source-deps/archive/refs/tags/tk-9.0.3.1.tar.gz",
+ "downloadLocation": "https://github.com/python/cpython-source-deps/archive/refs/tags/tk-9.0.4.1.tar.gz",
"externalRefs": [
{
"referenceCategory": "SECURITY",
- "referenceLocator": "cpe:2.3:a:tcl_tk:tcl_tk:9.0.3.1:*:*:*:*:*:*:*",
+ "referenceLocator": "cpe:2.3:a:tcl_tk:tcl_tk:9.0.4.1:*:*:*:*:*:*:*",
"referenceType": "cpe23Type"
}
],
"licenseConcluded": "NOASSERTION",
"name": "tk",
"primaryPackagePurpose": "SOURCE",
- "versionInfo": "9.0.3.1"
+ "versionInfo": "9.0.4.1"
},
{
"SPDXID": "SPDXRef-PACKAGE-xz",
@@ -175,42 +175,42 @@
"checksums": [
{
"algorithm": "SHA256",
- "checksumValue": "00bbd88709bc416cb96160ab61d3e1c8f76e106799af7328d0fe434dc7dd5004"
+ "checksumValue": "a9734c94080792af0b50d9c51c2cc8845c2f8ecfa4db87f6462a9b260af67f96"
}
],
- "downloadLocation": "https://github.com/python/cpython-source-deps/archive/refs/tags/zlib-ng-2.2.4.tar.gz",
+ "downloadLocation": "https://github.com/python/cpython-source-deps/archive/refs/tags/zlib-ng-2.2.5.tar.gz",
"externalRefs": [
{
"referenceCategory": "SECURITY",
- "referenceLocator": "cpe:2.3:a:zlib-ng:zlib-ng:2.2.4:*:*:*:*:*:*:*",
+ "referenceLocator": "cpe:2.3:a:zlib-ng:zlib-ng:2.2.5:*:*:*:*:*:*:*",
"referenceType": "cpe23Type"
}
],
"licenseConcluded": "NOASSERTION",
"name": "zlib-ng",
"primaryPackagePurpose": "SOURCE",
- "versionInfo": "2.2.4"
+ "versionInfo": "2.2.5"
},
{
"SPDXID": "SPDXRef-PACKAGE-zstd",
"checksums": [
{
"algorithm": "SHA256",
- "checksumValue": "f24b52470d12f466e9fa4fcc94e6c530625ada51d7b36de7fdc6ed7e6f499c8e"
+ "checksumValue": "eb34eed79af88b8dd7c07481d55192520b9545f865416c31c828b96b01d335d3"
}
],
- "downloadLocation": "https://github.com/python/cpython-source-deps/archive/refs/tags/zstd-1.5.7.tar.gz",
+ "downloadLocation": "https://github.com/python/cpython-source-deps/archive/refs/tags/zstd-1.6.0.tar.gz",
"externalRefs": [
{
"referenceCategory": "SECURITY",
- "referenceLocator": "cpe:2.3:a:facebook:zstandard:1.5.7:*:*:*:*:*:*:*",
+ "referenceLocator": "cpe:2.3:a:facebook:zstandard:1.6.0:*:*:*:*:*:*:*",
"referenceType": "cpe23Type"
}
],
"licenseConcluded": "NOASSERTION",
"name": "zstd",
"primaryPackagePurpose": "SOURCE",
- "versionInfo": "1.5.7"
+ "versionInfo": "1.6.0"
}
],
"spdxVersion": "SPDX-2.3"
diff --git a/Misc/platform_triplet.c b/Misc/platform_triplet.c
index f5cd73bdea83335..6c1863c943b3539 100644
--- a/Misc/platform_triplet.c
+++ b/Misc/platform_triplet.c
@@ -257,6 +257,32 @@ PLATFORM_TRIPLET=arm64-iphonesimulator
# else
PLATFORM_TRIPLET=arm64-iphoneos
# endif
+# elif defined(TARGET_OS_TV) && TARGET_OS_TV
+# if defined(TARGET_OS_SIMULATOR) && TARGET_OS_SIMULATOR
+# if __x86_64__
+PLATFORM_TRIPLET=x86_64-appletvsimulator
+# else
+PLATFORM_TRIPLET=arm64-appletvsimulator
+# endif
+# else
+PLATFORM_TRIPLET=arm64-appletvos
+# endif
+# elif defined(TARGET_OS_WATCH) && TARGET_OS_WATCH
+# if defined(TARGET_OS_SIMULATOR) && TARGET_OS_SIMULATOR
+# if __x86_64__
+PLATFORM_TRIPLET=x86_64-watchsimulator
+# else
+PLATFORM_TRIPLET=arm64-watchsimulator
+# endif
+# else
+PLATFORM_TRIPLET=arm64_32-watchos
+# endif
+# elif defined(TARGET_OS_VISION) && TARGET_OS_VISION
+# if defined(TARGET_OS_SIMULATOR) && TARGET_OS_SIMULATOR
+PLATFORM_TRIPLET=arm64-xrsimulator
+# else
+PLATFORM_TRIPLET=arm64-xros
+# endif
// Older macOS SDKs do not define TARGET_OS_OSX
# elif !defined(TARGET_OS_OSX) || TARGET_OS_OSX
PLATFORM_TRIPLET=darwin
diff --git a/Misc/python-config.sh.in b/Misc/python-config.sh.in
index 555b0cb6ba2a482..39b0031b58b916b 100644
--- a/Misc/python-config.sh.in
+++ b/Misc/python-config.sh.in
@@ -7,9 +7,9 @@ exit_with_usage ()
local usage
usage="Usage: $0 --prefix|--exec-prefix|--includes|--libs|--cflags|--ldflags|--extension-suffix|--help|--abiflags|--configdir|--embed"
if [ "$1" -eq 0 ]; then
- echo "$usage"
+ printf '%s\n' "$usage"
else
- echo "$usage" >&2
+ printf '%s\n' "$usage" >&2
fi
exit $1
}
@@ -19,29 +19,46 @@ if [ "$1" = "" ] ; then
fi
# Returns the actual prefix where this script was installed to.
+# Fails if the directory containing this script cannot be resolved.
installed_prefix ()
{
- RESULT=$(dirname $(cd $(dirname "$1") && pwd -P))
+ RESULT=$(cd "$(dirname "$1")" && pwd -P) || return 1
+ RESULT=$(dirname "$RESULT")
if which readlink >/dev/null 2>&1 ; then
if readlink -f "$RESULT" >/dev/null 2>&1; then
RESULT=$(readlink -f "$RESULT")
fi
fi
- echo $RESULT
+ printf '%s\n' "$RESULT"
}
-prefix_real=$(installed_prefix "$0")
+prefix_real=$(installed_prefix "$0") || {
+ printf '%s\n' "$0: cannot determine the installation prefix" >&2
+ exit 1
+}
-# Use sed to fix paths from their built-to locations to their installed-to
-# locations. Keep prefix & exec_prefix using their original values in case
+# Fix paths from their built-to locations to their installed-to locations
+# by replacing the first occurrence of the configured prefix with the actual
+# one. Keep prefix & exec_prefix using their original values in case
# they are referenced in other configure variables, to prevent double
# substitution, issue #22140.
prefix="@prefix@"
exec_prefix="@exec_prefix@"
exec_prefix_real=${prefix_real}
-includedir=$(echo "@includedir@" | sed "s#$prefix#$prefix_real#")
-libdir=$(echo "@libdir@" | sed "s#$prefix#$prefix_real#")
-CFLAGS=$(echo "@CFLAGS@" | sed "s#$prefix#$prefix_real#")
+relocate ()
+{
+ case "$1" in
+ *"$prefix"*)
+ printf '%s\n' "${1%%"$prefix"*}${prefix_real}${1#*"$prefix"}"
+ ;;
+ *)
+ printf '%s\n' "$1"
+ ;;
+ esac
+}
+includedir=$(relocate "@includedir@")
+libdir=$(relocate "@libdir@")
+CFLAGS=$(relocate "@CFLAGS@")
VERSION="@VERSION@"
LIBM="@LIBM@"
LIBC="@LIBC@"
@@ -55,7 +72,7 @@ OPT="@OPT@"
PY_ENABLE_SHARED="@PY_ENABLE_SHARED@"
LDVERSION="@LDVERSION@"
LIBDEST=${prefix_real}/lib/python${VERSION}
-LIBPL=$(echo "@LIBPL@" | sed "s#$prefix#$prefix_real#")
+LIBPL=$(relocate "@LIBPL@")
SO="@EXT_SUFFIX@"
PYTHONFRAMEWORK="@PYTHONFRAMEWORK@"
INCDIR="-I$includedir/python${VERSION}${ABIFLAGS}"
@@ -63,9 +80,9 @@ PLATINCDIR="-I$includedir/python${VERSION}${ABIFLAGS}"
PY_EMBED=0
# Scan for --help or unknown argument.
-for ARG in $*
+for ARG in "$@"
do
- case $ARG in
+ case "$ARG" in
--help)
exit_with_usage 0
;;
@@ -88,35 +105,35 @@ for ARG in "$@"
do
case "$ARG" in
--prefix)
- echo "$prefix_real"
+ printf '%s\n' "$prefix_real"
;;
--exec-prefix)
- echo "$exec_prefix_real"
+ printf '%s\n' "$exec_prefix_real"
;;
--includes)
- echo "$INCDIR $PLATINCDIR"
+ printf '%s\n' "$INCDIR $PLATINCDIR"
;;
--cflags)
- echo "$INCDIR $PLATINCDIR $BASECFLAGS $CFLAGS $OPT"
+ printf '%s\n' "$INCDIR $PLATINCDIR $BASECFLAGS $CFLAGS $OPT"
;;
--libs)
- echo "$LIBS"
+ printf '%s\n' "$LIBS"
;;
--ldflags)
LIBPLUSED=
if [ "$PY_ENABLE_SHARED" = "0" ] ; then
LIBPLUSED="-L$LIBPL"
fi
- echo "$LIBPLUSED -L$libdir $LIBS"
+ printf '%s\n' "$LIBPLUSED -L$libdir $LIBS"
;;
--extension-suffix)
- echo "$SO"
+ printf '%s\n' "$SO"
;;
--abiflags)
- echo "$ABIFLAGS"
+ printf '%s\n' "$ABIFLAGS"
;;
--configdir)
- echo "$LIBPL"
+ printf '%s\n' "$LIBPL"
;;
esac
done
diff --git a/Misc/python.man b/Misc/python.man
index 5e4f3c3debe9358..238d32099710173 100644
--- a/Misc/python.man
+++ b/Misc/python.man
@@ -299,7 +299,7 @@ the remaining fields.
The
.I message
-field must match the whole printed warning message; this match is
+field must match the start of the warning message; this match is
case-insensitive.
The
diff --git a/Misc/sbom.spdx.json b/Misc/sbom.spdx.json
index fbc7ca631d70e29..225f2a5d1863895 100644
--- a/Misc/sbom.spdx.json
+++ b/Misc/sbom.spdx.json
@@ -20,11 +20,11 @@
"checksums": [
{
"algorithm": "SHA1",
- "checksumValue": "b0235fa3cf845a7d68e8e66dd344d5e32e8951b5"
+ "checksumValue": "28cdbd89d1956e24045d83e5f50b4adeca1b8c0c"
},
{
"algorithm": "SHA256",
- "checksumValue": "42f8b392c70366743eacbc60ce021389ccaa333598dd49eef6ee5c93698ca205"
+ "checksumValue": "73dd48d5f41e789d5616e8998e5118ea0f25bde65b87a8f04e3e74d4dd51b1a4"
}
],
"fileName": "Modules/expat/ascii.h"
@@ -34,25 +34,39 @@
"checksums": [
{
"algorithm": "SHA1",
- "checksumValue": "cbb53d16ca1f35ee9c9e296116efd222ae611ed9"
+ "checksumValue": "f0c9b25759ccf57fd65eb4356c2762f25c0e9a6f"
},
{
"algorithm": "SHA256",
- "checksumValue": "1cc0ae749019fc0e488cd1cf245f6beaa6d4f7c55a1fc797e5aa40a408bc266b"
+ "checksumValue": "5792cb56f285c8876b988d875a70d49019bc7e6d5ebcd0f8224b24e695301832"
}
],
"fileName": "Modules/expat/asciitab.h"
},
+ {
+ "SPDXID": "SPDXRef-FILE-Modules-expat-entities.h",
+ "checksums": [
+ {
+ "algorithm": "SHA1",
+ "checksumValue": "27c38e2ca1427fe62d9ef6a30ef50f1c2c5bb9b7"
+ },
+ {
+ "algorithm": "SHA256",
+ "checksumValue": "ed3546fec0e33f14a99c95753357becfaec7c577965dc442d1cefd437acc5e92"
+ }
+ ],
+ "fileName": "Modules/expat/entities.h"
+ },
{
"SPDXID": "SPDXRef-FILE-Modules-expat-expat.h",
"checksums": [
{
"algorithm": "SHA1",
- "checksumValue": "00c5e72b384f5c305be613729184ad37bb491238"
+ "checksumValue": "2037910f6aacebac08a376d5c2b88cdba7309864"
},
{
"algorithm": "SHA256",
- "checksumValue": "eb43180fbdca40e36d9558060e6e654ef4c451ca656ad679e9e1269eb45456b3"
+ "checksumValue": "8dfdb5b7d0392391e74cd9cdb74455fcbebfdcfa75c5d7c6ac59fb5855af31fe"
}
],
"fileName": "Modules/expat/expat.h"
@@ -62,11 +76,11 @@
"checksums": [
{
"algorithm": "SHA1",
- "checksumValue": "d8f9211d52ff0384e229e4d4d56adae5db2d7f91"
+ "checksumValue": "942c816cf73281239728035ca2d2211b5982ed5c"
},
{
"algorithm": "SHA256",
- "checksumValue": "b77f8192baf90aaa41f7023bc68fd1f22ab2552f98758271a1e090544537def5"
+ "checksumValue": "d4e226932e8fd84afd0e396e71b307b2c8f2bf0556d8ea037f43c2dd449b7a73"
}
],
"fileName": "Modules/expat/expat_external.h"
@@ -76,25 +90,39 @@
"checksums": [
{
"algorithm": "SHA1",
- "checksumValue": "69db5031480c50a1e35a51190bd64fcb816b6caf"
+ "checksumValue": "378f1dffca32e580be8fb445677950cd1c4c4ea8"
},
{
"algorithm": "SHA256",
- "checksumValue": "3dac2e4fdec819ede1b081ef776f2421c98ab509f69d5647a21d63d651179df2"
+ "checksumValue": "5e42477487bca7e7caac6b832ab940f39a1a20b8765c945374e4f6c2670f55b6"
}
],
"fileName": "Modules/expat/fallthrough.h"
},
+ {
+ "SPDXID": "SPDXRef-FILE-Modules-expat-hash-table.h",
+ "checksums": [
+ {
+ "algorithm": "SHA1",
+ "checksumValue": "e0ab4fb3f3b06bac642dc525d98107337c3534d0"
+ },
+ {
+ "algorithm": "SHA256",
+ "checksumValue": "ad93851f86df1f4e8f85488dbac53cab3539e59d701ad747c7beea354d69e0dc"
+ }
+ ],
+ "fileName": "Modules/expat/hash_table.h"
+ },
{
"SPDXID": "SPDXRef-FILE-Modules-expat-iasciitab.h",
"checksums": [
{
"algorithm": "SHA1",
- "checksumValue": "1b0e9014c0baa4c6254d2b5e6a67c70148309c34"
+ "checksumValue": "19b25ac4e504efa5e51ce639c83be053da587543"
},
{
"algorithm": "SHA256",
- "checksumValue": "ad8b01e9f323cc4208bcd22241df383d7e8641fe3c8b3415aa513de82531f89f"
+ "checksumValue": "a9cd6f2cf5199ae3c29d22ee4913736fcd984f62132146a0352c88549700e83f"
}
],
"fileName": "Modules/expat/iasciitab.h"
@@ -104,11 +132,11 @@
"checksums": [
{
"algorithm": "SHA1",
- "checksumValue": "2555e70b29c1efc0af40879daafd12f8b36aca2c"
+ "checksumValue": "df8adcb0ea779b2b720d84a687684a08f3bf72c8"
},
{
"algorithm": "SHA256",
- "checksumValue": "4feb1df53898a48ae0ae04b5d0352c90395c8e693e5c2675f8ced41903d6fa94"
+ "checksumValue": "959b292f428b4ba899a620ae9c214e5a731396982aa445a997705bd8a420a6c8"
}
],
"fileName": "Modules/expat/internal.h"
@@ -118,11 +146,11 @@
"checksums": [
{
"algorithm": "SHA1",
- "checksumValue": "d335ecca380e331a0ea7dc33838a4decd93ec1e4"
+ "checksumValue": "2e37879c51aec484072d504d89e963bda5b553e5"
},
{
"algorithm": "SHA256",
- "checksumValue": "eab66226da100372e01e42e1cbcd8ac2bbbb5c1b5f95d735289cc85c7a8fc2ba"
+ "checksumValue": "dfc8d79ebdb977a3fd760591c6a92b7c7ae1eb76cd79003ba386015bb92c2b3d"
}
],
"fileName": "Modules/expat/latin1tab.h"
@@ -132,11 +160,11 @@
"checksums": [
{
"algorithm": "SHA1",
- "checksumValue": "abdf1b9e9642176466ecbb77d5f48e502d01d0d8"
+ "checksumValue": "19ff1e65b76536a4595c38d21a500cbc7b86c408"
},
{
"algorithm": "SHA256",
- "checksumValue": "10c66f1cf9dc28608d57cb19adc8c7c654800e8b5b1b9be176eaed802deca2d9"
+ "checksumValue": "377ca054fdc531360f42a5cb7c522bcbf88b6c67aebc2e29544c37d14e836bde"
}
],
"fileName": "Modules/expat/memory_sanitizer.h"
@@ -146,11 +174,11 @@
"checksums": [
{
"algorithm": "SHA1",
- "checksumValue": "cf2bc9626c945826602ba9170786e9a2a44645e4"
+ "checksumValue": "737800daf4e21db84a3c4ff2a0578b6fb3c3b3ad"
},
{
"algorithm": "SHA256",
- "checksumValue": "67dcf415d37a4b692a6a8bb46f990c02d83f2ef3d01a65cd61c8594a084246f2"
+ "checksumValue": "19a2e7c6ed53a66df77bcc1576a21f20e729f74997566347c050b97fd6244c95"
}
],
"fileName": "Modules/expat/nametab.h"
@@ -160,11 +188,11 @@
"checksums": [
{
"algorithm": "SHA1",
- "checksumValue": "6648f9c12a8d6f77a6eab5ef5c7caa976e7549aa"
+ "checksumValue": "bcde3e9100b62b87d2b2d628bdacddf415782bdb"
},
{
"algorithm": "SHA256",
- "checksumValue": "c1be28dd62282e668d4daedfe756edb68b7da165c442202bb06a9e597cd5c289"
+ "checksumValue": "12ecc9915bccb793ea8bb543cc7d002e226f4e4d6b97ec9839dca41cbe4e2e27"
}
],
"fileName": "Modules/expat/siphash.h"
@@ -174,11 +202,11 @@
"checksums": [
{
"algorithm": "SHA1",
- "checksumValue": "b77c8fcfb551553c81d6fbd94c798c8aa04ad021"
+ "checksumValue": "30276d76d64af27de1d0de06160c5b58c884ee8b"
},
{
"algorithm": "SHA256",
- "checksumValue": "8cd26bd461d334d5e1caedb3af4518d401749f2fc66d56208542b29085159c18"
+ "checksumValue": "3fa349a3a19143366e80a58d9aa950152ef9cd7903f557f971051410b47f335c"
}
],
"fileName": "Modules/expat/utf8tab.h"
@@ -188,39 +216,53 @@
"checksums": [
{
"algorithm": "SHA1",
- "checksumValue": "a3a8c44efd55dbf2cfea8fcee009ec63120ec0a3"
+ "checksumValue": "d296304ae595486ec094e341fed8a8450d4cedbe"
},
{
"algorithm": "SHA256",
- "checksumValue": "e70948500d34dfcba4e9f0b305319dfe2a937c7cbfb687905128b56e1a6f8b33"
+ "checksumValue": "0ab6446eb98abc492ae341ef7607b535e44dedf52633fdc7c6e1a1361aec3922"
}
],
"fileName": "Modules/expat/winconfig.h"
},
{
- "SPDXID": "SPDXRef-FILE-Modules-expat-xcsinc.c",
+ "SPDXID": "SPDXRef-FILE-Modules-expat-xcs.c",
+ "checksums": [
+ {
+ "algorithm": "SHA1",
+ "checksumValue": "4f4a913dc8385799ee56263aed7e60ddb265ed51"
+ },
+ {
+ "algorithm": "SHA256",
+ "checksumValue": "ab9228cf9662af965bd2222cae6797c6379ab0408501965294c00ca828f6bcb8"
+ }
+ ],
+ "fileName": "Modules/expat/xcs.c"
+ },
+ {
+ "SPDXID": "SPDXRef-FILE-Modules-expat-xcs.h",
"checksums": [
{
"algorithm": "SHA1",
- "checksumValue": "69fa7a25f555164f089fdcf290f3af6a1731621f"
+ "checksumValue": "9ec26ee2958c5e8a00eae16813c3681afee15d56"
},
{
"algorithm": "SHA256",
- "checksumValue": "071345c5ccfbe2e46a02839331ee60ee20048348b4408964bff48c4355473b9e"
+ "checksumValue": "105e1e3f694821583c6475a8b8bcad23e40c846c98fbe15988aaafbca8f7a8a6"
}
],
- "fileName": "Modules/expat/xcsinc.c"
+ "fileName": "Modules/expat/xcs.h"
},
{
"SPDXID": "SPDXRef-FILE-Modules-expat-xmlparse.c",
"checksums": [
{
"algorithm": "SHA1",
- "checksumValue": "a5a5dd44ee8eeb73f42fa42ca1499cd282ddf6a6"
+ "checksumValue": "0d49c8bd830acb84dcf87e3c156d980680dadc78"
},
{
"algorithm": "SHA256",
- "checksumValue": "5d2c99b576744edd9545cefe613e0577617f57e16c86387edc13d45710dc97d2"
+ "checksumValue": "c5b0e430fd8e9e9a6b0fe8a3bf3bfc1ebfbedf50a366f923110dcddaabae4c88"
}
],
"fileName": "Modules/expat/xmlparse.c"
@@ -230,11 +272,11 @@
"checksums": [
{
"algorithm": "SHA1",
- "checksumValue": "c8769fcb93f00272a6e6ca560be633649c817ff7"
+ "checksumValue": "56999d78b6ed247b00b0e3283fd174065b04e40f"
},
{
"algorithm": "SHA256",
- "checksumValue": "5b81f0eb0e144b611dbd1bc9e6037075a16bff94f823d57a81eb2a3e4999e91a"
+ "checksumValue": "b1ad87cc3c0d4722358a7dfb1642df7f62066d1613a0a56dc9289e7112fb3f0c"
}
],
"fileName": "Modules/expat/xmlrole.c"
@@ -244,11 +286,11 @@
"checksums": [
{
"algorithm": "SHA1",
- "checksumValue": "ac2964cca107f62dd133bfd4736a9a17defbc401"
+ "checksumValue": "08de6d1246312e179918de3533328000c887a95b"
},
{
"algorithm": "SHA256",
- "checksumValue": "92e41f373b67f6e0dcd7735faef3c3f1e2c17fe59e007e6b74beef6a2e70fa88"
+ "checksumValue": "8a0b61cd6efcd7427acbc86759e9013e7a61755097a1f82cbb2a79c011af5ee5"
}
],
"fileName": "Modules/expat/xmlrole.h"
@@ -258,11 +300,11 @@
"checksums": [
{
"algorithm": "SHA1",
- "checksumValue": "08dba893b34338e64b66f1044f542aa6760dbab1"
+ "checksumValue": "6a5bca82fb56189cc67136d17c9236c16999cdf2"
},
{
"algorithm": "SHA256",
- "checksumValue": "0c842b1876503e699517994317805dd2298d9e11c94dcc87c2ecb6c2b8e00bc0"
+ "checksumValue": "14cc3ff861c70528c7807a1fccf794c7e0c5c00185462e5066092e61e3e1d23c"
}
],
"fileName": "Modules/expat/xmltok.c"
@@ -272,11 +314,11 @@
"checksums": [
{
"algorithm": "SHA1",
- "checksumValue": "d126831eaa5158cff187a8c93f4bc1c8118f3b17"
+ "checksumValue": "d17abcb8cdf7e91fd2bc57ca692ead71cb81f464"
},
{
"algorithm": "SHA256",
- "checksumValue": "91bf003a725a675761ea8d92cebc299a76fd28c3a950572f41bc7ce5327ee7b5"
+ "checksumValue": "25c3d829eab7bcd5b64bafca3bdd1cc368bc71c7b8ebdae757671e4f641b5e64"
}
],
"fileName": "Modules/expat/xmltok.h"
@@ -286,11 +328,11 @@
"checksums": [
{
"algorithm": "SHA1",
- "checksumValue": "3ccb9335589c3ff60aae50ac79b2cdac57999bee"
+ "checksumValue": "e7da04f93f0bc0268b881da7b20d5a9ea6f000da"
},
{
"algorithm": "SHA256",
- "checksumValue": "94eeaef9ed46d10f80f748924fbf41f950b4859d6f234f61fdb2c8f1a8e77bd1"
+ "checksumValue": "2e0e61c0125f165c98b310888c642e36b49068a33b93662e5989a07094cb20bc"
}
],
"fileName": "Modules/expat/xmltok_impl.c"
@@ -300,11 +342,11 @@
"checksums": [
{
"algorithm": "SHA1",
- "checksumValue": "788332fe8040bed71172cddedb69abd848cc62f7"
+ "checksumValue": "f862ff6393d47ac1ad9cd0f5f844b43e7c21a20e"
},
{
"algorithm": "SHA256",
- "checksumValue": "f05ad4fe5e98429a7349ff04f57192cac58c324601f2a2e5e697ab0bc05d36d5"
+ "checksumValue": "a5053c69219d12788088de9bd670537e1c784302766c331afe6b253460d0417d"
}
],
"fileName": "Modules/expat/xmltok_impl.h"
@@ -314,11 +356,11 @@
"checksums": [
{
"algorithm": "SHA1",
- "checksumValue": "41b8c8fc275882c76d4210b7d40a18e506b07147"
+ "checksumValue": "0fc32be2ca285ea118dfafe1a2534d4dc1ebfc4f"
},
{
"algorithm": "SHA256",
- "checksumValue": "b2188c7e5fa5b33e355cf6cf342dfb8f6e23859f2a6b1ddf79841d7f84f7b196"
+ "checksumValue": "d2b1a0c17a8113d3323331a8acd980f22c1e8de316dff27d7fce23a6069e1487"
}
],
"fileName": "Modules/expat/xmltok_ns.c"
@@ -1044,14 +1086,14 @@
"checksums": [
{
"algorithm": "SHA256",
- "checksumValue": "ef7d1994f533c9e7343d6c19f31064fc8ebbcbcaa144be3812b4f43052a05f4c"
+ "checksumValue": "b3e3fcbb629e4d357a9cc0af5b146b85959bcf1cefe87e529d2c0a9234be737f"
}
],
- "downloadLocation": "https://github.com/libexpat/libexpat/releases/download/R_2_8_2/expat-2.8.2.tar.gz",
+ "downloadLocation": "https://github.com/libexpat/libexpat/releases/download/R_2_11_0/expat-2.11.0.tar.gz",
"externalRefs": [
{
"referenceCategory": "SECURITY",
- "referenceLocator": "cpe:2.3:a:libexpat_project:libexpat:2.8.2:*:*:*:*:*:*:*",
+ "referenceLocator": "cpe:2.3:a:libexpat_project:libexpat:2.11.0:*:*:*:*:*:*:*",
"referenceType": "cpe23Type"
}
],
@@ -1059,7 +1101,7 @@
"name": "expat",
"originator": "Organization: Expat development team",
"primaryPackagePurpose": "SOURCE",
- "versionInfo": "2.8.2"
+ "versionInfo": "2.11.0"
},
{
"SPDXID": "SPDXRef-PACKAGE-hacl-star",
@@ -1122,6 +1164,11 @@
"relationshipType": "CONTAINS",
"spdxElementId": "SPDXRef-PACKAGE-expat"
},
+ {
+ "relatedSpdxElement": "SPDXRef-FILE-Modules-expat-entities.h",
+ "relationshipType": "CONTAINS",
+ "spdxElementId": "SPDXRef-PACKAGE-expat"
+ },
{
"relatedSpdxElement": "SPDXRef-FILE-Modules-expat-expat.h",
"relationshipType": "CONTAINS",
@@ -1137,6 +1184,11 @@
"relationshipType": "CONTAINS",
"spdxElementId": "SPDXRef-PACKAGE-expat"
},
+ {
+ "relatedSpdxElement": "SPDXRef-FILE-Modules-expat-hash-table.h",
+ "relationshipType": "CONTAINS",
+ "spdxElementId": "SPDXRef-PACKAGE-expat"
+ },
{
"relatedSpdxElement": "SPDXRef-FILE-Modules-expat-iasciitab.h",
"relationshipType": "CONTAINS",
@@ -1178,7 +1230,12 @@
"spdxElementId": "SPDXRef-PACKAGE-expat"
},
{
- "relatedSpdxElement": "SPDXRef-FILE-Modules-expat-xcsinc.c",
+ "relatedSpdxElement": "SPDXRef-FILE-Modules-expat-xcs.c",
+ "relationshipType": "CONTAINS",
+ "spdxElementId": "SPDXRef-PACKAGE-expat"
+ },
+ {
+ "relatedSpdxElement": "SPDXRef-FILE-Modules-expat-xcs.h",
"relationshipType": "CONTAINS",
"spdxElementId": "SPDXRef-PACKAGE-expat"
},
diff --git a/Misc/stable_abi.toml b/Misc/stable_abi.toml
index d59a7c788fa9e02..dc892fc5f737eee 100644
--- a/Misc/stable_abi.toml
+++ b/Misc/stable_abi.toml
@@ -64,6 +64,8 @@
# on all platforms.)
# - abi3t_opaque: In abi3t, this struct is opaque (as if `struct_abi_kind`
# was 'opaque' and `members` was missing).
+# - is_static_inline_function: for `macro`: actually implemented as a static
+# inline function, rather than a macro.
# Removing items from this file is generally not allowed, and additions should
# be considered with that in mind. See the devguide for exact rules:
@@ -95,6 +97,8 @@
windows = 'maybe'
+### Python 3.2 (initial version) ############################################
+
# Mentioned in PEP 384:
[struct.PyObject]
@@ -627,8 +631,6 @@
added = '3.2'
[function.PyErr_Display]
added = '3.2'
-[function.PyErr_DisplayException]
- added = '3.12'
[function.PyErr_ExceptionMatches]
added = '3.2'
[function.PyErr_Fetch]
@@ -715,6 +717,7 @@
added = '3.2'
[function.PyEval_InitThreads]
added = '3.2'
+ abi_only = true
[function.PyEval_ReleaseLock]
added = '3.2'
abi_only = true
@@ -735,8 +738,6 @@
added = '3.2'
[data.PyExc_BaseException]
added = '3.2'
-[data.PyExc_BaseExceptionGroup]
- added = '3.11'
[data.PyExc_BufferError]
added = '3.2'
[data.PyExc_BytesWarning]
@@ -1351,8 +1352,10 @@
abi_only = true
[function.PySys_SetArgv]
added = '3.2'
+ abi_only = true
[function.PySys_SetArgvEx]
added = '3.2'
+ abi_only = true
[function.PySys_SetObject]
added = '3.2'
[function.PySys_SetPath]
@@ -1642,6 +1645,7 @@
added = '3.2'
[data.Py_FileSystemDefaultEncoding]
added = '3.2'
+ abi_only = true
[function.Py_Finalize]
added = '3.2'
[function.Py_GetBuildInfo]
@@ -1676,6 +1680,7 @@
added = '3.2'
[data.Py_HasFileSystemDefaultEncoding]
added = '3.2'
+ abi_only = true
[function.Py_IncRef]
added = '3.2'
[function.Py_Initialize]
@@ -1696,8 +1701,10 @@
added = '3.2'
[function.Py_SetProgramName]
added = '3.2'
+ abi_only = true
[function.Py_SetPythonHome]
added = '3.2'
+ abi_only = true
[function.Py_SetRecursionLimit]
added = '3.2'
[function.Py_VaBuildValue]
@@ -1867,6 +1874,25 @@
[function.PyThread_start_new_thread]
added = '3.2'
+# Python 3.2 macros
+
+[macro.Py_CLEAR]
+ added = '3.2'
+[macro.Py_DECREF]
+ added = '3.2'
+[macro.Py_INCREF]
+ added = '3.2'
+ is_static_inline_function = true
+[macro.Py_XDECREF]
+ added = '3.2'
+ is_static_inline_function = true
+[macro.Py_XINCREF]
+ added = '3.2'
+ is_static_inline_function = true
+
+
+### Python 3.3 ##############################################################
+
# The following were added in PC/python3.def in Python 3.3:
# 7800f75827b1be557be16f3b18f5170fbf9fae08
# 9c56409d3353b8cd4cfc19e0467bbe23fd34fc92
@@ -1896,6 +1922,9 @@
[function.PyThread_GetInfo]
added = '3.3'
+
+### Python 3.4 ##############################################################
+
# The following were added in PC/python3.def in Python 3.4:
# 3ba3a3ee56c142e93d6bbe20ff6bf939212a30f0
@@ -1904,6 +1933,9 @@
[function.PyType_GetSlot]
added = '3.4'
+
+### Python 3.5 ##############################################################
+
# The following were added in PC/python3.def in Python 3.5:
# 11d7b1423fc44d764eba7065ea5eba58ed748b21
# f3b73ad51da3097d7915796fdc62608b1ab90c0a
@@ -1942,6 +1974,9 @@
[const.Py_tp_finalize]
added = '3.5'
+
+### Python 3.6 ##############################################################
+
# The following were added in PC/python3.def in Python 3.6:
[function.Py_FinalizeEx]
@@ -1956,6 +1991,9 @@
[data.PyExc_ModuleNotFoundError]
added = '3.6'
+
+### Python 3.7 ##############################################################
+
# The following were added in PC/python3.def in Python 3.6.1 and 3.5.3/3.5.4:
[function.PyCodec_NameReplaceErrors]
@@ -2151,12 +2189,16 @@
[const.METH_METHOD]
added = '3.7'
+
+### Python 3.8 ##############################################################
+
# The following were added in PC/python3.def in Python 3.8:
[function.PyImport_GetModule]
added = '3.8'
[data.Py_UTF8Mode]
added = '3.8'
+ abi_only = true
[function.PyExceptionClass_Name]
added = '3.8'
[function.PyIndex_Check]
@@ -2174,11 +2216,14 @@
[function.Py_BytesMain]
added = '3.8'
-# New type flag (PEP 590):
+# New type flag in Python 3.8 (PEP 590):
[const.Py_TPFLAGS_METHOD_DESCRIPTOR]
added = '3.8'
+
+### Python 3.9 ##############################################################
+
# The following were added in PC/python3.def in Python 3.9:
[function.Py_EnterRecursiveCall]
@@ -2198,6 +2243,18 @@
[function.PyObject_GC_IsTracked]
added = '3.9'
+# Python 3.9 macros
+
+[macro.Py_SET_REFCNT]
+ added = '3.9'
+ is_static_inline_function = true
+[macro.Py_SET_TYPE]
+ added = '3.9'
+ is_static_inline_function = true
+
+
+### Python 3.10 #############################################################
+
# The following were added in PC/python3.def in Python 3.10:
[function.Py_GetArgcArgv]
@@ -2237,6 +2294,7 @@
added = '3.10'
[data.Py_FileSystemDefaultEncodeErrors]
added = '3.10'
+ abi_only = true
[function.PyCodec_Unregister]
added = '3.10'
[function.PyErr_SetInterruptEx]
@@ -2262,7 +2320,11 @@
[data.PyExc_EncodingWarning]
added = '3.10'
-# Support for Stable ABI in debug builds
+# Added in 3.7 but in the Stable ABI from 3.10
+[const.METH_FASTCALL]
+ added = '3.10'
+
+# Support for Stable ABI in debug builds (Python 3.10)
[data._Py_RefTotal]
added = '3.10'
@@ -2273,13 +2335,13 @@
ifdef = 'Py_REF_DEBUG'
abi_only = true
-# New slots in 3.10:
+# New slots in Python 3.10:
[const.Py_am_send]
added = '3.10'
-# New GC control functions in Py3.10 (https://bugs.python.org/issue28254)
+# New GC control functions in Python 3.10 (https://github.com/python/cpython/issues/72441)
[function.PyGC_Disable]
added = '3.10'
@@ -2288,8 +2350,11 @@
[function.PyGC_IsEnabled]
added = '3.10'
-# Add new C API in Python 3.11
+### Python 3.11 #############################################################
+
+[data.PyExc_BaseExceptionGroup]
+ added = '3.11'
[function.PyType_GetName]
added = '3.11'
[function.PyType_GetQualName]
@@ -2297,10 +2362,6 @@
[data.PyStructSequence_UnnamedField]
added = '3.11'
-# Added in 3.7 but in the Stable ABI from 3.10
-[const.METH_FASTCALL]
- added = '3.10'
-
# Add stable Py_buffer API in Python 3.11 (https://bugs.python.org/issue45459)
[struct.Py_buffer]
added = '3.11'
@@ -2379,7 +2440,6 @@
[const.PyBUF_WRITE]
added = '3.11'
-
# (Detailed comments aren't really needed for further entries: from here on
# we can use version control logs.)
@@ -2390,6 +2450,11 @@
[function.PyErr_SetHandledException]
added = '3.11'
+
+### Python 3.12 #############################################################
+
+[function.PyErr_DisplayException]
+ added = '3.12'
[function.PyType_FromMetaclass]
added = '3.12'
[const.Py_TPFLAGS_HAVE_VECTORCALL]
@@ -2413,7 +2478,7 @@
added = '3.12'
[function.PyObject_VectorcallMethod]
added = '3.12'
-[macro.PY_VECTORCALL_ARGUMENTS_OFFSET]
+[const.PY_VECTORCALL_ARGUMENTS_OFFSET]
added = '3.12'
[typedef.getbufferproc]
added = '3.12'
@@ -2473,6 +2538,9 @@
# Note: value changed in 3.15 (old value is still accepted)
added = '3.12'
+
+### Python 3.13 #############################################################
+
[function.PyImport_AddModuleRef]
added = '3.13'
[function.PyWeakref_GetRef]
@@ -2555,6 +2623,9 @@
# Note: value changed in 3.15 (old value is still accepted)
added = '3.13'
+
+### Python 3.14 #############################################################
+
[function.Py_TYPE]
# Before 3.14, this was a macro that accessed the PyObject member
added = '3.14'
@@ -2616,6 +2687,9 @@
[function.Py_PACK_VERSION]
added = '3.14'
+
+### Python 3.15 #############################################################
+
[function.PySys_GetAttr]
added = '3.15'
[function.PySys_GetAttrString]
@@ -2773,8 +2847,10 @@
added = '3.15'
[const.Py_tp_module]
added = '3.15'
+[function.PyObject_CallFinalizerFromDealloc]
+ added = '3.15'
-# PEP 757 import/export API.
+# Python 3.15 PEP 757 import/export API.
[function.PyLong_GetNativeLayout]
added = '3.15'
@@ -2800,7 +2876,7 @@
# (The definition of 'full-abi' was clarified when this entry was added.)
struct_abi_kind = 'full-abi'
-# PEP 788 finalization protection
+# Python 3.15 PEP 788 finalization protection
[struct.PyInterpreterGuard]
added = '3.15'
@@ -2830,5 +2906,38 @@
added = '3.15'
struct_abi_kind = 'opaque'
-[function.PyObject_CallFinalizerFromDealloc]
- added = '3.15'
+
+### Python 3.16 #############################################################
+
+[function.Py_HashBuffer]
+ added = '3.16'
+[macro.Py_SETREF]
+ added = '3.16'
+[macro.Py_XSETREF]
+ added = '3.16'
+[function.PyUnicodeWriter_Create]
+ added = '3.16'
+[function.PyUnicodeWriter_Discard]
+ added = '3.16'
+[function.PyUnicodeWriter_Finish]
+ added = '3.16'
+[function.PyUnicodeWriter_WriteChar]
+ added = '3.16'
+[function.PyUnicodeWriter_WriteUTF8]
+ added = '3.16'
+[function.PyUnicodeWriter_WriteASCII]
+ added = '3.16'
+[function.PyUnicodeWriter_WriteWideChar]
+ added = '3.16'
+[function.PyUnicodeWriter_WriteUCS4]
+ added = '3.16'
+[function.PyUnicodeWriter_WriteStr]
+ added = '3.16'
+[function.PyUnicodeWriter_WriteRepr]
+ added = '3.16'
+[function.PyUnicodeWriter_WriteSubstring]
+ added = '3.16'
+[function.PyUnicodeWriter_Format]
+ added = '3.16'
+[function.PyUnicodeWriter_DecodeUTF8Stateful]
+ added = '3.16'
diff --git a/Modules/Setup b/Modules/Setup
index e97a78e628693dc..0a183ae30f8f0ae 100644
--- a/Modules/Setup
+++ b/Modules/Setup
@@ -202,7 +202,7 @@ PYTHONPATH=$(COREPYTHONPATH)
#_gdbm _gdbmmodule.c -lgdbm
#_lzma _lzmamodule.c -llzma
#_uuid _uuidmodule.c -luuid
-#_zstd _zstd/_zstdmodule.c -lzstd -I$(srcdir)/Modules/_zstd
+#_zstd _zstd/_zstdmodule.c _zstd/zstddict.c _zstd/compressor.c _zstd/decompressor.c -lzstd -I$(srcdir)/Modules/_zstd
#zlib zlibmodule.c -lz
# The readline module also supports libeditline (-leditline).
diff --git a/Modules/Setup.bootstrap.in b/Modules/Setup.bootstrap.in
index 65a1fefe72e92ec..1d1de43fd8f05b4 100644
--- a/Modules/Setup.bootstrap.in
+++ b/Modules/Setup.bootstrap.in
@@ -1,5 +1,9 @@
# -*- makefile -*-
+# Mark bootstrap modules explicitly so older Makefile recipes work
+# without passing -b to makesetup (gh-161364).
+*bootstrap*
+
# ---
# Built-in modules required to get a functioning interpreter;
# cannot be built as shared!
diff --git a/Modules/Setup.stdlib.in b/Modules/Setup.stdlib.in
index 524f1466b191f64..d8cd8de10dfe084 100644
--- a/Modules/Setup.stdlib.in
+++ b/Modules/Setup.stdlib.in
@@ -172,9 +172,9 @@
@MODULE_XXSUBTYPE_TRUE@xxsubtype xxsubtype.c
@MODULE__XXTESTFUZZ_TRUE@_xxtestfuzz _xxtestfuzz/_xxtestfuzz.c _xxtestfuzz/fuzzer.c
@MODULE__TESTBUFFER_TRUE@_testbuffer _testbuffer.c
-@MODULE__TESTINTERNALCAPI_TRUE@_testinternalcapi _testinternalcapi.c _testinternalcapi/test_lock.c _testinternalcapi/pytime.c _testinternalcapi/set.c _testinternalcapi/test_critical_sections.c _testinternalcapi/complex.c _testinternalcapi/interpreter.c _testinternalcapi/tuple.c
-@MODULE__TESTCAPI_TRUE@_testcapi _testcapimodule.c _testcapi/vectorcall.c _testcapi/heaptype.c _testcapi/abstract.c _testcapi/unicode.c _testcapi/dict.c _testcapi/set.c _testcapi/list.c _testcapi/tuple.c _testcapi/getargs.c _testcapi/datetime.c _testcapi/docstring.c _testcapi/mem.c _testcapi/watchers.c _testcapi/long.c _testcapi/float.c _testcapi/complex.c _testcapi/numbers.c _testcapi/structmember.c _testcapi/exceptions.c _testcapi/code.c _testcapi/buffer.c _testcapi/pyatomic.c _testcapi/run.c _testcapi/file.c _testcapi/codec.c _testcapi/immortal.c _testcapi/gc.c _testcapi/hash.c _testcapi/time.c _testcapi/bytes.c _testcapi/object.c _testcapi/modsupport.c _testcapi/monitoring.c _testcapi/config.c _testcapi/import.c _testcapi/frame.c _testcapi/type.c _testcapi/function.c _testcapi/module.c _testcapi/weakref.c
-@MODULE__TESTLIMITEDCAPI_TRUE@_testlimitedcapi _testlimitedcapi.c _testlimitedcapi/abstract.c _testlimitedcapi/bytearray.c _testlimitedcapi/bytes.c _testlimitedcapi/codec.c _testlimitedcapi/complex.c _testlimitedcapi/dict.c _testlimitedcapi/eval.c _testlimitedcapi/float.c _testlimitedcapi/heaptype_relative.c _testlimitedcapi/import.c _testlimitedcapi/list.c _testlimitedcapi/long.c _testlimitedcapi/object.c _testlimitedcapi/pyos.c _testlimitedcapi/set.c _testlimitedcapi/slots.c _testlimitedcapi/sys.c _testlimitedcapi/threadstate.c _testlimitedcapi/tuple.c _testlimitedcapi/unicode.c _testlimitedcapi/vectorcall_limited.c _testlimitedcapi/version.c _testlimitedcapi/file.c _testlimitedcapi/weakref.c _testlimitedcapi/run.c
+@MODULE__TESTINTERNALCAPI_TRUE@_testinternalcapi _testinternalcapi.c _testinternalcapi/test_lock.c _testinternalcapi/pytime.c _testinternalcapi/set.c _testinternalcapi/test_critical_sections.c _testinternalcapi/complex.c _testinternalcapi/interpreter.c _testinternalcapi/tokenizer.c _testinternalcapi/tuple.c _testinternalcapi/typecache.c
+@MODULE__TESTCAPI_TRUE@_testcapi _testcapimodule.c _testcapi/vectorcall.c _testcapi/heaptype.c _testcapi/abstract.c _testcapi/unicode.c _testcapi/dict.c _testcapi/set.c _testcapi/list.c _testcapi/tuple.c _testcapi/getargs.c _testcapi/datetime.c _testcapi/docstring.c _testcapi/mem.c _testcapi/watchers.c _testcapi/long.c _testcapi/float.c _testcapi/complex.c _testcapi/numbers.c _testcapi/structmember.c _testcapi/exceptions.c _testcapi/code.c _testcapi/buffer.c _testcapi/pyatomic.c _testcapi/run.c _testcapi/file.c _testcapi/codec.c _testcapi/immortal.c _testcapi/gc.c _testcapi/hash.c _testcapi/time.c _testcapi/bytes.c _testcapi/object.c _testcapi/modsupport.c _testcapi/monitoring.c _testcapi/config.c _testcapi/import.c _testcapi/frame.c _testcapi/type.c _testcapi/function.c _testcapi/module.c _testcapi/weakref.c _testcapi/marshal.c _testcapi/fpcast.c
+@MODULE__TESTLIMITEDCAPI_TRUE@_testlimitedcapi _testlimitedcapi.c _testlimitedcapi/abstract.c _testlimitedcapi/bytearray.c _testlimitedcapi/bytes.c _testlimitedcapi/capsule.c _testlimitedcapi/codec.c _testlimitedcapi/complex.c _testlimitedcapi/dict.c _testlimitedcapi/eval.c _testlimitedcapi/float.c _testlimitedcapi/heaptype_relative.c _testlimitedcapi/import.c _testlimitedcapi/list.c _testlimitedcapi/long.c _testlimitedcapi/object.c _testlimitedcapi/pyos.c _testlimitedcapi/set.c _testlimitedcapi/slice.c _testlimitedcapi/slots.c _testlimitedcapi/sys.c _testlimitedcapi/threadstate.c _testlimitedcapi/tuple.c _testlimitedcapi/unicode.c _testlimitedcapi/vectorcall_limited.c _testlimitedcapi/version.c _testlimitedcapi/file.c _testlimitedcapi/weakref.c _testlimitedcapi/run.c _testlimitedcapi/type.c _testlimitedcapi/hash.c _testlimitedcapi/build.c
@MODULE__TESTCLINIC_TRUE@_testclinic _testclinic.c
@MODULE__TESTCLINIC_LIMITED_TRUE@_testclinic_limited _testclinic_limited.c
diff --git a/Modules/_abc.c b/Modules/_abc.c
index 5826efbfecb6901..79904513c49b643 100644
--- a/Modules/_abc.c
+++ b/Modules/_abc.c
@@ -4,11 +4,17 @@
#endif
#include "Python.h"
-#include "pycore_moduleobject.h" // _PyModule_GetState()
-#include "pycore_object.h" // _PyType_GetSubclasses()
-#include "pycore_runtime.h" // _Py_ID()
-#include "pycore_setobject.h" // _PySet_NextEntry()
-#include "pycore_weakref.h" // _PyWeakref_GET_REF()
+#include "pycore_critical_section.h" // Py_BEGIN_CRITICAL_SECTION()
+#include "pycore_moduleobject.h" // _PyModule_GetState()
+#include "pycore_object.h" // _PyType_LookupStackRefAndVersion()
+#include "pycore_object_deferred.h" // _PyObject_SetDeferredRefcount()
+#include "pycore_pyatomic_ft_wrappers.h" // FT_ATOMIC_LOAD_PTR_ACQUIRE()
+#include "pycore_pymem.h" // _PyMem_FreeDelayed()
+#include "pycore_pystate.h" // _PyThreadState_GET()
+#include "pycore_runtime.h" // _Py_ID()
+#include "pycore_stackref.h" // _PyStackRef
+#include "pycore_typeobject.h" // _PyType_GetSubclasses()
+#include "pycore_pyhash.h"
#include "clinic/_abc.c.h"
/*[clinic input]
@@ -22,6 +28,14 @@ PyDoc_STRVAR(_abc__doc__,
typedef struct {
PyTypeObject *_abc_data_type;
uint64_t abc_invalidation_counter;
+ // Default implementations, compared by identity to skip the call
+ // when a class doesn't override them.
+ PyObject *object_class_descr;
+ PyObject *object_subclasshook;
+ PyObject *type_subclasses;
+ // ABCMeta.__subclasscheck__, set by abc.py on import. Classes using it
+ // are checked directly instead of going through issubclass().
+ PyObject *subclasscheck_func;
} _abcmodule_state;
static inline _abcmodule_state*
@@ -35,57 +49,288 @@ get_abc_state(PyObject *module)
static inline uint64_t
get_invalidation_counter(_abcmodule_state *state)
{
-#ifdef Py_GIL_DISABLED
- return _Py_atomic_load_uint64(&state->abc_invalidation_counter);
-#else
- return state->abc_invalidation_counter;
-#endif
+ return FT_ATOMIC_LOAD_UINT64_RELAXED(state->abc_invalidation_counter);
}
static inline void
increment_invalidation_counter(_abcmodule_state *state)
{
-#ifdef Py_GIL_DISABLED
- _Py_atomic_add_uint64(&state->abc_invalidation_counter, 1);
-#else
- state->abc_invalidation_counter++;
-#endif
+ FT_ATOMIC_ADD_UINT64(state->abc_invalidation_counter, 1);
+}
+
+
+// The registry and the caches of an ABC are sets of classes, stored as
+// open addressed hash tables keyed by the address of the class.
+//
+// Each entry also holds a weakref to the class. It is only used to check
+// that the class is still alive, as the address of a dead class can be
+// reused by a new one. The weakrefs have no callback, so the same weakref
+// is shared by all the tables a class is in, and dead entries are only
+// removed when the table is rebuilt.
+typedef struct {
+ PyObject *key; /* borrowed ref of a class */
+ PyObject *ref; /* weakref to key */
+} abc_entry;
+
+typedef struct {
+ size_t mask; /* number of entries - 1 */
+ size_t used; /* entries with a key, live or dead */
+ abc_entry entries[];
+} abc_table;
+
+#define TABLE_MIN_SIZE 8
+#define PERTURB_SHIFT 5
+
+// Shared empty table, so that lookups don't need a NULL check.
+// It is never modified or freed.
+static const abc_table empty_table_struct = {
+ 0, /* mask */
+ 0, /* used */
+ {{NULL, NULL}}, /* entries */
+};
+
+#define EMPTY_TABLE ((abc_table *)&empty_table_struct)
+
+static inline size_t
+abc_table_nbytes(size_t size)
+{
+ return offsetof(abc_table, entries) + size * sizeof(abc_entry);
+}
+
+static abc_table *
+abc_table_new(size_t size)
+{
+ assert((size & (size - 1)) == 0 && size >= TABLE_MIN_SIZE);
+ abc_table *table = PyMem_Calloc(1, abc_table_nbytes(size));
+ if (table == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+ table->mask = size - 1;
+ table->used = 0;
+ return table;
+}
+
+// Free a table and its weakrefs. Use delayed if other threads
+// can still be reading the table.
+static void
+abc_table_release(abc_table *table, int delayed)
+{
+ if (table == EMPTY_TABLE) {
+ return;
+ }
+ for (size_t i = 0; i <= table->mask; i++) {
+ PyObject *ref = table->entries[i].ref;
+ if (delayed) {
+ _PyObject_XDecRefDelayed(ref);
+ }
+ else {
+ Py_XDECREF(ref);
+ }
+ }
+ if (delayed) {
+ _PyMem_FreeDelayed(table, abc_table_nbytes(table->mask + 1));
+ }
+ else {
+ PyMem_Free(table);
+ }
+}
+
+static inline size_t
+abc_hash(PyObject *key)
+{
+ return (size_t)_Py_HashPointerRaw(key);
+}
+
+static inline int
+abc_entry_is_live(PyObject *ref, PyObject *key)
+{
+ // The caller holds a strong reference to key, so a weakref pointing
+ // to key cannot be of a dead class which was at the same address.
+ // wr_object only changes when key dies, so a relaxed load is enough.
+ assert(ref != NULL);
+ PyWeakReference *wr = (PyWeakReference *)ref;
+ return FT_ATOMIC_LOAD_PTR_RELAXED(wr->wr_object) == key;
+}
+
+static abc_entry *
+abc_table_find(abc_table *table, PyObject *key, PyObject **found)
+{
+ size_t mask = table->mask;
+ size_t perturb = abc_hash(key);
+ size_t i = perturb & mask;
+ for (;;) {
+ abc_entry *entry = &table->entries[i];
+ PyObject *k = FT_ATOMIC_LOAD_PTR_ACQUIRE(entry->key);
+ if (k == NULL || k == key) {
+ *found = k;
+ return entry;
+ }
+ perturb >>= PERTURB_SHIFT;
+ i = (i * 5 + perturb + 1) & mask;
+ }
+}
+
+// Lock-free, the caller must hold a strong reference to key.
+static int
+abc_table_contains(abc_table *table, PyObject *key)
+{
+ PyObject *found;
+ abc_entry *entry = abc_table_find(table, key, &found);
+ if (found == NULL) {
+ return 0;
+ }
+ PyObject *ref = FT_ATOMIC_LOAD_PTR_ACQUIRE(entry->ref);
+ return abc_entry_is_live(ref, key);
+}
+
+static abc_table *
+abc_table_rebuild(abc_table *old, size_t extra)
+{
+ size_t live = 0;
+ for (size_t i = 0; i <= old->mask; i++) {
+ abc_entry *entry = &old->entries[i];
+ if (entry->key != NULL && abc_entry_is_live(entry->ref, entry->key)) {
+ live++;
+ }
+ }
+ size_t size = TABLE_MIN_SIZE;
+ while (size < (live + extra) * 2) {
+ size <<= 1;
+ }
+ abc_table *table = abc_table_new(size);
+ if (table == NULL) {
+ return NULL;
+ }
+ for (size_t i = 0; i <= old->mask; i++) {
+ abc_entry *entry = &old->entries[i];
+ if (entry->key == NULL) {
+ continue;
+ }
+ if (abc_entry_is_live(entry->ref, entry->key)) {
+ PyObject *found;
+ abc_entry *dst = abc_table_find(table, entry->key, &found);
+ assert(found == NULL);
+ dst->key = entry->key;
+ dst->ref = entry->ref;
+ table->used++;
+ }
+ else {
+ _PyObject_XDecRefDelayed(entry->ref);
+ }
+ }
+ return table;
+}
+
+static int
+abc_table_add(abc_table **ptable, PyObject *key, PyObject *ref)
+{
+ abc_table *table = *ptable;
+ PyObject *found;
+ abc_entry *entry = abc_table_find(table, key, &found);
+ if (found == key) {
+ // The existing weakref can be of a dead class at the same address.
+ PyObject *old = entry->ref;
+ if (old == ref) {
+ Py_DECREF(ref);
+ }
+ else {
+ FT_ATOMIC_STORE_PTR_RELEASE(entry->ref, ref);
+ _PyObject_XDecRefDelayed(old);
+ }
+ return 0;
+ }
+ // Always true for EMPTY_TABLE.
+ if ((table->used + 1) * 3 > (table->mask + 1) * 2) {
+ abc_table *newtable = abc_table_rebuild(table, 1);
+ if (newtable == NULL) {
+ Py_DECREF(ref);
+ return -1;
+ }
+ FT_ATOMIC_STORE_PTR_RELEASE(*ptable, newtable);
+ if (table != EMPTY_TABLE) {
+ // The weakrefs were moved to newtable.
+ _PyMem_FreeDelayed(table, abc_table_nbytes(table->mask + 1));
+ }
+ table = newtable;
+ entry = abc_table_find(table, key, &found);
+ }
+ assert(found == NULL);
+ FT_ATOMIC_STORE_PTR_RELAXED(entry->ref, ref);
+ FT_ATOMIC_STORE_PTR_RELEASE(entry->key, key);
+ table->used++;
+ return 0;
+}
+
+static void
+abc_table_clear(abc_table **ptable)
+{
+ abc_table *table = *ptable;
+ if (table != EMPTY_TABLE) {
+ FT_ATOMIC_STORE_PTR_RELAXED(*ptable, EMPTY_TABLE);
+ abc_table_release(table, 1);
+ }
+}
+
+static PyObject *
+abc_table_snapshot(abc_table *table)
+{
+ PyObject *list = PyList_New(0);
+ if (list == NULL) {
+ return NULL;
+ }
+ for (size_t i = 0; i <= table->mask; i++) {
+ abc_entry *entry = &table->entries[i];
+ if (entry->key == NULL) {
+ continue;
+ }
+ PyObject *obj;
+ if (PyWeakref_GetRef(entry->ref, &obj) < 0) {
+ Py_DECREF(list);
+ return NULL;
+ }
+ if (obj == NULL) {
+ continue;
+ }
+ int rc = PyList_Append(list, obj);
+ Py_DECREF(obj);
+ if (rc < 0) {
+ Py_DECREF(list);
+ return NULL;
+ }
+ }
+ return list;
}
-/* This object stores internal state for ABCs.
- Note that we can use normal sets for caches,
- since they are never iterated over. */
+
+// Internal state of an ABC, stored in its _abc_impl attribute.
+
typedef struct {
PyObject_HEAD
- /* These sets of weak references are lazily created. Once created, they
- will point to the same sets until the ABCMeta object is destroyed or
- cleared, both of which will only happen while the object is visible to a
- single thread. */
- PyObject *_abc_registry;
- PyObject *_abc_cache;
- PyObject *_abc_negative_cache;
- uint64_t _abc_negative_cache_version;
+ abc_table *registry;
+ abc_table *cache;
+ abc_table *negative_cache;
+ uint64_t negative_cache_version;
} _abc_data;
#define _abc_data_CAST(op) ((_abc_data *)(op))
+// The version is updated after the negative cache is cleared and read
+// before the negative cache is, so a reader which sees the new version
+// never sees the old entries.
static inline uint64_t
get_cache_version(_abc_data *impl)
{
-#ifdef Py_GIL_DISABLED
- return _Py_atomic_load_uint64(&impl->_abc_negative_cache_version);
-#else
- return impl->_abc_negative_cache_version;
-#endif
+ return FT_ATOMIC_LOAD_UINT64_ACQUIRE(impl->negative_cache_version);
}
static inline void
set_cache_version(_abc_data *impl, uint64_t version)
{
#ifdef Py_GIL_DISABLED
- _Py_atomic_store_uint64(&impl->_abc_negative_cache_version, version);
+ _Py_atomic_store_uint64_release(&impl->negative_cache_version, version);
#else
- impl->_abc_negative_cache_version = version;
+ impl->negative_cache_version = version;
#endif
}
@@ -93,10 +338,9 @@ static int
abc_data_traverse(PyObject *op, visitproc visit, void *arg)
{
_abc_data *self = _abc_data_CAST(op);
+ // The tables only hold weakrefs without callbacks which cannot
+ // be part of a reference cycle.
Py_VISIT(Py_TYPE(self));
- Py_VISIT(self->_abc_registry);
- Py_VISIT(self->_abc_cache);
- Py_VISIT(self->_abc_negative_cache);
return 0;
}
@@ -104,9 +348,15 @@ static int
abc_data_clear(PyObject *op)
{
_abc_data *self = _abc_data_CAST(op);
- Py_CLEAR(self->_abc_registry);
- Py_CLEAR(self->_abc_cache);
- Py_CLEAR(self->_abc_negative_cache);
+ abc_table *registry = self->registry;
+ abc_table *cache = self->cache;
+ abc_table *negative_cache = self->negative_cache;
+ self->registry = EMPTY_TABLE;
+ self->cache = EMPTY_TABLE;
+ self->negative_cache = EMPTY_TABLE;
+ abc_table_release(registry, 0);
+ abc_table_release(cache, 0);
+ abc_table_release(negative_cache, 0);
return 0;
}
@@ -135,10 +385,12 @@ abc_data_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
return NULL;
}
- self->_abc_registry = NULL;
- self->_abc_cache = NULL;
- self->_abc_negative_cache = NULL;
- self->_abc_negative_cache_version = get_invalidation_counter(state);
+ self->registry = EMPTY_TABLE;
+ self->cache = EMPTY_TABLE;
+ self->negative_cache = EMPTY_TABLE;
+ self->negative_cache_version = get_invalidation_counter(state);
+ // Avoid refcount contention between threads.
+ _PyObject_SetDeferredRefcount((PyObject *)self);
return (PyObject *) self;
}
@@ -162,100 +414,135 @@ static PyType_Spec _abc_data_type_spec = {
};
static _abc_data *
-_get_impl(PyObject *module, PyObject *self)
+lookup_impl(_abcmodule_state *state, PyObject *self, _PyCStackRef *cref)
{
- _abcmodule_state *state = get_abc_state(module);
- PyObject *impl = PyObject_GetAttr(self, &_Py_ID(_abc_impl));
- if (impl == NULL) {
+ if (!PyType_Check(self)) {
return NULL;
}
+ _PyType_LookupStackRefAndVersion((PyTypeObject *)self, &_Py_ID(_abc_impl),
+ &cref->ref);
+ if (PyStackRef_IsNull(cref->ref)) {
+ return NULL;
+ }
+ PyObject *impl = PyStackRef_AsPyObjectBorrow(cref->ref);
if (!Py_IS_TYPE(impl, state->_abc_data_type)) {
- PyErr_SetString(PyExc_TypeError, "_abc_impl is set to a wrong type");
- Py_DECREF(impl);
+ PyStackRef_CLOSE(cref->ref);
+ cref->ref = PyStackRef_NULL;
return NULL;
}
return (_abc_data *)impl;
}
+// Like lookup_impl() but falls back to a full attribute lookup,
+// and sets an exception on failure.
+static _abc_data *
+get_impl(_abcmodule_state *state, PyObject *self, _PyCStackRef *cref)
+{
+ _abc_data *impl = lookup_impl(state, self, cref);
+ if (impl != NULL) {
+ return impl;
+ }
+ cref->ref = _PyObject_GetAttrStackRef(self, &_Py_ID(_abc_impl));
+ if (PyStackRef_IsNull(cref->ref)) {
+ return NULL;
+ }
+ impl = (_abc_data *)PyStackRef_AsPyObjectBorrow(cref->ref);
+ if (!Py_IS_TYPE(impl, state->_abc_data_type)) {
+ PyErr_SetString(PyExc_TypeError, "_abc_impl is set to a wrong type");
+ PyStackRef_CLOSE(cref->ref);
+ cref->ref = PyStackRef_NULL;
+ return NULL;
+ }
+ return impl;
+}
+
static int
-_in_weak_set(_abc_data *impl, PyObject **pset, PyObject *obj)
+type_lookup_is(PyTypeObject *type, PyObject *name, PyObject *expected)
{
- PyObject *set;
- Py_BEGIN_CRITICAL_SECTION(impl);
- set = *pset;
- Py_END_CRITICAL_SECTION();
- if (set == NULL || PySet_GET_SIZE(set) == 0) {
- return 0;
+ _PyStackRef ref;
+ _PyType_LookupStackRefAndVersion(type, name, &ref);
+ if (PyStackRef_IsNull(ref)) {
+ return expected == NULL;
}
- PyObject *ref = PyWeakref_NewRef(obj, NULL);
+ int res = (PyStackRef_AsPyObjectBorrow(ref) == expected);
+ PyStackRef_CLOSE(ref);
+ return res;
+}
+
+static int
+add_to_table(_abc_data *impl, abc_table **ptable, PyObject *cls)
+{
+ // PyWeakref_NewRef() can lock cls, call it outside the critical section.
+ PyObject *ref = PyWeakref_NewRef(cls, NULL);
if (ref == NULL) {
- if (PyErr_ExceptionMatches(PyExc_TypeError)) {
- PyErr_Clear();
- return 0;
- }
return -1;
}
- int res = PySet_Contains(set, ref);
- Py_DECREF(ref);
+ int res;
+ Py_BEGIN_CRITICAL_SECTION(impl);
+ res = abc_table_add(ptable, cls, ref);
+ Py_END_CRITICAL_SECTION();
return res;
}
-static PyObject *
-_destroy(PyObject *setweakref, PyObject *objweakref)
+// Add cls to the negative cache if it is still valid for counter.
+static int
+add_to_negative_cache(_abc_data *impl, PyObject *cls, uint64_t counter)
{
- PyObject *set = _PyWeakref_GET_REF(setweakref);
- if (set == NULL) {
- Py_RETURN_NONE;
+ PyObject *ref = PyWeakref_NewRef(cls, NULL);
+ if (ref == NULL) {
+ return -1;
}
- if (PySet_Discard(set, objweakref) < 0) {
- Py_DECREF(set);
- return NULL;
+ int res = 0;
+ Py_BEGIN_CRITICAL_SECTION(impl);
+ if (impl->negative_cache_version == counter) {
+ res = abc_table_add(&impl->negative_cache, cls, ref);
}
- Py_DECREF(set);
- Py_RETURN_NONE;
+ else {
+ Py_DECREF(ref);
+ }
+ Py_END_CRITICAL_SECTION();
+ return res;
}
-static PyMethodDef _destroy_def = {
- "_destroy", _destroy, METH_O
-};
+typedef enum {
+ CACHE_UNKNOWN = -1, // not cached or stale
+ CACHE_NEGATIVE = 0, // in the negative cache
+ CACHE_POSITIVE = 1, // in the positive cache
+} cache_result;
-static int
-_add_to_weak_set(_abc_data *impl, PyObject **pset, PyObject *obj)
+static cache_result
+lookup_caches(_abcmodule_state *state, _abc_data *impl, PyObject *subclass)
{
- PyObject *set;
- Py_BEGIN_CRITICAL_SECTION(impl);
- set = *pset;
- if (set == NULL) {
- set = *pset = PySet_New(NULL);
- }
- Py_END_CRITICAL_SECTION();
- if (set == NULL) {
- return -1;
+ abc_table *table = FT_ATOMIC_LOAD_PTR_ACQUIRE(impl->cache);
+ if (abc_table_contains(table, subclass)) {
+ return CACHE_POSITIVE;
+ }
+ if (get_cache_version(impl) == get_invalidation_counter(state)) {
+ table = FT_ATOMIC_LOAD_PTR_ACQUIRE(impl->negative_cache);
+ if (abc_table_contains(table, subclass)) {
+ return CACHE_NEGATIVE;
+ }
}
+ return CACHE_UNKNOWN;
+}
- PyObject *ref, *wr;
- PyObject *destroy_cb;
- wr = PyWeakref_NewRef(set, NULL);
- if (wr == NULL) {
- return -1;
- }
- destroy_cb = PyCFunction_NewEx(&_destroy_def, wr, NULL);
- if (destroy_cb == NULL) {
- Py_DECREF(wr);
- return -1;
+// Clear the negative cache if register() was called since it was last
+// validated.
+static void
+validate_negative_cache(_abc_data *impl, uint64_t counter)
+{
+ if (get_cache_version(impl) >= counter) {
+ return;
}
- ref = PyWeakref_NewRef(obj, destroy_cb);
- Py_DECREF(destroy_cb);
- if (ref == NULL) {
- Py_DECREF(wr);
- return -1;
+ Py_BEGIN_CRITICAL_SECTION(impl);
+ if (impl->negative_cache_version < counter) {
+ abc_table_clear(&impl->negative_cache);
+ set_cache_version(impl, counter);
}
- int ret = PySet_Add(set, ref);
- Py_DECREF(wr);
- Py_DECREF(ref);
- return ret;
+ Py_END_CRITICAL_SECTION();
}
+
/*[clinic input]
_abc._reset_registry
@@ -271,19 +558,22 @@ static PyObject *
_abc__reset_registry(PyObject *module, PyObject *self)
/*[clinic end generated code: output=92d591a43566cc10 input=12a0b7eb339ac35c]*/
{
- _abc_data *impl = _get_impl(module, self);
- if (impl == NULL) {
- return NULL;
+ PyThreadState *tstate = _PyThreadState_GET();
+ _PyCStackRef cref;
+ _PyThreadState_PushCStackRef(tstate, &cref);
+ _abc_data *impl = get_impl(get_abc_state(module), self, &cref);
+ if (impl != NULL) {
+ Py_BEGIN_CRITICAL_SECTION(impl);
+ abc_table_clear(&impl->registry);
+ // Registered classes are also in the cache, and register()
+ // does nothing for a class which is cached as a subclass.
+ abc_table_clear(&impl->cache);
+ Py_END_CRITICAL_SECTION();
}
- PyObject *registry;
- Py_BEGIN_CRITICAL_SECTION(impl);
- registry = impl->_abc_registry;
- Py_END_CRITICAL_SECTION();
- if (registry != NULL && PySet_Clear(registry) < 0) {
- Py_DECREF(impl);
+ _PyThreadState_PopCStackRef(tstate, &cref);
+ if (impl == NULL) {
return NULL;
}
- Py_DECREF(impl);
Py_RETURN_NONE;
}
@@ -302,26 +592,44 @@ static PyObject *
_abc__reset_caches(PyObject *module, PyObject *self)
/*[clinic end generated code: output=f296f0d5c513f80c input=c0ac616fd8acfb6f]*/
{
- _abc_data *impl = _get_impl(module, self);
+ PyThreadState *tstate = _PyThreadState_GET();
+ _PyCStackRef cref;
+ _PyThreadState_PushCStackRef(tstate, &cref);
+ _abc_data *impl = get_impl(get_abc_state(module), self, &cref);
+ if (impl != NULL) {
+ Py_BEGIN_CRITICAL_SECTION(impl);
+ abc_table_clear(&impl->cache);
+ abc_table_clear(&impl->negative_cache);
+ Py_END_CRITICAL_SECTION();
+ }
+ _PyThreadState_PopCStackRef(tstate, &cref);
if (impl == NULL) {
return NULL;
}
- PyObject *cache, *negative_cache;
- Py_BEGIN_CRITICAL_SECTION(impl);
- cache = impl->_abc_cache;
- negative_cache = impl->_abc_negative_cache;
- Py_END_CRITICAL_SECTION();
- if (cache != NULL && PySet_Clear(cache) < 0) {
- Py_DECREF(impl);
+ Py_RETURN_NONE;
+}
+
+static PyObject *
+weakref_set_from_list(PyObject *list)
+{
+ PyObject *set = PySet_New(NULL);
+ if (set == NULL) {
return NULL;
}
- /* also the second cache */
- if (negative_cache != NULL && PySet_Clear(negative_cache) < 0) {
- Py_DECREF(impl);
- return NULL;
+ for (Py_ssize_t i = 0; i < PyList_GET_SIZE(list); i++) {
+ PyObject *ref = PyWeakref_NewRef(PyList_GET_ITEM(list, i), NULL);
+ if (ref == NULL) {
+ Py_DECREF(set);
+ return NULL;
+ }
+ int rc = PySet_Add(set, ref);
+ Py_DECREF(ref);
+ if (rc < 0) {
+ Py_DECREF(set);
+ return NULL;
+ }
}
- Py_DECREF(impl);
- Py_RETURN_NONE;
+ return set;
}
/*[clinic input]
@@ -341,19 +649,41 @@ static PyObject *
_abc__get_dump(PyObject *module, PyObject *self)
/*[clinic end generated code: output=9d9569a8e2c1c443 input=2c5deb1bfe9e3c79]*/
{
- _abc_data *impl = _get_impl(module, self);
+ PyThreadState *tstate = _PyThreadState_GET();
+ _PyCStackRef cref;
+ _PyThreadState_PushCStackRef(tstate, &cref);
+ _abc_data *impl = get_impl(get_abc_state(module), self, &cref);
if (impl == NULL) {
+ _PyThreadState_PopCStackRef(tstate, &cref);
return NULL;
}
- PyObject *res;
+ PyObject *lists[3] = {NULL, NULL, NULL};
+ PyObject *sets[3] = {NULL, NULL, NULL};
+ PyObject *res = NULL;
+ uint64_t version;
Py_BEGIN_CRITICAL_SECTION(impl);
- res = Py_BuildValue("NNNK",
- PySet_New(impl->_abc_registry),
- PySet_New(impl->_abc_cache),
- PySet_New(impl->_abc_negative_cache),
- get_cache_version(impl));
+ lists[0] = abc_table_snapshot(impl->registry);
+ lists[1] = abc_table_snapshot(impl->cache);
+ lists[2] = abc_table_snapshot(impl->negative_cache);
+ version = get_cache_version(impl);
Py_END_CRITICAL_SECTION();
- Py_DECREF(impl);
+ _PyThreadState_PopCStackRef(tstate, &cref);
+ for (int i = 0; i < 3; i++) {
+ if (lists[i] == NULL) {
+ goto done;
+ }
+ sets[i] = weakref_set_from_list(lists[i]);
+ if (sets[i] == NULL) {
+ goto done;
+ }
+ }
+ res = Py_BuildValue("OOOK", sets[0], sets[1], sets[2],
+ (unsigned long long)version);
+done:
+ for (int i = 0; i < 3; i++) {
+ Py_XDECREF(lists[i]);
+ Py_XDECREF(sets[i]);
+ }
return res;
}
@@ -580,18 +910,20 @@ _abc__abc_register_impl(PyObject *module, PyObject *self, PyObject *subclass)
if (result < 0) {
return NULL;
}
- _abc_data *impl = _get_impl(module, self);
- if (impl == NULL) {
- return NULL;
- }
- if (_add_to_weak_set(impl, &impl->_abc_registry, subclass) < 0) {
- Py_DECREF(impl);
+ _abcmodule_state *state = get_abc_state(module);
+ PyThreadState *tstate = _PyThreadState_GET();
+ _PyCStackRef cref;
+ _PyThreadState_PushCStackRef(tstate, &cref);
+ _abc_data *impl = get_impl(state, self, &cref);
+ int err = (impl == NULL
+ || add_to_table(impl, &impl->registry, subclass) < 0);
+ _PyThreadState_PopCStackRef(tstate, &cref);
+ if (err) {
return NULL;
}
- Py_DECREF(impl);
/* Invalidate negative cache */
- increment_invalidation_counter(get_abc_state(module));
+ increment_invalidation_counter(state);
/* Set Py_TPFLAGS_SEQUENCE or Py_TPFLAGS_MAPPING flag */
if (PyType_Check(self)) {
@@ -607,6 +939,16 @@ _abc__abc_register_impl(PyObject *module, PyObject *self, PyObject *subclass)
}
+// True if instance.__class__ is type(instance) and the lookup
+// doesn't run any Python code.
+static inline int
+has_default_class_attr(_abcmodule_state *state, PyObject *instance)
+{
+ PyTypeObject *tp = Py_TYPE(instance);
+ return tp->tp_getattro == PyObject_GenericGetAttr
+ && type_lookup_is(tp, &_Py_ID(__class__), state->object_class_descr);
+}
+
/*[clinic input]
@permit_long_summary
_abc._abc_instancecheck
@@ -623,46 +965,53 @@ _abc__abc_instancecheck_impl(PyObject *module, PyObject *self,
PyObject *instance)
/*[clinic end generated code: output=b8b5148f63b6b56f input=0bbc8da0ea346719]*/
{
- PyObject *subtype, *result = NULL, *subclass = NULL;
- _abc_data *impl = _get_impl(module, self);
- if (impl == NULL) {
- return NULL;
- }
+ _abcmodule_state *state = get_abc_state(module);
+ PyObject *subclass_owned = NULL;
+ PyObject *result = NULL;
- subclass = PyObject_GetAttr(instance, &_Py_ID(__class__));
- if (subclass == NULL) {
- Py_DECREF(impl);
- return NULL;
- }
- /* Inline the cache checking. */
- int incache = _in_weak_set(impl, &impl->_abc_cache, subclass);
- if (incache < 0) {
- goto end;
+ if (!has_default_class_attr(state, instance)) {
+ if (PyObject_GetOptionalAttr(instance, &_Py_ID(__class__),
+ &subclass_owned) < 0) {
+ return NULL;
+ }
}
- if (incache > 0) {
- result = Py_NewRef(Py_True);
- goto end;
+ // The __class__ lookup can change the type of the instance.
+ PyObject *subtype = (PyObject *)Py_TYPE(instance);
+ // subclass is either subtype, which is kept alive by instance, or
+ // subclass_owned. The fast path doesn't incref subtype to avoid
+ // refcount contention between threads.
+ /* Fall back to the type when the instance has no __class__,
+ matching the behaviour of the built-in isinstance()
+ (gh-153772). */
+ PyObject *subclass = subclass_owned != NULL ? subclass_owned : subtype;
+
+ // Fast path: cache hits don't need any locking.
+ PyThreadState *tstate = _PyThreadState_GET();
+ _PyCStackRef cref;
+ _PyThreadState_PushCStackRef(tstate, &cref);
+ _abc_data *impl = get_impl(state, self, &cref);
+ cache_result incache = CACHE_UNKNOWN;
+ if (impl != NULL) {
+ incache = lookup_caches(state, impl, subclass);
+ }
+ _PyThreadState_PopCStackRef(tstate, &cref);
+ if (impl == NULL) {
+ Py_XDECREF(subclass_owned);
+ return NULL;
}
- subtype = (PyObject *)Py_TYPE(instance);
- if (subtype == subclass) {
- if (get_cache_version(impl) == get_invalidation_counter(get_abc_state(module))) {
- incache = _in_weak_set(impl, &impl->_abc_negative_cache, subclass);
- if (incache < 0) {
- goto end;
- }
- if (incache > 0) {
- result = Py_NewRef(Py_False);
- goto end;
- }
- }
- /* Fall back to the subclass check. */
- result = PyObject_CallMethodOneArg(self, &_Py_ID(__subclasscheck__),
- subclass);
- goto end;
+ if (incache == CACHE_POSITIVE
+ || (incache == CACHE_NEGATIVE && subtype == subclass))
+ {
+ Py_XDECREF(subclass_owned);
+ return PyBool_FromLong(incache);
}
+
+ /* A subclass check can change the instance's actual type. */
+ Py_INCREF(subtype);
result = PyObject_CallMethodOneArg(self, &_Py_ID(__subclasscheck__),
subclass);
- if (result == NULL) {
+ if (result == NULL || subtype == subclass) {
+ Py_DECREF(subtype);
goto end;
}
@@ -680,234 +1029,265 @@ _abc__abc_instancecheck_impl(PyObject *module, PyObject *self,
default:
Py_UNREACHABLE();
}
+ Py_DECREF(subtype);
end:
- Py_XDECREF(impl);
- Py_XDECREF(subclass);
+ Py_XDECREF(subclass_owned);
return result;
}
-// Return -1 when exception occurred.
-// Return 1 when result is set.
-// Return 0 otherwise.
-static int subclasscheck_check_registry(_abc_data *impl, PyObject *subclass,
- PyObject **result);
-
-/*[clinic input]
-@permit_long_summary
-_abc._abc_subclasscheck
+static int subclasscheck(_abcmodule_state *state, _abc_data *impl,
+ PyObject *self, PyObject *subclass, int nested);
- self: object
- subclass: object
- /
-
-Internal ABC helper for subclasss checks. Should be never used outside abc module.
-[clinic start generated code]*/
-
-static PyObject *
-_abc__abc_subclasscheck_impl(PyObject *module, PyObject *self,
- PyObject *subclass)
-/*[clinic end generated code: output=b56c9e4a530e3894 input=5bf1ef712f5d3610]*/
+// Like PyObject_IsSubclass(subclass, cls), but doesn't add subclass to the
+// negative cache of cls if cls uses the default ABCMeta.__subclasscheck__.
+static int
+issubclass_nested(_abcmodule_state *state, PyObject *subclass, PyObject *cls)
{
- if (!PyType_Check(subclass)) {
- PyErr_SetString(PyExc_TypeError, "issubclass() arg 1 must be a class");
- return NULL;
+ assert(PyType_Check(cls));
+ if (type_lookup_is(Py_TYPE(cls), &_Py_ID(__subclasscheck__),
+ state->subclasscheck_func))
+ {
+ PyThreadState *tstate = _PyThreadState_GET();
+ _PyCStackRef cref;
+ _PyThreadState_PushCStackRef(tstate, &cref);
+ _abc_data *impl = lookup_impl(state, cls, &cref);
+ int res = -1;
+ if (impl != NULL) {
+ if (!Py_EnterRecursiveCall(" in __subclasscheck__")) {
+ res = subclasscheck(state, impl, cls, subclass, 1);
+ Py_LeaveRecursiveCall();
+ }
+ }
+ _PyThreadState_PopCStackRef(tstate, &cref);
+ if (impl != NULL) {
+ return res;
+ }
}
+ return PyObject_IsSubclass(subclass, cls);
+}
- PyObject *ok, *subclasses = NULL, *result = NULL;
- _abcmodule_state *state = NULL;
- Py_ssize_t pos;
- int incache;
- _abc_data *impl = _get_impl(module, self);
- if (impl == NULL) {
- return NULL;
+// Check if subclass is a subclass of a registered class.
+// Returns -1 on error.
+static int
+check_registry(_abcmodule_state *state, _abc_data *impl, PyObject *subclass)
+{
+ abc_table *registry = FT_ATOMIC_LOAD_PTR_ACQUIRE(impl->registry);
+ // Fast path: subclass is registered directly.
+ if (abc_table_contains(registry, subclass)) {
+ return 1;
}
-
- /* 1. Check cache. */
- incache = _in_weak_set(impl, &impl->_abc_cache, subclass);
- if (incache < 0) {
- goto end;
+ // The registry can be modified by the checks, iterate over a copy.
+ PyObject *classes;
+ Py_BEGIN_CRITICAL_SECTION(impl);
+ classes = abc_table_snapshot(impl->registry);
+ Py_END_CRITICAL_SECTION();
+ if (classes == NULL) {
+ return -1;
}
- if (incache > 0) {
- result = Py_True;
- goto end;
+ int res = 0;
+ for (Py_ssize_t i = 0; i < PyList_GET_SIZE(classes); i++) {
+ res = PyObject_IsSubclass(subclass, PyList_GET_ITEM(classes, i));
+ if (res != 0) {
+ break;
+ }
}
+ Py_DECREF(classes);
+ return res;
+}
- state = get_abc_state(module);
- /* 2. Check negative cache; may have to invalidate. */
- uint64_t invalidation_counter = get_invalidation_counter(state);
- if (get_cache_version(impl) < invalidation_counter) {
- /* Invalidate the negative cache. */
- PyObject *negative_cache;
- Py_BEGIN_CRITICAL_SECTION(impl);
- negative_cache = impl->_abc_negative_cache;
- Py_END_CRITICAL_SECTION();
- if (negative_cache != NULL && PySet_Clear(negative_cache) < 0) {
- goto end;
- }
- set_cache_version(impl, invalidation_counter);
+// Check if subclass is a subclass of a subclass of self.
+// Returns -1 on error.
+static int
+check_subclasses(_abcmodule_state *state, PyObject *self, PyObject *subclass)
+{
+ PyObject *subclasses;
+ int native = 0;
+ if (PyType_Check(self)
+ && type_lookup_is((PyTypeObject *)self, &_Py_ID(__subclasses__), NULL)
+ && type_lookup_is(Py_TYPE(self), &_Py_ID(__subclasses__),
+ state->type_subclasses))
+ {
+ // __subclasses__() is not overridden, get the subclasses directly.
+ subclasses = _PyType_GetSubclasses((PyTypeObject *)self);
+ native = 1;
}
else {
- incache = _in_weak_set(impl, &impl->_abc_negative_cache, subclass);
- if (incache < 0) {
- goto end;
+ subclasses = PyObject_CallMethodNoArgs(self, &_Py_ID(__subclasses__));
+ if (subclasses != NULL && !PyList_Check(subclasses)) {
+ PyErr_SetString(PyExc_TypeError, "__subclasses__() must return a list");
+ Py_DECREF(subclasses);
+ return -1;
+ }
+ }
+ if (subclasses == NULL) {
+ return -1;
+ }
+ int res = 0;
+ for (Py_ssize_t i = 0; i < PyList_GET_SIZE(subclasses); i++) {
+ PyObject *scls = PyList_GetItemRef(subclasses, i);
+ if (scls == NULL) {
+ res = -1;
+ break;
+ }
+ if (native) {
+ res = issubclass_nested(state, subclass, scls);
}
- if (incache > 0) {
- result = Py_False;
- goto end;
+ else {
+ res = PyObject_IsSubclass(subclass, scls);
+ }
+ Py_DECREF(scls);
+ if (res != 0) {
+ break;
}
}
+ Py_DECREF(subclasses);
+ return res;
+}
- /* 3. Check the subclass hook. */
- ok = PyObject_CallMethodOneArg(
- (PyObject *)self, &_Py_ID(__subclasshook__), subclass);
- if (ok == NULL) {
- goto end;
+// Implementation of ABCMeta.__subclasscheck__. Returns -1 on error.
+//
+// nested is set when checking the subclasses of another ABC. Negative
+// results are not cached then, otherwise every class in the hierarchy
+// would cache them which is quadratic in the number of classes.
+static int
+subclasscheck(_abcmodule_state *state, _abc_data *impl,
+ PyObject *self, PyObject *subclass, int nested)
+{
+ uint64_t counter = get_invalidation_counter(state);
+
+ /* 1. Check cache. 2. Check negative cache; may have to invalidate. */
+ validate_negative_cache(impl, counter);
+ cache_result incache = lookup_caches(state, impl, subclass);
+ if (incache != CACHE_UNKNOWN) {
+ return incache;
}
- if (ok == Py_True) {
- Py_DECREF(ok);
- if (_add_to_weak_set(impl, &impl->_abc_cache, subclass) < 0) {
- goto end;
+
+ /* 3. Check the subclass hook. */
+ // The default hook always returns NotImplemented, skip the call.
+ if (!(PyType_Check(self)
+ && type_lookup_is((PyTypeObject *)self, &_Py_ID(__subclasshook__),
+ state->object_subclasshook)
+ && type_lookup_is(Py_TYPE(self), &_Py_ID(__subclasshook__),
+ state->object_subclasshook)))
+ {
+ PyObject *ok = PyObject_CallMethodOneArg(
+ self, &_Py_ID(__subclasshook__), subclass);
+ if (ok == NULL) {
+ return -1;
}
- result = Py_True;
- goto end;
- }
- if (ok == Py_False) {
- Py_DECREF(ok);
- if (_add_to_weak_set(impl, &impl->_abc_negative_cache, subclass) < 0) {
- goto end;
+ if (ok == Py_True) {
+ goto positive;
+ }
+ if (ok == Py_False) {
+ goto negative;
+ }
+ if (ok != Py_NotImplemented) {
+ Py_DECREF(ok);
+ PyErr_SetString(PyExc_AssertionError, "__subclasshook__ must return either"
+ " False, True, or NotImplemented");
+ return -1;
}
- result = Py_False;
- goto end;
- }
- if (ok != Py_NotImplemented) {
- Py_DECREF(ok);
- PyErr_SetString(PyExc_AssertionError, "__subclasshook__ must return either"
- " False, True, or NotImplemented");
- goto end;
}
- Py_DECREF(ok);
/* 4. Check if it's a direct subclass. */
if (PyType_IsSubtype((PyTypeObject *)subclass, (PyTypeObject *)self)) {
- if (_add_to_weak_set(impl, &impl->_abc_cache, subclass) < 0) {
- goto end;
- }
- result = Py_True;
- goto end;
+ goto positive;
}
/* 5. Check if it's a subclass of a registered class (recursive). */
- if (subclasscheck_check_registry(impl, subclass, &result)) {
- // Exception occurred or result is set.
- goto end;
+ int res = check_registry(state, impl, subclass);
+ if (res < 0) {
+ return -1;
+ }
+ if (res > 0) {
+ goto positive;
}
/* 6. Check if it's a subclass of a subclass (recursive). */
- subclasses = PyObject_CallMethod(self, "__subclasses__", NULL);
- if (subclasses == NULL) {
- goto end;
- }
- if (!PyList_Check(subclasses)) {
- PyErr_SetString(PyExc_TypeError, "__subclasses__() must return a list");
- goto end;
+ res = check_subclasses(state, self, subclass);
+ if (res < 0) {
+ return -1;
}
- for (pos = 0; pos < PyList_GET_SIZE(subclasses); pos++) {
- PyObject *scls = PyList_GetItemRef(subclasses, pos);
- if (scls == NULL) {
- goto end;
- }
- int r = PyObject_IsSubclass(subclass, scls);
- Py_DECREF(scls);
- if (r > 0) {
- if (_add_to_weak_set(impl, &impl->_abc_cache, subclass) < 0) {
- goto end;
- }
- result = Py_True;
- goto end;
- }
- if (r < 0) {
- goto end;
- }
+ if (res > 0) {
+ goto positive;
}
+negative:
/* No dice; update negative cache. */
- if (_add_to_weak_set(impl, &impl->_abc_negative_cache, subclass) < 0) {
- goto end;
+ if (!nested && add_to_negative_cache(impl, subclass, counter) < 0) {
+ return -1;
}
- result = Py_False;
+ return 0;
-end:
- Py_DECREF(impl);
- Py_XDECREF(subclasses);
- return Py_XNewRef(result);
+positive:
+ if (add_to_table(impl, &impl->cache, subclass) < 0) {
+ return -1;
+ }
+ return 1;
}
+/*[clinic input]
+@permit_long_summary
+_abc._abc_subclasscheck
-static int
-subclasscheck_check_registry(_abc_data *impl, PyObject *subclass,
- PyObject **result)
+ self: object
+ subclass: object
+ /
+
+Internal ABC helper for subclasss checks. Should be never used outside abc module.
+[clinic start generated code]*/
+
+static PyObject *
+_abc__abc_subclasscheck_impl(PyObject *module, PyObject *self,
+ PyObject *subclass)
+/*[clinic end generated code: output=b56c9e4a530e3894 input=5bf1ef712f5d3610]*/
{
- // Fast path: check subclass is in weakref directly.
- int ret = _in_weak_set(impl, &impl->_abc_registry, subclass);
- if (ret < 0) {
- *result = NULL;
- return -1;
- }
- if (ret > 0) {
- *result = Py_True;
- return 1;
+ if (!PyType_Check(subclass)) {
+ PyErr_SetString(PyExc_TypeError, "issubclass() arg 1 must be a class");
+ return NULL;
}
- PyObject *registry_shared;
- Py_BEGIN_CRITICAL_SECTION(impl);
- registry_shared = impl->_abc_registry;
- Py_END_CRITICAL_SECTION();
- if (registry_shared == NULL) {
- return 0;
+ _abcmodule_state *state = get_abc_state(module);
+ PyThreadState *tstate = _PyThreadState_GET();
+ _PyCStackRef cref;
+ _PyThreadState_PushCStackRef(tstate, &cref);
+ _abc_data *impl = get_impl(state, self, &cref);
+ int res = -1;
+ if (impl != NULL) {
+ res = lookup_caches(state, impl, subclass);
+ if (res == CACHE_UNKNOWN) {
+ res = subclasscheck(state, impl, self, subclass, 0);
+ }
}
-
- // Make a local copy of the registry to protect against concurrent
- // modifications of _abc_registry.
- PyObject *registry = PyFrozenSet_New(registry_shared);
- if (registry == NULL) {
- return -1;
+ _PyThreadState_PopCStackRef(tstate, &cref);
+ if (res < 0) {
+ return NULL;
}
- PyObject *key;
- Py_ssize_t pos = 0;
- Py_hash_t hash;
+ return PyBool_FromLong(res);
+}
- while (_PySet_NextEntry(registry, &pos, &key, &hash)) {
- PyObject *rkey;
- if (PyWeakref_GetRef(key, &rkey) < 0) {
- // Someone inject non-weakref type in the registry.
- ret = -1;
- break;
- }
+/*[clinic input]
+_abc._set_subclasscheck
- if (rkey == NULL) {
- continue;
- }
- int r = PyObject_IsSubclass(subclass, rkey);
- Py_DECREF(rkey);
- if (r < 0) {
- ret = -1;
- break;
- }
- if (r > 0) {
- if (_add_to_weak_set(impl, &impl->_abc_cache, subclass) < 0) {
- ret = -1;
- break;
- }
- *result = Py_True;
- ret = 1;
- break;
- }
- }
+ func: object
+ /
- Py_DECREF(registry);
- return ret;
+Internal ABC helper to register ABCMeta.__subclasscheck__.
+
+Classes whose metaclass resolves __subclasscheck__ to func are checked
+natively when walking the subclass tree of an ABC.
+[clinic start generated code]*/
+
+static PyObject *
+_abc__set_subclasscheck(PyObject *module, PyObject *func)
+/*[clinic end generated code: output=1dc657738311dea5 input=c2e47dd519524e44]*/
+{
+ _abcmodule_state *state = get_abc_state(module);
+ // abc can be reloaded.
+ Py_XSETREF(state->subclasscheck_func, Py_NewRef(func));
+ Py_RETURN_NONE;
}
/*[clinic input]
@@ -937,9 +1317,23 @@ static struct PyMethodDef _abcmodule_methods[] = {
_ABC__ABC_REGISTER_METHODDEF
_ABC__ABC_INSTANCECHECK_METHODDEF
_ABC__ABC_SUBCLASSCHECK_METHODDEF
+ _ABC__SET_SUBCLASSCHECK_METHODDEF
{NULL, NULL} /* sentinel */
};
+static int
+get_type_dict_item(PyTypeObject *type, PyObject *name, PyObject **result)
+{
+ if (PyDict_GetItemRef(_PyType_GetDict(type), name, result) < 0) {
+ return -1;
+ }
+ if (*result == NULL) {
+ PyErr_Format(PyExc_SystemError, "%s has no %U", type->tp_name, name);
+ return -1;
+ }
+ return 0;
+}
+
static int
_abcmodule_exec(PyObject *module)
{
@@ -949,7 +1343,15 @@ _abcmodule_exec(PyObject *module)
if (state->_abc_data_type == NULL) {
return -1;
}
-
+ if (get_type_dict_item(&PyBaseObject_Type, &_Py_ID(__class__),
+ &state->object_class_descr) < 0
+ || get_type_dict_item(&PyBaseObject_Type, &_Py_ID(__subclasshook__),
+ &state->object_subclasshook) < 0
+ || get_type_dict_item(&PyType_Type, &_Py_ID(__subclasses__),
+ &state->type_subclasses) < 0)
+ {
+ return -1;
+ }
return 0;
}
@@ -958,6 +1360,10 @@ _abcmodule_traverse(PyObject *module, visitproc visit, void *arg)
{
_abcmodule_state *state = get_abc_state(module);
Py_VISIT(state->_abc_data_type);
+ Py_VISIT(state->object_class_descr);
+ Py_VISIT(state->object_subclasshook);
+ Py_VISIT(state->type_subclasses);
+ Py_VISIT(state->subclasscheck_func);
return 0;
}
@@ -966,6 +1372,10 @@ _abcmodule_clear(PyObject *module)
{
_abcmodule_state *state = get_abc_state(module);
Py_CLEAR(state->_abc_data_type);
+ Py_CLEAR(state->object_class_descr);
+ Py_CLEAR(state->object_subclasshook);
+ Py_CLEAR(state->type_subclasses);
+ Py_CLEAR(state->subclasscheck_func);
return 0;
}
diff --git a/Modules/_asynciomodule.c b/Modules/_asynciomodule.c
index bc0f7f3901e0eda..0ab7682a5404230 100644
--- a/Modules/_asynciomodule.c
+++ b/Modules/_asynciomodule.c
@@ -68,8 +68,8 @@ typedef struct TaskObj {
PyObject *task_context;
struct llist_node task_node;
#ifdef Py_GIL_DISABLED
- // thread id of the thread where this task was created
- uintptr_t task_tid;
+ // unique id of the thread state where the task was registered
+ uint64_t task_tstate_id;
#endif
} TaskObj;
@@ -769,7 +769,6 @@ future_get_result(asyncio_state *state, FutureObj *fut, PyObject **result)
return -1;
}
*result = Py_NewRef(fut->fut_exception);
- Py_CLEAR(fut->fut_exception_tb);
return 1;
}
@@ -873,6 +872,7 @@ future_cancel(asyncio_state *state, FutureObj *fut, PyObject *msg)
}
/*[clinic input]
+@vectorcall
_asyncio.Future.__init__
*
@@ -894,7 +894,7 @@ This class is *almost* compatible with concurrent.futures.Future.
static int
_asyncio_Future___init___impl(FutureObj *self, PyObject *loop)
-/*[clinic end generated code: output=9ed75799eaccb5d6 input=89af317082bc0bf8]*/
+/*[clinic end generated code: output=9ed75799eaccb5d6 input=28ff6d3b6c3aa828]*/
{
return future_init(self, loop);
@@ -1355,93 +1355,67 @@ _asyncio_Future__asyncio_awaited_by_get_impl(FutureObj *self)
/*[clinic input]
@critical_section
@getter
-_asyncio.Future._asyncio_future_blocking
+_asyncio.Future._asyncio_future_blocking -> bool
[clinic start generated code]*/
-static PyObject *
+static int
_asyncio_Future__asyncio_future_blocking_get_impl(FutureObj *self)
-/*[clinic end generated code: output=a558a2c51e38823b input=58da92efc03b617d]*/
+/*[clinic end generated code: output=32944de3df031979 input=2a51a0cf31a96826]*/
{
- if (future_is_alive(self) && self->fut_blocking) {
- Py_RETURN_TRUE;
- }
- else {
- Py_RETURN_FALSE;
- }
+ return future_is_alive(self) && self->fut_blocking;
}
/*[clinic input]
@critical_section
@setter
_asyncio.Future._asyncio_future_blocking
+ value: bool
[clinic start generated code]*/
static int
-_asyncio_Future__asyncio_future_blocking_set_impl(FutureObj *self,
- PyObject *value)
-/*[clinic end generated code: output=0686d1cb024a7453 input=3fd4a5f95df788b7]*/
-
+_asyncio_Future__asyncio_future_blocking_set_impl(FutureObj *self, int value)
+/*[clinic end generated code: output=be2d5cb1cad6dd30 input=81780cb7b89f28e1]*/
{
if (future_ensure_alive(self)) {
return -1;
}
- if (value == NULL) {
- PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
- return -1;
- }
-
- int is_true = PyObject_IsTrue(value);
- if (is_true < 0) {
- return -1;
- }
- self->fut_blocking = is_true;
+ self->fut_blocking = value;
return 0;
}
/*[clinic input]
@critical_section
@getter
-_asyncio.Future._log_traceback
+_asyncio.Future._log_traceback -> bool
[clinic start generated code]*/
-static PyObject *
+static int
_asyncio_Future__log_traceback_get_impl(FutureObj *self)
-/*[clinic end generated code: output=2724433b238593c7 input=91e5144ea4117d8e]*/
+/*[clinic end generated code: output=ba1356634182ac25 input=50f4db8eca9d1fb4]*/
{
- asyncio_state *state = get_asyncio_state_by_def((PyObject *)self);
- ENSURE_FUTURE_ALIVE(state, self)
- if (self->fut_log_tb) {
- Py_RETURN_TRUE;
- }
- else {
- Py_RETURN_FALSE;
+ if (future_ensure_alive(self)) {
+ return -1;
}
+ return self->fut_log_tb;
}
/*[clinic input]
@critical_section
@setter
_asyncio.Future._log_traceback
+ value: bool
[clinic start generated code]*/
static int
-_asyncio_Future__log_traceback_set_impl(FutureObj *self, PyObject *value)
-/*[clinic end generated code: output=9ce8e19504f42f54 input=30ac8217754b08c2]*/
+_asyncio_Future__log_traceback_set_impl(FutureObj *self, int value)
+/*[clinic end generated code: output=ad84ae67ef80e3ad input=30c0f841c945c73f]*/
{
- if (value == NULL) {
- PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
- return -1;
- }
- int is_true = PyObject_IsTrue(value);
- if (is_true < 0) {
- return -1;
- }
- if (is_true) {
+ if (value) {
PyErr_SetString(PyExc_ValueError,
"_log_traceback can only be set to False");
return -1;
}
- self->fut_log_tb = is_true;
+ self->fut_log_tb = value;
return 0;
}
/*[clinic input]
@@ -1593,10 +1567,6 @@ static int
_asyncio_Future__cancel_message_set_impl(FutureObj *self, PyObject *value)
/*[clinic end generated code: output=0854b2f77bff2209 input=f461d17f2d891fad]*/
{
- if (value == NULL) {
- PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
- return -1;
- }
Py_INCREF(value);
Py_XSETREF(self->fut_cancel_msg, value);
return 0;
@@ -1765,6 +1735,7 @@ static PyType_Slot Future_slots[] = {
{Py_tp_methods, FutureType_methods},
{Py_tp_getset, FutureType_getsetlist},
{Py_tp_init, _asyncio_Future___init__},
+ {Py_tp_vectorcall, _asyncio_Future_vectorcall},
{Py_tp_new, PyType_GenericNew},
{Py_tp_finalize, FutureObj_finalize},
@@ -1826,10 +1797,9 @@ FutureIter_dealloc(PyObject *it)
}
static PySendResult
-FutureIter_am_send_lock_held(futureiterobject *it, PyObject **result)
+FutureIter_am_send_lock_held(FutureObj *fut, PyObject **result)
{
PyObject *res;
- FutureObj *fut = it->future;
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(fut);
*result = NULL;
@@ -1860,11 +1830,24 @@ FutureIter_am_send(PyObject *op,
PyObject **result)
{
futureiterobject *it = (futureiterobject*)op;
+
+ FutureObj *fut;
+ Py_BEGIN_CRITICAL_SECTION(op);
+ fut = (FutureObj*)Py_XNewRef(it->future);
+ Py_END_CRITICAL_SECTION();
+
+ if (fut == NULL) {
+ PyErr_SetNone(PyExc_StopIteration);
+ *result = NULL;
+ return PYGEN_ERROR;
+ }
+
/* arg is unused, see the comment on FutureIter_send for clarification */
PySendResult res;
- Py_BEGIN_CRITICAL_SECTION(it->future);
- res = FutureIter_am_send_lock_held(it, result);
+ Py_BEGIN_CRITICAL_SECTION(fut);
+ res = FutureIter_am_send_lock_held(fut, result);
Py_END_CRITICAL_SECTION();
+ Py_DECREF(fut);
return res;
}
@@ -1958,7 +1941,9 @@ FutureIter_throw(PyObject *op, PyObject *const *args, Py_ssize_t nargs)
goto fail;
}
+ Py_BEGIN_CRITICAL_SECTION(self);
Py_CLEAR(self->future);
+ Py_END_CRITICAL_SECTION();
PyErr_Restore(type, val, tb);
@@ -1971,6 +1956,16 @@ FutureIter_throw(PyObject *op, PyObject *const *args, Py_ssize_t nargs)
return NULL;
}
+static PyObject *
+FutureIter_close(PyObject *self, PyObject *arg)
+{
+ futureiterobject *it = (futureiterobject*)self;
+ Py_BEGIN_CRITICAL_SECTION(self);
+ Py_CLEAR(it->future);
+ Py_END_CRITICAL_SECTION();
+ Py_RETURN_NONE;
+}
+
static int
FutureIter_clear(PyObject *op)
{
@@ -1979,13 +1974,6 @@ FutureIter_clear(PyObject *op)
return 0;
}
-static PyObject *
-FutureIter_close(PyObject *self, PyObject *arg)
-{
- (void)FutureIter_clear(self);
- Py_RETURN_NONE;
-}
-
static int
FutureIter_traverse(PyObject *op, visitproc visit, void *arg)
{
@@ -2002,6 +1990,22 @@ static PyMethodDef FutureIter_methods[] = {
{NULL, NULL} /* Sentinel */
};
+static PyObject *
+FutureIter_get_fi_future(PyObject *op, void *Py_UNUSED(closure))
+{
+ futureiterobject *it = (futureiterobject*)op;
+ PyObject *fut;
+ Py_BEGIN_CRITICAL_SECTION(op);
+ fut = it->future ? Py_NewRef(it->future) : Py_None;
+ Py_END_CRITICAL_SECTION();
+ return fut;
+}
+
+static PyGetSetDef FutureIter_getsetlist[] = {
+ {"fi_future", FutureIter_get_fi_future, NULL, NULL},
+ {NULL} /* Sentinel */
+};
+
static PyType_Slot FutureIter_slots[] = {
{Py_tp_dealloc, FutureIter_dealloc},
{Py_tp_getattro, PyObject_GenericGetAttr},
@@ -2010,6 +2014,7 @@ static PyType_Slot FutureIter_slots[] = {
{Py_tp_iter, PyObject_SelfIter},
{Py_tp_iternext, FutureIter_iternext},
{Py_tp_methods, FutureIter_methods},
+ {Py_tp_getset, FutureIter_getsetlist},
// async methods
{Py_am_send, FutureIter_am_send},
@@ -2182,6 +2187,9 @@ register_task(_PyThreadStateImpl *ts, TaskObj *task)
assert(task->task_node.prev != NULL);
return;
}
+#ifdef Py_GIL_DISABLED
+ task->task_tstate_id = ts->base.id;
+#endif
struct llist_node *head = &ts->asyncio_tasks_head;
llist_insert_tail(head, &task->task_node);
}
@@ -2201,15 +2209,15 @@ static void
unregister_task(TaskObj *task)
{
#ifdef Py_GIL_DISABLED
- // check if we are in the same thread
- // if so, we can avoid locking
- if (task->task_tid == _Py_ThreadId()) {
+ PyThreadState *tstate = _PyThreadState_GET();
+ // The task can only be on this thread's list if this thread state
+ // registered it, in which case no locking is needed.
+ if (task->task_tstate_id == tstate->id) {
unregister_task_safe(task);
}
else {
- // we are in a different thread
- // stop the world then check and remove the task
- PyThreadState *tstate = _PyThreadState_GET();
+ // The task is on another thread's list or on the interpreter's
+ // list of lingering tasks: stop the world to remove it.
_PyEval_StopTheWorld(tstate->interp);
unregister_task_safe(task);
_PyEval_StartTheWorld(tstate->interp);
@@ -2284,6 +2292,7 @@ swap_current_task(_PyThreadStateImpl *ts, PyObject *loop, PyObject *task)
/* ----- Task */
/*[clinic input]
+@vectorcall
_asyncio.Task.__init__
coro: object
@@ -2300,7 +2309,7 @@ static int
_asyncio_Task___init___impl(TaskObj *self, PyObject *coro, PyObject *loop,
PyObject *name, PyObject *context,
int eager_start)
-/*[clinic end generated code: output=7aced2d27836f1a1 input=18e3f113a51b829d]*/
+/*[clinic end generated code: output=7aced2d27836f1a1 input=de87c52b0800ab4b]*/
{
if (future_init((FutureObj*)self, loop)) {
return -1;
@@ -2325,14 +2334,18 @@ _asyncio_Task___init___impl(TaskObj *self, PyObject *coro, PyObject *loop,
if (self->task_context == NULL) {
return -1;
}
+ } else if (!PyContext_CheckExact(context)) {
+ // gh-157301: the passed value must be a contextvars.Context
+ self->task_log_destroy_pending = 0;
+ PyErr_Format(PyExc_TypeError,
+ "a contextvars.Context was expected, got %T",
+ context);
+ return -1;
} else {
Py_XSETREF(self->task_context, Py_NewRef(context));
}
Py_CLEAR(self->task_fut_waiter);
-#ifdef Py_GIL_DISABLED
- self->task_tid = _Py_ThreadId();
-#endif
self->task_must_cancel = 0;
self->task_log_destroy_pending = 1;
self->task_num_cancels_requested = 0;
@@ -2364,7 +2377,9 @@ _asyncio_Task___init___impl(TaskObj *self, PyObject *coro, PyObject *loop,
_PyObject_SetMaybeWeakref((PyObject *)self);
#endif
if (eager_start) {
- PyObject *res = PyObject_CallMethodNoArgs(loop, &_Py_ID(is_running));
+ // gh-154695: loop may be None here, future_init() resolved it into task_loop.
+ PyObject *res = PyObject_CallMethodNoArgs(self->task_loop,
+ &_Py_ID(is_running));
if (res == NULL) {
return -1;
}
@@ -2424,40 +2439,28 @@ TaskObj_traverse(PyObject *op, visitproc visit, void *arg)
/*[clinic input]
@critical_section
@getter
-_asyncio.Task._log_destroy_pending
+_asyncio.Task._log_destroy_pending -> bool
[clinic start generated code]*/
-static PyObject *
+static int
_asyncio_Task__log_destroy_pending_get_impl(TaskObj *self)
-/*[clinic end generated code: output=e6c2a47d029ac93b input=17127298cd4c720b]*/
+/*[clinic end generated code: output=98b5f7bad24a2381 input=a87002bdf72e380b]*/
{
- if (self->task_log_destroy_pending) {
- Py_RETURN_TRUE;
- }
- else {
- Py_RETURN_FALSE;
- }
+ return self->task_log_destroy_pending;
}
/*[clinic input]
@critical_section
@setter
_asyncio.Task._log_destroy_pending
+ value: bool
[clinic start generated code]*/
static int
-_asyncio_Task__log_destroy_pending_set_impl(TaskObj *self, PyObject *value)
-/*[clinic end generated code: output=7ebc030bb92ec5ce input=49b759c97d1216a4]*/
+_asyncio_Task__log_destroy_pending_set_impl(TaskObj *self, int value)
+/*[clinic end generated code: output=132bbf2b4c627777 input=533fea7776daa075]*/
{
- if (value == NULL) {
- PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
- return -1;
- }
- int is_true = PyObject_IsTrue(value);
- if (is_true < 0) {
- return -1;
- }
- self->task_log_destroy_pending = is_true;
+ self->task_log_destroy_pending = value;
return 0;
}
@@ -2785,7 +2788,11 @@ static PyObject *
_asyncio_Task_get_context_impl(TaskObj *self)
/*[clinic end generated code: output=6996f53d3dc01aef input=87c0b209b8fceeeb]*/
{
- return Py_NewRef(self->task_context);
+ if (self->task_context) {
+ return Py_NewRef(self->task_context);
+ }
+
+ Py_RETURN_NONE;
}
/*[clinic input]
@@ -2799,7 +2806,12 @@ _asyncio_Task_get_name_impl(TaskObj *self)
{
if (self->task_name) {
if (PyLong_CheckExact(self->task_name)) {
- PyObject *name = PyUnicode_FromFormat("Task-%S", self->task_name);
+ // Formatting can run arbitrary code (e.g. a GC finalizer that logs
+ // and re-enters get_name()), which may replace self->task_name.
+ // Hold a strong reference to the counter while formatting it.
+ PyObject *counter = Py_NewRef(self->task_name);
+ PyObject *name = PyUnicode_FromFormat("Task-%S", counter);
+ Py_DECREF(counter);
if (name == NULL) {
return NULL;
}
@@ -2943,6 +2955,7 @@ static PyType_Slot Task_slots[] = {
{Py_tp_methods, TaskType_methods},
{Py_tp_getset, TaskType_getsetlist},
{Py_tp_init, _asyncio_Task___init__},
+ {Py_tp_vectorcall, _asyncio_Task_vectorcall},
{Py_tp_new, PyType_GenericNew},
{Py_tp_finalize, TaskObj_finalize},
@@ -2966,13 +2979,17 @@ TaskObj_dealloc(PyObject *self)
if (PyObject_CallFinalizerFromDealloc(self) < 0) {
return; // resurrected
}
+ // Untrack the object before unregistering the task, since the
+ // latter can cause a stop-the-world pause, after which another
+ // thread might call the GC and reach the object while it is
+ // semi-deallocated but still tracked
+ PyObject_GC_UnTrack(self);
+
// unregister the task after finalization so that
// if the task gets resurrected, it remains registered
unregister_task((TaskObj *)self);
PyTypeObject *tp = Py_TYPE(self);
- PyObject_GC_UnTrack(self);
-
PyObject_ClearWeakRefs(self);
(void)TaskObj_clear(self);
@@ -3058,8 +3075,13 @@ task_step_impl(asyncio_state *state, TaskObj *task, PyObject *exc)
if (task->task_must_cancel) {
assert(exc != Py_None);
- if (!exc || !PyErr_GivenExceptionMatches(exc, state->asyncio_CancelledError)) {
- /* exc was not a CancelledError */
+ /* Replace exc with a CancelledError unless it already is one, or
+ it is SystemExit/KeyboardInterrupt, which must propagate
+ unchanged (gh-108549). */
+ if (!exc ||
+ (!PyErr_GivenExceptionMatches(exc, state->asyncio_CancelledError) &&
+ !PyErr_GivenExceptionMatches(exc, PyExc_KeyboardInterrupt) &&
+ !PyErr_GivenExceptionMatches(exc, PyExc_SystemExit))) {
exc = create_cancelled_error(state, (FutureObj*)task);
if (!exc) {
@@ -3460,24 +3482,49 @@ task_eager_start(_PyThreadStateImpl *ts, asyncio_state *state, TaskObj *task)
// it will continue as a regular (non-eager) asyncio task
register_task(ts, task);
+ assert(PyContext_CheckExact(task->task_context));
if (_PyContext_Enter(&ts->base, task->task_context) == -1) {
+ // gh-157301: a failed enter must not leave the task current and registered
+ task->task_log_destroy_pending = 0;
+ PyObject *curtask = swap_current_task(ts, task->task_loop, prevtask);
+ Py_XDECREF(curtask);
+ unregister_task(task);
Py_DECREF(prevtask);
return -1;
}
int retval = 0;
+ // gh-157299: the eager step must record the awaited_by edge
+ int eager_edge = TaskOrFuture_Check(state, prevtask);
PyObject *stepres;
Py_BEGIN_CRITICAL_SECTION(task);
- stepres = task_step_impl(state, task, NULL);
- Py_END_CRITICAL_SECTION();
+ if (eager_edge &&
+ future_awaited_by_add(state, (FutureObj *)task, prevtask) < 0)
+ {
+ eager_edge = 0;
+ task->task_log_destroy_pending = 0;
+ unregister_task(task);
+ stepres = NULL;
+ }
+ else {
+ stepres = task_step_impl(state, task, NULL);
+ }
+
+ PyObject *exc = stepres == NULL ? PyErr_GetRaisedException() : NULL;
+ if (eager_edge) {
+ int res = future_awaited_by_discard(state, (FutureObj *)task, prevtask);
+ if (res) {
+ retval = -1;
+ }
+ }
if (stepres == NULL) {
- PyObject *exc = PyErr_GetRaisedException();
_PyErr_ChainExceptions1(exc);
retval = -1;
} else {
Py_DECREF(stepres);
}
+ Py_END_CRITICAL_SECTION();
PyObject *curtask = swap_current_task(ts, task->task_loop, prevtask);
Py_DECREF(prevtask);
@@ -3963,7 +4010,6 @@ add_tasks_llist(struct llist_node *head, PyListObject *tasks)
struct llist_node *node;
llist_for_each_safe(node, head) {
TaskObj *task = llist_data(node, TaskObj, task_node);
- assert(task->task_state == STATE_PENDING);
// The linked list holds borrowed references to task
// as such it is possible that the task is concurrently
// deallocated while added to this list.
@@ -4172,6 +4218,23 @@ _asyncio_future_discard_from_awaited_by_impl(PyObject *module, PyObject *fut,
Py_RETURN_NONE;
}
+/*[clinic input]
+_asyncio._clear_caches
+
+Clear internal caches. Used for internal tests.
+[clinic start generated code]*/
+
+static PyObject *
+_asyncio__clear_caches_impl(PyObject *module)
+/*[clinic end generated code: output=9691a293f83d4303 input=6e1ae31e51dc906c]*/
+{
+ asyncio_state *state = get_asyncio_state(module);
+ if (PySet_Clear(state->iscoroutine_typecache) < 0) {
+ return NULL;
+ }
+ Py_RETURN_NONE;
+}
+
static int
module_traverse(PyObject *mod, visitproc visit, void *arg)
{
@@ -4343,6 +4406,7 @@ static PyMethodDef asyncio_methods[] = {
_ASYNCIO_ALL_TASKS_METHODDEF
_ASYNCIO_FUTURE_ADD_TO_AWAITED_BY_METHODDEF
_ASYNCIO_FUTURE_DISCARD_FROM_AWAITED_BY_METHODDEF
+ _ASYNCIO__CLEAR_CACHES_METHODDEF
{NULL, NULL}
};
diff --git a/Modules/_bz2module.c b/Modules/_bz2module.c
index 9db3ac39da52099..e0d85b78741a91e 100644
--- a/Modules/_bz2module.c
+++ b/Modules/_bz2module.c
@@ -747,6 +747,61 @@ static PyType_Spec bz2_decompressor_type_spec = {
.slots = bz2_decompressor_type_slots,
};
+
+PyDoc_STRVAR(bzlib_version_info__doc__,
+"_bz2.bzlib_version_info\n\
+\n\
+Bzlib version information as a named tuple.");
+
+static PyStructSequence_Field bzlib_version_info_fields[] = {
+ {"major", "Major release number"},
+ {"minor", "Minor release number"},
+ {"patch", "Patch release number"},
+ {0}
+};
+
+static PyStructSequence_Desc bzlib_version_info_desc = {
+ "_bz2.bzlib_version_info", /* name */
+ bzlib_version_info__doc__, /* doc */
+ bzlib_version_info_fields, /* fields */
+ 3
+};
+
+/* BZ2_bzlibVersion() returns a string with a trailing suffix, for example
+ "1.0.8, 13-Jul-2019" for bzip2 or "1.1.0-libbz2-rs-sys-0.2.5" for
+ libbz2-rs. sscanf() stops at the suffix; components which were not
+ parsed are left zero. This is deliberate -- a zero is more useful
+ here than a hard error. */
+static PyObject *
+make_bzlib_version_info(PyTypeObject *type, const char *string)
+{
+ PyObject *version;
+ int pos = 0;
+ unsigned int major = 0, minor = 0, patch = 0;
+
+ sscanf(string, "%u.%u.%u", &major, &minor, &patch);
+
+ version = PyStructSequence_New(type);
+ if (version == NULL) {
+ return NULL;
+ }
+
+#define SetIntItem(VALUE) \
+ PyStructSequence_SET_ITEM(version, pos++, PyLong_FromUnsignedLong(VALUE)); \
+ if (PyErr_Occurred()) { \
+ Py_DECREF(version); \
+ return NULL; \
+ }
+
+ SetIntItem(major)
+ SetIntItem(minor)
+ SetIntItem(patch)
+#undef SetIntItem
+
+ return version;
+}
+
+
/* Module initialization. */
static int
@@ -771,6 +826,24 @@ _bz2_exec(PyObject *module)
return -1;
}
+ /* bzlib_version */
+ if (PyModule_Add(module, "bzlib_version",
+ PyUnicode_FromString(BZ2_bzlibVersion())) < 0)
+ {
+ return -1;
+ }
+ PyTypeObject *version_type;
+ version_type = PyStructSequence_NewType(&bzlib_version_info_desc);
+ if (version_type == NULL) {
+ return -1;
+ }
+ if (PyModule_Add(module, "bzlib_version_info",
+ make_bzlib_version_info(version_type, BZ2_bzlibVersion())) < 0)
+ {
+ Py_DECREF(version_type);
+ return -1;
+ }
+ Py_DECREF(version_type);
return 0;
}
diff --git a/Modules/_codecsmodule.c b/Modules/_codecsmodule.c
index 7cba234fc80b591..dd0ace58cf42fdb 100644
--- a/Modules/_codecsmodule.c
+++ b/Modules/_codecsmodule.c
@@ -642,7 +642,7 @@ _codecs_code_page_decode_impl(PyObject *module, int codepage,
#endif /* MS_WINDOWS */
-#ifdef HAVE_ICONV
+#ifdef _Py_HAVE_ICONV
/*[clinic input]
_codecs.iconv_decode
@@ -665,7 +665,7 @@ _codecs_iconv_decode_impl(PyObject *module, const char *encoding,
return codec_tuple(decoded, consumed);
}
-#endif /* HAVE_ICONV */
+#endif /* _Py_HAVE_ICONV */
/* --- Encoder ------------------------------------------------------------ */
@@ -977,7 +977,7 @@ _codecs_code_page_encode_impl(PyObject *module, int code_page, PyObject *str,
#endif /* MS_WINDOWS */
-#ifdef HAVE_ICONV
+#ifdef _Py_HAVE_ICONV
/*[clinic input]
_codecs.iconv_encode
@@ -996,7 +996,7 @@ _codecs_iconv_encode_impl(PyObject *module, const char *encoding,
PyUnicode_GET_LENGTH(str));
}
-#endif /* HAVE_ICONV */
+#endif /* _Py_HAVE_ICONV */
/* --- Error handler registry --------------------------------------------- */
diff --git a/Modules/_collectionsmodule.c b/Modules/_collectionsmodule.c
index 62d1dad5735ec8e..c63dc0661bd69e7 100644
--- a/Modules/_collectionsmodule.c
+++ b/Modules/_collectionsmodule.c
@@ -1,6 +1,7 @@
#include "Python.h"
#include "pycore_call.h" // _PyObject_CallNoArgs()
-#include "pycore_dict.h" // _PyDict_GetItem_KnownHash()
+#include "pycore_critical_section.h" // _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED()
+#include "pycore_dict.h" // _PyDict_GetItemRef_KnownHash_LockHeld()
#include "pycore_long.h" // _PyLong_GetZero()
#include "pycore_moduleobject.h" // _PyModule_GetState()
#include "pycore_pyatomic_ft_wrappers.h"
@@ -648,7 +649,7 @@ deque_copy_impl(dequeobject *deque)
result = PyObject_CallOneArg((PyObject *)(Py_TYPE(deque)),
(PyObject *)deque);
else
- result = PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
+ result = PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "On",
deque, old_deque->maxlen, NULL);
if (result != NULL && !PyObject_TypeCheck(result, state->deque_type)) {
PyErr_Format(PyExc_TypeError,
@@ -674,8 +675,18 @@ deque___copy___impl(dequeobject *deque)
return deque_copy_impl(deque);
}
+/*[clinic input]
+@critical_section
+_collections.deque.__add__ as deque_concat
+
+ deque: dequeobject
+ other: object
+ /
+[clinic start generated code]*/
+
static PyObject *
-deque_concat_lock_held(dequeobject *deque, PyObject *other)
+deque_concat_impl(dequeobject *deque, PyObject *other)
+/*[clinic end generated code: output=fa6c28f7752f0b28 input=1816c51a4c6c4f05]*/
{
PyObject *new_deque, *result;
int rv;
@@ -706,17 +717,6 @@ deque_concat_lock_held(dequeobject *deque, PyObject *other)
return new_deque;
}
-static PyObject *
-deque_concat(PyObject *self, PyObject *other)
-{
- dequeobject *deque = dequeobject_CAST(self);
- PyObject *result;
- Py_BEGIN_CRITICAL_SECTION(deque);
- result = deque_concat_lock_held(deque, other);
- Py_END_CRITICAL_SECTION();
- return result;
-}
-
static int
deque_clear(PyObject *self)
{
@@ -819,8 +819,18 @@ deque_clearmethod_impl(dequeobject *deque)
Py_RETURN_NONE;
}
+/*[clinic input]
+@critical_section
+_collections.deque.__imul__ as deque_inplace_repeat
+
+ deque: dequeobject
+ n: Py_ssize_t
+ /
+[clinic start generated code]*/
+
static PyObject *
-deque_inplace_repeat_lock_held(dequeobject *deque, Py_ssize_t n)
+deque_inplace_repeat_impl(dequeobject *deque, Py_ssize_t n)
+/*[clinic end generated code: output=e9052495a8eb46f9 input=0ebbaedad03b8abf]*/
{
Py_ssize_t i, m, size;
PyObject *seq;
@@ -896,17 +906,6 @@ deque_inplace_repeat_lock_held(dequeobject *deque, Py_ssize_t n)
return (PyObject *)deque;
}
-static PyObject *
-deque_inplace_repeat(PyObject *self, Py_ssize_t n)
-{
- dequeobject *deque = dequeobject_CAST(self);
- PyObject *result;
- Py_BEGIN_CRITICAL_SECTION(deque);
- result = deque_inplace_repeat_lock_held(deque, n);
- Py_END_CRITICAL_SECTION();
- return result;
-}
-
static PyObject *
deque_repeat(PyObject *self, Py_ssize_t n)
{
@@ -921,7 +920,7 @@ deque_repeat(PyObject *self, Py_ssize_t n)
return NULL;
// It's safe to not acquire the per-object lock for new_deque; it's
// invisible to other threads.
- rv = deque_inplace_repeat_lock_held(new_deque, n);
+ rv = deque_inplace_repeat_impl(new_deque, n);
Py_DECREF(new_deque);
return rv;
}
@@ -1192,8 +1191,17 @@ deque_count_impl(dequeobject *deque, PyObject *v)
return PyLong_FromSsize_t(count);
}
+/*[clinic input]
+@critical_section
+_collections.deque.__contains__ as deque_contains
+ deque: dequeobject
+ v: object
+ /
+[clinic start generated code]*/
+
static int
-deque_contains_lock_held(dequeobject *deque, PyObject *v)
+deque_contains_impl(dequeobject *deque, PyObject *v)
+/*[clinic end generated code: output=5e7718757d3063bf input=8dd115a2cdaf0f23]*/
{
block *b = deque->leftblock;
Py_ssize_t index = deque->leftindex;
@@ -1224,17 +1232,6 @@ deque_contains_lock_held(dequeobject *deque, PyObject *v)
return 0;
}
-static int
-deque_contains(PyObject *self, PyObject *v)
-{
- dequeobject *deque = dequeobject_CAST(self);
- int result;
- Py_BEGIN_CRITICAL_SECTION(deque);
- result = deque_contains_lock_held(deque, v);
- Py_END_CRITICAL_SECTION();
- return result;
-}
-
static Py_ssize_t
deque_len(PyObject *self)
{
@@ -1380,8 +1377,17 @@ valid_index(Py_ssize_t i, Py_ssize_t limit)
return (size_t) i < (size_t) limit;
}
+/*[clinic input]
+@critical_section
+_collections.deque.__getitem__ as deque_item
+ deque: dequeobject
+ i: Py_ssize_t
+ /
+[clinic start generated code]*/
+
static PyObject *
-deque_item_lock_held(dequeobject *deque, Py_ssize_t i)
+deque_item_impl(dequeobject *deque, Py_ssize_t i)
+/*[clinic end generated code: output=52e62af1427d61ef input=89f14f06b29122a1]*/
{
block *b;
PyObject *item;
@@ -1419,17 +1425,6 @@ deque_item_lock_held(dequeobject *deque, Py_ssize_t i)
return Py_NewRef(item);
}
-static PyObject *
-deque_item(PyObject *self, Py_ssize_t i)
-{
- dequeobject *deque = dequeobject_CAST(self);
- PyObject *result;
- Py_BEGIN_CRITICAL_SECTION(deque);
- result = deque_item_lock_held(deque, i);
- Py_END_CRITICAL_SECTION();
- return result;
-}
-
static int
deque_del_item(dequeobject *deque, Py_ssize_t i)
{
@@ -1499,8 +1494,19 @@ deque_remove_impl(dequeobject *deque, PyObject *value)
Py_RETURN_NONE;
}
+/*[clinic input]
+@critical_section
+_collections.deque.__setitem__ as deque_ass_item
+
+ deque: dequeobject
+ i: Py_ssize_t
+ v: object
+ /
+[clinic start generated code]*/
+
static int
-deque_ass_item_lock_held(dequeobject *deque, Py_ssize_t i, PyObject *v)
+deque_ass_item_impl(dequeobject *deque, Py_ssize_t i, PyObject *v)
+/*[clinic end generated code: output=28739a830dc69ab1 input=b767e1a4972fa537]*/
{
block *b;
Py_ssize_t n, len=Py_SIZE(deque), halflen=(len+1)>>1, index=i;
@@ -1531,17 +1537,6 @@ deque_ass_item_lock_held(dequeobject *deque, Py_ssize_t i, PyObject *v)
return 0;
}
-static int
-deque_ass_item(PyObject *self, Py_ssize_t i, PyObject *v)
-{
- dequeobject *deque = dequeobject_CAST(self);
- int result;
- Py_BEGIN_CRITICAL_SECTION(deque);
- result = deque_ass_item_lock_held(deque, i, v);
- Py_END_CRITICAL_SECTION();
- return result;
-}
-
static void
deque_dealloc(PyObject *self)
{
@@ -2531,6 +2526,66 @@ static PyType_Spec defdict_spec = {
/* helper function for Counter *********************************************/
+/* Fast path advantages:
+ 1. Eliminate double hashing
+ (by re-using the same hash for both the get and set)
+ 2. Avoid argument overhead of PyObject_CallFunctionObjArgs
+ (argument tuple creation and parsing)
+ 3. Avoid indirection through a bound method object
+ (creates another argument tuple)
+ 4. Avoid initial increment from zero
+ (reuse an existing one-object instead)
+*/
+static int
+_count_elements_dict_lock_held(PyDictObject *mapping, PyObject *it)
+{
+ _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(mapping);
+ PyObject *one = _PyLong_GetOne(); // borrowed reference
+
+ while (1) {
+ Py_hash_t hash;
+ PyObject *oldval;
+ int status;
+
+ PyObject *key = PyIter_Next(it);
+ if (key == NULL) {
+ return PyErr_Occurred() ? -1 : 0;
+ }
+
+ hash = _PyObject_HashDictKey(key);
+ if (hash == -1) {
+ Py_DECREF(key);
+ return -1;
+ }
+
+ int found = _PyDict_GetItemRef_KnownHash_LockHeld(mapping, key, hash,
+ &oldval);
+ if (found < 0) {
+ Py_DECREF(key);
+ return -1;
+ }
+ if (found == 0) {
+ status = _PyDict_SetItem_KnownHash_LockHeld(mapping, key, one,
+ hash);
+ }
+ else {
+ PyObject *newval = PyNumber_Add(oldval, one);
+ Py_DECREF(oldval);
+ if (newval == NULL) {
+ Py_DECREF(key);
+ return -1;
+ }
+ status = _PyDict_SetItem_KnownHash_LockHeld(mapping, key, newval,
+ hash);
+ Py_DECREF(newval);
+ }
+ Py_DECREF(key);
+ if (status < 0) {
+ return -1;
+ }
+ }
+}
+
/*[clinic input]
_collections._count_elements
@@ -2547,7 +2602,6 @@ _collections__count_elements_impl(PyObject *module, PyObject *mapping,
/*[clinic end generated code: output=7e0c1789636b3d8f input=e79fad04534a0b45]*/
{
PyObject *it, *oldval;
- PyObject *newval = NULL;
PyObject *key = NULL;
PyObject *bound_get = NULL;
PyObject *mapping_get;
@@ -2572,48 +2626,12 @@ _collections__count_elements_impl(PyObject *module, PyObject *mapping,
mapping_setitem != NULL && mapping_setitem == dict_setitem &&
PyDict_Check(mapping))
{
- while (1) {
- /* Fast path advantages:
- 1. Eliminate double hashing
- (by re-using the same hash for both the get and set)
- 2. Avoid argument overhead of PyObject_CallFunctionObjArgs
- (argument tuple creation and parsing)
- 3. Avoid indirection through a bound method object
- (creates another argument tuple)
- 4. Avoid initial increment from zero
- (reuse an existing one-object instead)
- */
- Py_hash_t hash;
-
- key = PyIter_Next(it);
- if (key == NULL)
- break;
-
- hash = _PyObject_HashDictKey(key);
- if (hash == -1) {
- goto done;
- }
-
- oldval = _PyDict_GetItem_KnownHash(mapping, key, hash);
- if (oldval == NULL) {
- if (PyErr_Occurred())
- goto done;
- if (_PyDict_SetItem_KnownHash(mapping, key, one, hash) < 0)
- goto done;
- } else {
- /* oldval is a borrowed reference. Keep it alive across
- PyNumber_Add(), which can execute arbitrary user code and
- mutate (or even clear) the underlying dict. */
- Py_INCREF(oldval);
- newval = PyNumber_Add(oldval, one);
- Py_DECREF(oldval);
- if (newval == NULL)
- goto done;
- if (_PyDict_SetItem_KnownHash(mapping, key, newval, hash) < 0)
- goto done;
- Py_CLEAR(newval);
- }
- Py_DECREF(key);
+ int status;
+ Py_BEGIN_CRITICAL_SECTION(mapping);
+ status = _count_elements_dict_lock_held((PyDictObject *)mapping, it);
+ Py_END_CRITICAL_SECTION();
+ if (status < 0) {
+ goto done;
}
}
else {
@@ -2629,6 +2647,7 @@ _collections__count_elements_impl(PyObject *module, PyObject *mapping,
oldval = PyObject_CallFunctionObjArgs(bound_get, key, zero, NULL);
if (oldval == NULL)
break;
+ PyObject *newval;
if (oldval == zero) {
newval = Py_NewRef(one);
} else {
@@ -2637,9 +2656,10 @@ _collections__count_elements_impl(PyObject *module, PyObject *mapping,
Py_DECREF(oldval);
if (newval == NULL)
break;
- if (PyObject_SetItem(mapping, key, newval) < 0)
+ int status = PyObject_SetItem(mapping, key, newval);
+ Py_DECREF(newval);
+ if (status < 0)
break;
- Py_CLEAR(newval);
Py_DECREF(key);
}
}
@@ -2649,7 +2669,6 @@ _collections__count_elements_impl(PyObject *module, PyObject *mapping,
Py_XDECREF(mapping_setitem);
Py_DECREF(it);
Py_XDECREF(key);
- Py_XDECREF(newval);
Py_XDECREF(bound_get);
if (PyErr_Occurred())
return NULL;
diff --git a/Modules/_csv.c b/Modules/_csv.c
index a7fcc78e058f058..484f7bc0f9d2d49 100644
--- a/Modules/_csv.c
+++ b/Modules/_csv.c
@@ -21,10 +21,10 @@ module instead.
/*[clinic input]
module _csv
+class _csv.Dialect "DialectObj *" "clinic_state()->dialect_type"
+class _csv.Reader "ReaderObj *" "clinic_state()->reader_type"
[clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=385118b71aa43706]*/
-
-#include "clinic/_csv.c.h"
+/*[clinic end generated code: output=da39a3ee5e6b4b0d input=7bdf66dc7d68ed90]*/
#define NOT_SET ((Py_UCS4)-1)
#define EOL ((Py_UCS4)-2)
@@ -117,7 +117,12 @@ typedef struct {
Py_UCS4 quotechar; /* quote character */
Py_UCS4 escapechar; /* escape character */
PyObject *lineterminator; /* string to write between records */
-
+ /* Cache for the writer: bit c is set if the ASCII character c needs
+ quoting or escaping (delimiter, quotechar, escapechar, '\r', '\n'
+ and the characters of lineterminator). */
+ uint64_t special_chars[2];
+ /* Whether any of the special characters is non-ASCII. */
+ bool nonascii_special;
} DialectObj;
typedef struct {
@@ -155,6 +160,8 @@ typedef struct {
#define _ReaderObj_CAST(op) ((ReaderObj *)(op))
#define _WriterObj_CAST(op) ((WriterObj *)(op))
+#include "clinic/_csv.c.h"
+
/*
* DIALECT class
*/
@@ -332,6 +339,54 @@ _set_str(const char *name, PyObject **target, PyObject *src, const char *dflt)
return 0;
}
+static void
+dialect_add_special_char(DialectObj *self, Py_UCS4 c)
+{
+ if (c == NOT_SET) {
+ return;
+ }
+ if (c < 128) {
+ self->special_chars[c / 64] |= (uint64_t)1 << (c % 64);
+ }
+ else {
+ self->nonascii_special = true;
+ }
+}
+
+static void
+dialect_init_special_chars_cache(DialectObj *self)
+{
+ self->special_chars[0] = self->special_chars[1] = 0;
+ self->nonascii_special = false;
+ dialect_add_special_char(self, self->delimiter);
+ dialect_add_special_char(self, self->quotechar);
+ dialect_add_special_char(self, self->escapechar);
+ dialect_add_special_char(self, '\r');
+ dialect_add_special_char(self, '\n');
+ PyObject *lt = self->lineterminator;
+ for (Py_ssize_t i = 0; i < PyUnicode_GET_LENGTH(lt); i++) {
+ dialect_add_special_char(self, PyUnicode_READ_CHAR(lt, i));
+ }
+}
+
+/* Whether the character needs quoting or escaping by the writer. */
+static inline bool
+dialect_is_special_char(DialectObj *self, Py_UCS4 c)
+{
+ if (c < 128) {
+ return (self->special_chars[c / 64] >> (c % 64)) & 1;
+ }
+ if (!self->nonascii_special) {
+ return false;
+ }
+ return (c == self->delimiter ||
+ c == self->quotechar ||
+ c == self->escapechar ||
+ PyUnicode_FindChar(self->lineterminator, c, 0,
+ PyUnicode_GET_LENGTH(self->lineterminator),
+ 1) >= 0);
+}
+
static int
dialect_check_quoting(int quoting)
{
@@ -558,6 +613,7 @@ dialect_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
{
goto err;
}
+ dialect_init_special_chars_cache(self);
ret = Py_NewRef(self);
err:
@@ -577,18 +633,62 @@ dialect_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
/* Since dialect is now a heap type, it inherits pickling method for
* protocol 0 and 1 from object, therefore it needs to be overridden */
-PyDoc_STRVAR(dialect_reduce_doc, "raises an exception to avoid pickling");
+/*[clinic input]
+_csv.Dialect.__reduce__
+
+Raise an exception to avoid pickling.
+[clinic start generated code]*/
static PyObject *
-Dialect_reduce(PyObject *self, PyObject *args) {
+_csv_Dialect___reduce___impl(DialectObj *self)
+/*[clinic end generated code: output=f728b34af509ed69 input=e46419b46279e480]*/
+{
PyErr_Format(PyExc_TypeError,
"cannot pickle '%.100s' instances", _PyType_Name(Py_TYPE(self)));
return NULL;
}
+/*[clinic input]
+_csv.Dialect.__reduce_ex__
+
+ protocol: object
+ /
+
+Raise an exception to avoid pickling.
+[clinic start generated code]*/
+
+static PyObject *
+_csv_Dialect___reduce_ex___impl(DialectObj *self, PyObject *protocol)
+/*[clinic end generated code: output=d45dec397da6575a input=c6ebd579e8959040]*/
+{
+ return _csv_Dialect___reduce___impl(self);
+}
+
+/*[clinic input]
+_csv.Dialect.__replace__
+
+ **changes: dict
+
+Return a copy of the dialect with the specified options replaced.
+[clinic start generated code]*/
+
+static PyObject *
+_csv_Dialect___replace___impl(DialectObj *self, PyObject *changes)
+/*[clinic end generated code: output=8f692c2c63a61b50 input=154beb565fbabd4c]*/
+{
+ PyObject *newargs = PyTuple_Pack(1, self);
+ if (newargs == NULL) {
+ return NULL;
+ }
+ PyObject *result = dialect_new(Py_TYPE(self), newargs, changes);
+ Py_DECREF(newargs);
+ return result;
+}
+
static struct PyMethodDef dialect_methods[] = {
- {"__reduce__", Dialect_reduce, METH_VARARGS, dialect_reduce_doc},
- {"__reduce_ex__", Dialect_reduce, METH_VARARGS, dialect_reduce_doc},
+ _CSV_DIALECT___REDUCE___METHODDEF
+ _CSV_DIALECT___REDUCE_EX___METHODDEF
+ _CSV_DIALECT___REPLACE___METHODDEF
{NULL, NULL}
};
@@ -921,11 +1021,15 @@ parse_reset(ReaderObj *self)
return 0;
}
+/*[clinic input]
+@critical_section
+_csv.Reader.__next__ as Reader_iternext
+[clinic start generated code]*/
+
static PyObject *
-Reader_iternext_lock_held(PyObject *op)
+Reader_iternext_impl(ReaderObj *self)
+/*[clinic end generated code: output=3a02b0254a76e1fc input=97c70a4e2fe621e4]*/
{
- ReaderObj *self = _ReaderObj_CAST(op);
-
PyObject *fields = NULL;
Py_UCS4 c;
Py_ssize_t pos, linelen;
@@ -995,16 +1099,6 @@ Reader_iternext_lock_held(PyObject *op)
return fields;
}
-static PyObject *
-Reader_iternext(PyObject *op)
-{
- PyObject *result;
- Py_BEGIN_CRITICAL_SECTION(op);
- result = Reader_iternext_lock_held(op);
- Py_END_CRITICAL_SECTION();
- return result;
-}
-
static void
Reader_dealloc(PyObject *op)
{
@@ -1083,10 +1177,31 @@ PyType_Spec Reader_Type_spec = {
};
+/*[clinic input]
+_csv.reader
+
+ iterable: object
+ dialect: object(c_default='NULL') = 'excel'
+ /
+ **fmtparams: dict
+
+Return a reader object that will process lines from the given iterable.
+
+The "iterable" argument can be any object that returns a line
+of input for each iteration, such as a file object or a list. The
+optional "dialect" argument defines a CSV dialect. The function
+also accepts optional keyword arguments which override settings
+provided by the dialect.
+
+The returned object is an iterator. Each iteration returns a row
+of the CSV file (which can span multiple input lines).
+[clinic start generated code]*/
+
static PyObject *
-csv_reader(PyObject *module, PyObject *args, PyObject *keyword_args)
+_csv_reader_impl(PyObject *module, PyObject *iterable, PyObject *dialect,
+ PyObject *fmtparams)
+/*[clinic end generated code: output=c7033323f4e82fae input=330c6d58878e33b7]*/
{
- PyObject * iterator, * dialect = NULL;
_csvstate *module_state = get_csv_state(module);
ReaderObj * self = PyObject_GC_New(
ReaderObj,
@@ -1107,17 +1222,13 @@ csv_reader(PyObject *module, PyObject *args, PyObject *keyword_args)
return NULL;
}
- if (!PyArg_UnpackTuple(args, "reader", 1, 2, &iterator, &dialect)) {
- Py_DECREF(self);
- return NULL;
- }
- self->input_iter = PyObject_GetIter(iterator);
+ self->input_iter = PyObject_GetIter(iterable);
if (self->input_iter == NULL) {
Py_DECREF(self);
return NULL;
}
self->dialect = (DialectObj *)_call_dialect(module_state, dialect,
- keyword_args);
+ fmtparams);
if (self->dialect == NULL) {
Py_DECREF(self);
return NULL;
@@ -1183,14 +1294,7 @@ join_append_data(WriterObj *self, int field_kind, const void *field_data,
Py_UCS4 c = PyUnicode_READ(field_kind, field_data, i);
int want_escape = 0;
- if (c == dialect->delimiter ||
- c == dialect->escapechar ||
- c == dialect->quotechar ||
- c == '\n' ||
- c == '\r' ||
- PyUnicode_FindChar(
- dialect->lineterminator, c, 0,
- PyUnicode_GET_LENGTH(dialect->lineterminator), 1) >= 0) {
+ if (dialect_is_special_char(dialect, c)) {
if (dialect->quoting == QUOTE_NONE)
want_escape = 1;
else {
@@ -1552,10 +1656,27 @@ PyType_Spec Writer_Type_spec = {
};
+/*[clinic input]
+_csv.writer
+
+ fileobj as output_file: object
+ dialect: object(c_default='NULL') = 'excel'
+ /
+ **fmtparams: dict
+
+Return a writer object writing user data to the given file object.
+
+The "fileobj" argument can be any object that supports the file API.
+The optional "dialect" argument defines a CSV dialect. The function
+also accepts optional keyword arguments which override settings
+provided by the dialect.
+[clinic start generated code]*/
+
static PyObject *
-csv_writer(PyObject *module, PyObject *args, PyObject *keyword_args)
+_csv_writer_impl(PyObject *module, PyObject *output_file, PyObject *dialect,
+ PyObject *fmtparams)
+/*[clinic end generated code: output=3f57919e03cca475 input=18d396d2aa8138f0]*/
{
- PyObject * output_file, * dialect = NULL;
_csvstate *module_state = get_csv_state(module);
WriterObj * self = PyObject_GC_New(WriterObj, module_state->writer_type);
@@ -1572,10 +1693,6 @@ csv_writer(PyObject *module, PyObject *args, PyObject *keyword_args)
self->error_obj = Py_NewRef(module_state->error_obj);
- if (!PyArg_UnpackTuple(args, "writer", 1, 2, &output_file, &dialect)) {
- Py_DECREF(self);
- return NULL;
- }
if (PyObject_GetOptionalAttr(output_file,
module_state->str_write,
&self->write) < 0) {
@@ -1589,7 +1706,7 @@ csv_writer(PyObject *module, PyObject *args, PyObject *keyword_args)
return NULL;
}
self->dialect = (DialectObj *)_call_dialect(module_state, dialect,
- keyword_args);
+ fmtparams);
if (self->dialect == NULL) {
Py_DECREF(self);
return NULL;
@@ -1615,21 +1732,36 @@ _csv_list_dialects_impl(PyObject *module)
return PyDict_Keys(get_csv_state(module)->dialects);
}
+/*[clinic input]
+_csv.register_dialect
+
+ name as name_obj: object
+ dialect as dialect_obj: object(c_default='NULL') = 'excel'
+ /
+ **fmtparams: dict
+
+Create a mapping from a string name to a CVS dialect.
+
+The optional "dialect" argument specifies the base dialect instance
+or the name of the registered dialect. The function also accepts
+optional keyword arguments which override settings provided by the
+dialect.
+[clinic start generated code]*/
+
static PyObject *
-csv_register_dialect(PyObject *module, PyObject *args, PyObject *kwargs)
+_csv_register_dialect_impl(PyObject *module, PyObject *name_obj,
+ PyObject *dialect_obj, PyObject *fmtparams)
+/*[clinic end generated code: output=b00b54de5b950472 input=64e9180e18d88a97]*/
{
- PyObject *name_obj, *dialect_obj = NULL;
_csvstate *module_state = get_csv_state(module);
PyObject *dialect;
- if (!PyArg_UnpackTuple(args, "register_dialect", 1, 2, &name_obj, &dialect_obj))
- return NULL;
if (!PyUnicode_Check(name_obj)) {
PyErr_SetString(PyExc_TypeError,
"dialect name must be a string");
return NULL;
}
- dialect = _call_dialect(module_state, dialect_obj, kwargs);
+ dialect = _call_dialect(module_state, dialect_obj, fmtparams);
if (dialect == NULL)
return NULL;
if (PyDict_SetItem(module_state->dialects, name_obj, dialect) < 0) {
@@ -1728,47 +1860,10 @@ PyType_Spec error_spec = {
PyDoc_STRVAR(csv_module_doc, "CSV parsing and writing.\n");
-PyDoc_STRVAR(csv_reader_doc,
-"reader($module, iterable, /, dialect='excel', **fmtparams)\n"
-"--\n\n"
-"Return a reader object that will process lines from the given iterable.\n"
-"\n"
-"The \"iterable\" argument can be any object that returns a line\n"
-"of input for each iteration, such as a file object or a list. The\n"
-"optional \"dialect\" argument defines a CSV dialect. The function\n"
-"also accepts optional keyword arguments which override settings\n"
-"provided by the dialect.\n"
-"\n"
-"The returned object is an iterator. Each iteration returns a row\n"
-"of the CSV file (which can span multiple input lines).\n");
-
-PyDoc_STRVAR(csv_writer_doc,
-"writer($module, fileobj, /, dialect='excel', **fmtparams)\n"
-"--\n\n"
-"Return a writer object that will write user data on the given file object.\n"
-"\n"
-"The \"fileobj\" argument can be any object that supports the file API.\n"
-"The optional \"dialect\" argument defines a CSV dialect. The function\n"
-"also accepts optional keyword arguments which override settings\n"
-"provided by the dialect.\n");
-
-PyDoc_STRVAR(csv_register_dialect_doc,
-"register_dialect($module, name, /, dialect='excel', **fmtparams)\n"
-"--\n\n"
-"Create a mapping from a string name to a CVS dialect.\n"
-"\n"
-"The optional \"dialect\" argument specifies the base dialect instance\n"
-"or the name of the registered dialect. The function also accepts\n"
-"optional keyword arguments which override settings provided by the\n"
-"dialect.\n");
-
static struct PyMethodDef csv_methods[] = {
- { "reader", _PyCFunction_CAST(csv_reader),
- METH_VARARGS | METH_KEYWORDS, csv_reader_doc},
- { "writer", _PyCFunction_CAST(csv_writer),
- METH_VARARGS | METH_KEYWORDS, csv_writer_doc},
- { "register_dialect", _PyCFunction_CAST(csv_register_dialect),
- METH_VARARGS | METH_KEYWORDS, csv_register_dialect_doc},
+ _CSV_READER_METHODDEF
+ _CSV_WRITER_METHODDEF
+ _CSV_REGISTER_DIALECT_METHODDEF
_CSV_LIST_DIALECTS_METHODDEF
_CSV_UNREGISTER_DIALECT_METHODDEF
_CSV_GET_DIALECT_METHODDEF
diff --git a/Modules/_ctypes/_ctypes.c b/Modules/_ctypes/_ctypes.c
index adfdf44e53604e3..301c28d2eb21154 100644
--- a/Modules/_ctypes/_ctypes.c
+++ b/Modules/_ctypes/_ctypes.c
@@ -186,7 +186,23 @@ _DictRemover_call(PyObject *myself, PyObject *args, PyObject *kw)
{
DictRemoverObject *self = _DictRemoverObject_CAST(myself);
if (self->key && self->dict) {
- if (-1 == PyDict_DelItem(self->dict, self->key)) {
+ /* Only remove the entry if it is still the proxy that died: the
+ key may have been reused for a new object in the meantime. */
+ PyObject *proxy = PyTuple_GET_SIZE(args) == 1
+ ? PyTuple_GET_ITEM(args, 0) : NULL;
+ PyObject *current;
+ int rc;
+ Py_BEGIN_CRITICAL_SECTION(self->dict);
+ rc = PyDict_GetItemRef(self->dict, self->key, ¤t);
+ if (rc == 1) {
+ rc = 0;
+ if (current == proxy) {
+ rc = PyDict_DelItem(self->dict, self->key);
+ }
+ Py_DECREF(current);
+ }
+ Py_END_CRITICAL_SECTION();
+ if (rc < 0) {
PyErr_FormatUnraisable("Exception ignored while "
"calling _ctypes.DictRemover");
}
@@ -215,32 +231,72 @@ static PyType_Spec dictremover_spec = {
.slots = dictremover_slots,
};
-int
-PyDict_SetItemProxy(ctypes_state *st, PyObject *dict, PyObject *key, PyObject *item)
+/* Cache `item` in `dict` under `key` through a weakref proxy, unless a live
+ entry already exists. On success *presult is a new reference to whatever
+ is cached for `key` afterwards: `item` itself, or the object another
+ thread cached first.
+ Returns 0 on success, -1 with an exception set on failure. */
+static int
+_PyDict_SetDefaultItemProxy(ctypes_state *st, PyObject *dict, PyObject *key,
+ PyObject *item, PyObject **presult)
{
- PyObject *obj;
- DictRemoverObject *remover;
- PyObject *proxy;
- int result;
-
- obj = _PyObject_CallNoArgs((PyObject *)st->DictRemover_Type);
- if (obj == NULL)
+ PyObject *obj = _PyObject_CallNoArgs((PyObject *)st->DictRemover_Type);
+ if (obj == NULL) {
return -1;
+ }
- remover = (DictRemoverObject *)obj;
+ DictRemoverObject *remover = (DictRemoverObject *)obj;
assert(remover->key == NULL);
assert(remover->dict == NULL);
remover->key = Py_NewRef(key);
remover->dict = Py_NewRef(dict);
- proxy = PyWeakref_NewProxy(item, obj);
+ PyObject *proxy = PyWeakref_NewProxy(item, obj);
Py_DECREF(obj);
- if (proxy == NULL)
+ if (proxy == NULL) {
+ return -1;
+ }
+
+ PyObject *stored;
+ int present = PyDict_SetDefaultRef(dict, key, proxy, &stored);
+ if (present < 0) {
+ Py_DECREF(proxy);
return -1;
+ }
+ if (present == 0) {
+ /* Our proxy was inserted; `item` is the canonical object. */
+ Py_DECREF(stored);
+ Py_DECREF(proxy);
+ *presult = Py_NewRef(item);
+ return 0;
+ }
- result = PyDict_SetItem(dict, key, proxy);
+ /* Another thread cached an object for this key first. Prefer it, so that
+ every caller gets the same object. */
+ PyObject *existing = NULL;
+ int rc = 0;
+ if (PyWeakref_CheckProxy(stored)) {
+ rc = PyWeakref_GetRef(stored, &existing);
+ }
+ Py_DECREF(stored);
+ if (rc < 0) {
+ Py_DECREF(proxy);
+ return -1;
+ }
+ if (existing != NULL) {
+ Py_DECREF(proxy);
+ *presult = existing;
+ return 0;
+ }
+
+ /* The cached entry had already been cleared; install ours instead. */
+ rc = PyDict_SetItem(dict, key, proxy);
Py_DECREF(proxy);
- return result;
+ if (rc < 0) {
+ return -1;
+ }
+ *presult = Py_NewRef(item);
+ return 0;
}
static int
@@ -598,13 +654,13 @@ _ctypes_CType_Type___pointer_type___get_impl(PyObject *self)
/*[clinic input]
@setter
+@deleter
_ctypes.CType_Type.__pointer_type__
-
[clinic start generated code]*/
static int
_ctypes_CType_Type___pointer_type___set_impl(PyObject *self, PyObject *value)
-/*[clinic end generated code: output=6259be8ea21693fa input=a05055fc7f4714b6]*/
+/*[clinic end generated code: output=6259be8ea21693fa input=07e8b7a8fcc1efc1]*/
{
ctypes_state *st = get_module_state_by_def(Py_TYPE(self));
StgInfo *info;
@@ -1436,6 +1492,21 @@ PyCPointerType_from_param_impl(PyObject *type, PyTypeObject *cls,
return Py_NewRef(value);
}
}
+
+ PyObject *as_parameter;
+ if (PyObject_GetOptionalAttr(value, &_Py_ID(_as_parameter_), &as_parameter) < 0) {
+ return NULL;
+ }
+ if (as_parameter) {
+ if (_Py_EnterRecursiveCall(" while processing _as_parameter_")) {
+ Py_DECREF(as_parameter);
+ return NULL;
+ }
+ value = PyCPointerType_from_param_impl(type, cls, as_parameter);
+ Py_DECREF(as_parameter);
+ _Py_LeaveRecursiveCall();
+ return value;
+ }
return CDataType_from_param_impl(type, cls, value);
}
@@ -1481,37 +1552,20 @@ class _ctypes.PyCArrayType_Type "CDataObject *" "clinic_state()->PyCArrayType_Ty
@critical_section
@setter
_ctypes.PyCArrayType_Type.raw
+ value: Py_buffer
[clinic start generated code]*/
static int
-_ctypes_PyCArrayType_Type_raw_set_impl(CDataObject *self, PyObject *value)
-/*[clinic end generated code: output=cf9b2a9fd92e9ecb input=a3717561efc45efd]*/
+_ctypes_PyCArrayType_Type_raw_set_impl(CDataObject *self, Py_buffer *value)
+/*[clinic end generated code: output=273e537dc31f4bbd input=90775c9408b1bb59]*/
{
- char *ptr;
- Py_ssize_t size;
- Py_buffer view;
-
- if (value == NULL) {
- PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
- return -1;
- }
- if (PyObject_GetBuffer(value, &view, PyBUF_SIMPLE) < 0)
- return -1;
- size = view.len;
- ptr = view.buf;
- if (size > self->b_size) {
+ if (value->len > self->b_size) {
PyErr_SetString(PyExc_ValueError,
"byte string too long");
- goto fail;
+ return -1;
}
-
- memcpy(self->b_ptr, ptr, size);
-
- PyBuffer_Release(&view);
+ memcpy(self->b_ptr, value->buf, value->len);
return 0;
- fail:
- PyBuffer_Release(&view);
- return -1;
}
/*[clinic input]
@@ -1551,42 +1605,24 @@ _ctypes_PyCArrayType_Type_value_get_impl(CDataObject *self)
@critical_section
@setter
_ctypes.PyCArrayType_Type.value
+ value: object(subclass_of='&PyBytes_Type', type='PyBytesObject *')
[clinic start generated code]*/
static int
-_ctypes_PyCArrayType_Type_value_set_impl(CDataObject *self, PyObject *value)
-/*[clinic end generated code: output=39ad655636a28dd5 input=e2e6385fc6ab1a29]*/
+_ctypes_PyCArrayType_Type_value_set_impl(CDataObject *self,
+ PyBytesObject *value)
+/*[clinic end generated code: output=21cbd436230dc33e input=47d40501c4ecae23]*/
{
- const char *ptr;
- Py_ssize_t size;
-
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "can't delete attribute");
- return -1;
- }
-
- if (!PyBytes_Check(value)) {
- PyErr_Format(PyExc_TypeError,
- "bytes expected instead of %s instance",
- Py_TYPE(value)->tp_name);
- return -1;
- } else
- Py_INCREF(value);
- size = PyBytes_GET_SIZE(value);
+ Py_ssize_t size = PyBytes_GET_SIZE(value);
if (size > self->b_size) {
PyErr_SetString(PyExc_ValueError,
"byte string too long");
- Py_DECREF(value);
return -1;
}
- ptr = PyBytes_AS_STRING(value);
- memcpy(self->b_ptr, ptr, size);
+ memcpy(self->b_ptr, PyBytes_AS_STRING(value), size);
if (size < self->b_size)
self->b_ptr[size] = '\0';
- Py_DECREF(value);
-
return 0;
}
@@ -2337,7 +2373,7 @@ PyCSimpleType_paramfunc(ctypes_state *st, CDataObject *self)
parg->tag = fd->code;
parg->pffi_type = fd->pffi_type;
parg->obj = Py_NewRef(self);
- memcpy(&parg->value, self->b_ptr, self->b_size);
+ memcpy(&parg->value, self->b_ptr, info->size);
return parg;
}
@@ -2499,22 +2535,30 @@ PyCSimpleType_init(PyObject *self, PyObject *args, PyObject *kwds)
}
assert(sw_info);
#ifdef WORDS_BIGENDIAN
- PyObject_SetAttrString(self, "__ctype_le__", swapped);
- PyObject_SetAttrString(self, "__ctype_be__", self);
- PyObject_SetAttrString(swapped, "__ctype_be__", self);
- PyObject_SetAttrString(swapped, "__ctype_le__", swapped);
+ if (PyObject_SetAttrString(self, "__ctype_le__", swapped) < 0 ||
+ PyObject_SetAttrString(self, "__ctype_be__", self) < 0 ||
+ PyObject_SetAttrString(swapped, "__ctype_be__", self) < 0 ||
+ PyObject_SetAttrString(swapped, "__ctype_le__", swapped) < 0)
+ {
+ Py_DECREF(swapped);
+ return -1;
+ }
/* We are creating the type for the OTHER endian */
sw_info->format = _ctypes_alloc_format_string("<", stginfo->format+1);
#else
- PyObject_SetAttrString(self, "__ctype_be__", swapped);
- PyObject_SetAttrString(self, "__ctype_le__", self);
- PyObject_SetAttrString(swapped, "__ctype_le__", self);
- PyObject_SetAttrString(swapped, "__ctype_be__", swapped);
+ if (PyObject_SetAttrString(self, "__ctype_be__", swapped) < 0 ||
+ PyObject_SetAttrString(self, "__ctype_le__", self) < 0 ||
+ PyObject_SetAttrString(swapped, "__ctype_le__", self) < 0 ||
+ PyObject_SetAttrString(swapped, "__ctype_be__", swapped) < 0)
+ {
+ Py_DECREF(swapped);
+ return -1;
+ }
/* We are creating the type for the OTHER endian */
sw_info->format = _ctypes_alloc_format_string(">", stginfo->format+1);
#endif
Py_DECREF(swapped);
- if (PyErr_Occurred()) {
+ if (sw_info->format == NULL) {
return -1;
}
};
@@ -2900,28 +2944,33 @@ static PyType_Spec pycfuncptr_type_spec = {
* Code to keep needed objects alive
*/
+static CDataObject *
+PyCData_GetContainer_lock_held(CDataObject *root)
+{
+ assert(root->b_base == NULL);
+ _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(root);
+ if (root->b_objects == NULL) {
+ if (root->b_length) {
+ root->b_objects = PyDict_New();
+ if (root->b_objects == NULL) {
+ return NULL;
+ }
+ } else {
+ root->b_objects = Py_NewRef(Py_None);
+ }
+ }
+ return root;
+}
+
static CDataObject *
PyCData_GetContainer(CDataObject *self)
{
while (self->b_base) {
self = self->b_base;
}
- CDataObject *res = self;
+ CDataObject *res;
Py_BEGIN_CRITICAL_SECTION(self);
- // avoid using return directly in this block because critical section
- // needs to be released before returning
- if (self->b_objects == NULL) {
- if (self->b_length) {
- self->b_objects = PyDict_New();
- if (self->b_objects == NULL) {
- res = NULL;
- goto exit;
- }
- } else {
- self->b_objects = Py_NewRef(Py_None);
- }
- }
-exit:;
+ res = PyCData_GetContainer_lock_held(self);
Py_END_CRITICAL_SECTION();
return res;
}
@@ -2936,6 +2985,22 @@ GetKeepedObjects(CDataObject *target)
return container->b_objects;
}
+/* Like GetKeepedObjects(), for a caller that already holds target's lock. */
+static PyObject *
+GetKeepedObjects_lock_held(CDataObject *target)
+{
+ CDataObject *container;
+ if (target->b_base == NULL) {
+ container = PyCData_GetContainer_lock_held(target);
+ }
+ else {
+ container = PyCData_GetContainer(target);
+ }
+ if (container == NULL)
+ return NULL;
+ return container->b_objects;
+}
+
static PyObject *
unique_key(CDataObject *target, Py_ssize_t index)
{
@@ -2972,7 +3037,15 @@ KeepRef_lock_held(CDataObject *target, Py_ssize_t index, PyObject *keep)
Py_DECREF(Py_None);
return 0;
}
- ob = PyCData_GetContainer(target);
+ if (target->b_base == NULL) {
+ // target is its own root and the caller already holds its lock:
+ // re-entering the critical section would be a nested same-object
+ // lock (failed CAS + slow path) on every field assignment.
+ ob = PyCData_GetContainer_lock_held(target);
+ }
+ else {
+ ob = PyCData_GetContainer(target);
+ }
if (ob == NULL) {
Py_DECREF(keep);
return -1;
@@ -3140,16 +3213,6 @@ PyCData_NewGetBuffer(PyObject *myself, Py_buffer *view, int flags)
return 0;
}
-/*
- * CData objects are mutable, so they cannot be hashable!
- */
-static Py_hash_t
-PyCData_nohash(PyObject *self)
-{
- PyErr_SetString(PyExc_TypeError, "unhashable type");
- return -1;
-}
-
/*[clinic input]
@critical_section
_ctypes.PyCData.__reduce__
@@ -3246,25 +3309,42 @@ static PyMethodDef PyCData_methods[] = {
{ NULL, NULL },
};
-static PyType_Slot pycdata_slots[] = {
- {Py_tp_dealloc, PyCData_dealloc},
- {Py_tp_hash, PyCData_nohash},
- {Py_tp_doc, PyDoc_STR("XXX to be provided")},
- {Py_tp_traverse, PyCData_traverse},
- {Py_tp_clear, PyCData_clear},
- {Py_tp_methods, PyCData_methods},
- {Py_tp_members, PyCData_members},
- {Py_bf_getbuffer, PyCData_NewGetBuffer},
- {0, NULL},
-};
-
-static PyType_Spec pycdata_spec = {
- .name = "_ctypes._CData",
- .basicsize = sizeof(CDataObject),
- .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION),
- .slots = pycdata_slots,
-};
+/*
+ * CData objects are mutable, so they cannot be hashable. Setting tp_hash to
+ * PyObject_HashNotImplemented() makes type_ready() set __hash__ to None.
+ *
+ * Unfortunately, on Windows, PyObject_HashNotImplemented is imported from
+ * the Python DLL. MSVC resolves imported functions in static initializers to
+ * local thunks, and Clang does the same even for local aggregate initializers.
+ * Assign the hash slot explicitly at runtime to load the real address from
+ * the import table.
+ */
+static PyObject *
+PyCData_create_type(PyObject *mod)
+{
+ PyType_Slot slots[] = {
+ {Py_tp_dealloc, PyCData_dealloc},
+ {Py_tp_hash, NULL},
+ {Py_tp_doc, PyDoc_STR("The common base class of all ctypes "
+ "data types.")},
+ {Py_tp_traverse, PyCData_traverse},
+ {Py_tp_clear, PyCData_clear},
+ {Py_tp_methods, PyCData_methods},
+ {Py_tp_members, PyCData_members},
+ {Py_bf_getbuffer, PyCData_NewGetBuffer},
+ {0, NULL},
+ };
+ slots[1].pfunc = PyObject_HashNotImplemented;
+ PyType_Spec spec = {
+ .name = "_ctypes._CData",
+ .basicsize = sizeof(CDataObject),
+ .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
+ Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE |
+ Py_TPFLAGS_DISALLOW_INSTANTIATION),
+ .slots = slots,
+ };
+ return PyType_FromMetaclass(NULL, mod, &spec, NULL);
+}
static int
PyCData_MallocBuffer(CDataObject *obj, StgInfo *info)
@@ -3569,7 +3649,7 @@ PyCData_set(ctypes_state *st,
/* KeepRef steals a refcount from it's last argument */
/* If KeepRef fails, we are stumped. The dst memory block has already
been changed */
- return KeepRef(mem, index, result);
+ return KeepRef_lock_held(mem, index, result);
}
@@ -3664,12 +3744,13 @@ _validate_paramflags(ctypes_state *st, PyTypeObject *type, PyObject *paramflags,
/*[clinic input]
@critical_section
@setter
+@deleter
_ctypes.CFuncPtr.errcheck
[clinic start generated code]*/
static int
_ctypes_CFuncPtr_errcheck_set_impl(PyCFuncPtrObject *self, PyObject *value)
-/*[clinic end generated code: output=6580cf1ffdf3b9fb input=84930bb16c490b33]*/
+/*[clinic end generated code: output=6580cf1ffdf3b9fb input=bcd5d3ed1a0c36e9]*/
{
if (value && !PyCallable_Check(value)) {
PyErr_SetString(PyExc_TypeError,
@@ -3701,13 +3782,14 @@ _ctypes_CFuncPtr_errcheck_get_impl(PyCFuncPtrObject *self)
/*[clinic input]
@setter
+@deleter
@critical_section
_ctypes.CFuncPtr.restype
[clinic start generated code]*/
static int
_ctypes_CFuncPtr_restype_set_impl(PyCFuncPtrObject *self, PyObject *value)
-/*[clinic end generated code: output=0be0a086abbabf18 input=683c3bef4562ccc6]*/
+/*[clinic end generated code: output=0be0a086abbabf18 input=ffc941a26dbb31f3]*/
{
PyObject *checker;
if (value == NULL) {
@@ -3764,13 +3846,14 @@ _ctypes_CFuncPtr_restype_get_impl(PyCFuncPtrObject *self)
/*[clinic input]
@setter
+@deleter
@critical_section
_ctypes.CFuncPtr.argtypes
[clinic start generated code]*/
static int
_ctypes_CFuncPtr_argtypes_set_impl(PyCFuncPtrObject *self, PyObject *value)
-/*[clinic end generated code: output=596a36e2ae89d7d1 input=c4627573e980aa8b]*/
+/*[clinic end generated code: output=596a36e2ae89d7d1 input=fd012f1fd7cc35be]*/
{
if (value == NULL || value == Py_None) {
atomic_xsetref(&self->argtypes, NULL);
@@ -4993,6 +5076,12 @@ static PyType_Spec pycunion_spec = {
/*
PyCArray_Type
*/
+
+/*[clinic input]
+class _ctypes.Array "PyObject *" "clinic_state()->PyCArray_Type"
+[clinic start generated code]*/
+/*[clinic end generated code: output=da39a3ee5e6b4b0d input=b2d780e2e2dc6e8a]*/
+
static int
Array_init(PyObject *self, PyObject *args, PyObject *kw)
{
@@ -5005,6 +5094,22 @@ Array_init(PyObject *self, PyObject *args, PyObject *kw)
return -1;
}
n = PyTuple_GET_SIZE(args);
+
+ /* Optimization: If the type doesn't override __setitem__, we can store the
+ * items directly (see gh-72113). */
+ PyMappingMethods *mp = Py_TYPE(self)->tp_as_mapping;
+ if (mp != NULL && mp->mp_ass_subscript == Array_ass_subscript) {
+ int result = 0;
+ Py_BEGIN_CRITICAL_SECTION(self);
+ for (i = 0; result >= 0 && i < n; ++i) {
+ PyObject *v = PyTuple_GET_ITEM(args, i);
+ assert(v != NULL);
+ result = Array_ass_item_impl(self, i, v);
+ }
+ Py_END_CRITICAL_SECTION();
+ return result;
+ }
+
for (i = 0; i < n; ++i) {
PyObject *v;
v = PyTuple_GET_ITEM(args, i);
@@ -5014,8 +5119,17 @@ Array_init(PyObject *self, PyObject *args, PyObject *kw)
return 0;
}
+/*[clinic input]
+@critical_section
+_ctypes.Array.__getitem__ as Array_item
+ myself: self
+ index: Py_ssize_t
+ /
+[clinic start generated code]*/
+
static PyObject *
-Array_item_lock_held(PyObject *myself, Py_ssize_t index)
+Array_item_impl(PyObject *myself, Py_ssize_t index)
+/*[clinic end generated code: output=d038162d727d7d9b input=68fa9889c77bb8c9]*/
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(myself);
@@ -5044,18 +5158,17 @@ Array_item_lock_held(PyObject *myself, Py_ssize_t index)
index, size, self->b_ptr + offset);
}
-static PyObject *
-Array_item(PyObject *myself, Py_ssize_t index)
-{
- PyObject *result;
- Py_BEGIN_CRITICAL_SECTION(myself);
- result = Array_item_lock_held(myself, index);
- Py_END_CRITICAL_SECTION();
- return result;
-}
+/*[clinic input]
+@critical_section
+_ctypes.Array.__getitem__ as Array_subscript
+ myself: self
+ item: object
+ /
+[clinic start generated code]*/
static PyObject *
-Array_subscript_lock_held(PyObject *myself, PyObject *item)
+Array_subscript_impl(PyObject *myself, PyObject *item)
+/*[clinic end generated code: output=5c88d612ad5c8a1a input=510935495a857cac]*/
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(myself);
@@ -5068,7 +5181,7 @@ Array_subscript_lock_held(PyObject *myself, PyObject *item)
return NULL;
if (i < 0)
i += self->b_length;
- return Array_item_lock_held(myself, i);
+ return Array_item_impl(myself, i);
}
else if (PySlice_Check(item)) {
PyObject *proto;
@@ -5097,7 +5210,6 @@ Array_subscript_lock_held(PyObject *myself, PyObject *item)
if (iteminfo->getfunc == _ctypes_get_fielddesc("c")->getfunc) {
char *ptr = (char *)self->b_ptr;
- char *dest;
if (slicelen <= 0)
return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
@@ -5107,19 +5219,17 @@ Array_subscript_lock_held(PyObject *myself, PyObject *item)
slicelen);
return res;
}
- dest = (char *)PyMem_Malloc(slicelen);
-
- if (dest == NULL)
- return PyErr_NoMemory();
-
+ PyBytesWriter *writer = PyBytesWriter_Create(slicelen);
+ if (writer == NULL) {
+ return NULL;
+ }
+ char *dest = PyBytesWriter_GetData(writer);
for (cur = start, i = 0; i < slicelen;
cur += step, i++) {
dest[i] = ptr[cur];
}
- np = PyBytes_FromStringAndSize(dest, slicelen);
- PyMem_Free(dest);
- return np;
+ return PyBytesWriter_Finish(writer);
}
if (iteminfo->getfunc == _ctypes_get_fielddesc("u")->getfunc) {
wchar_t *ptr = (wchar_t *)self->b_ptr;
@@ -5156,7 +5266,7 @@ Array_subscript_lock_held(PyObject *myself, PyObject *item)
for (cur = start, i = 0; i < slicelen;
cur += step, i++) {
- PyObject *v = Array_item_lock_held(myself, cur);
+ PyObject *v = Array_item_impl(myself, cur);
if (v == NULL) {
Py_DECREF(np);
return NULL;
@@ -5173,18 +5283,19 @@ Array_subscript_lock_held(PyObject *myself, PyObject *item)
}
-static PyObject *
-Array_subscript(PyObject *myself, PyObject *item)
-{
- PyObject *result;
- Py_BEGIN_CRITICAL_SECTION(myself);
- result = Array_subscript_lock_held(myself, item);
- Py_END_CRITICAL_SECTION();
- return result;
-}
+/*[clinic input]
+@critical_section
+_ctypes.Array.__setitem__ as Array_ass_item
+
+ myself: self
+ index: Py_ssize_t
+ value: object
+ /
+[clinic start generated code]*/
static int
-Array_ass_item_lock_held(PyObject *myself, Py_ssize_t index, PyObject *value)
+Array_ass_item_impl(PyObject *myself, Py_ssize_t index, PyObject *value)
+/*[clinic end generated code: output=8fb1fd51b5b45da8 input=8b6ddb53d6377b96]*/
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(myself);
@@ -5218,19 +5329,19 @@ Array_ass_item_lock_held(PyObject *myself, Py_ssize_t index, PyObject *value)
index, size, ptr);
}
-static int
-Array_ass_item(PyObject *myself, Py_ssize_t index, PyObject *value)
-{
- int result;
- Py_BEGIN_CRITICAL_SECTION(myself);
- result = Array_ass_item_lock_held(myself, index, value);
- Py_END_CRITICAL_SECTION();
- return result;
-}
+/*[clinic input]
+@critical_section
+_ctypes.Array.__setitem__ as Array_ass_subscript
+ myself: self
+ item: object
+ value: object
+ /
+[clinic start generated code]*/
static int
-Array_ass_subscript_lock_held(PyObject *myself, PyObject *item, PyObject *value)
+Array_ass_subscript_impl(PyObject *myself, PyObject *item, PyObject *value)
+/*[clinic end generated code: output=cb9a138e4e40c5ac input=4b7aedebbb357853]*/
{
CDataObject *self = _CDataObject_CAST(myself);
@@ -5247,7 +5358,7 @@ Array_ass_subscript_lock_held(PyObject *myself, PyObject *item, PyObject *value)
return -1;
if (i < 0)
i += self->b_length;
- return Array_ass_item_lock_held(myself, i, value);
+ return Array_ass_item_impl(myself, i, value);
}
else if (PySlice_Check(item)) {
Py_ssize_t start, stop, step, slicelen, otherlen, i;
@@ -5262,6 +5373,9 @@ Array_ass_subscript_lock_held(PyObject *myself, PyObject *item, PyObject *value)
stop = start;
otherlen = PySequence_Length(value);
+ if (otherlen < 0) {
+ return -1;
+ }
if (otherlen != slicelen) {
PyErr_SetString(PyExc_ValueError,
"Can only assign sequence of same size");
@@ -5272,7 +5386,7 @@ Array_ass_subscript_lock_held(PyObject *myself, PyObject *item, PyObject *value)
int result;
if (item == NULL)
return -1;
- result = Array_ass_item_lock_held(myself, cur, item);
+ result = Array_ass_item_impl(myself, cur, item);
Py_DECREF(item);
if (result == -1)
return -1;
@@ -5286,17 +5400,6 @@ Array_ass_subscript_lock_held(PyObject *myself, PyObject *item, PyObject *value)
}
}
-static int
-Array_ass_subscript(PyObject *myself, PyObject *item, PyObject *value)
-{
- int result;
- Py_BEGIN_CRITICAL_SECTION(myself);
- result = Array_ass_subscript_lock_held(myself, item, value);
- Py_END_CRITICAL_SECTION();
- return result;
-}
-
-
static Py_ssize_t
Array_length(PyObject *myself)
{
@@ -5390,13 +5493,20 @@ PyCArrayType_from_ctype(ctypes_state *st, PyObject *itemtype, Py_ssize_t length)
Py_DECREF(key);
return NULL;
}
- if (PyDict_SetItemProxy(st, st->array_cache, key, result) < 0) {
+ PyObject *cached;
+ int rc;
+ Py_BEGIN_CRITICAL_SECTION(st->array_cache);
+ rc = _PyDict_SetDefaultItemProxy(st, st->array_cache, key, result,
+ &cached);
+ Py_END_CRITICAL_SECTION();
+ if (rc < 0) {
Py_DECREF(key);
Py_DECREF(result);
return NULL;
}
Py_DECREF(key);
- return result;
+ Py_DECREF(result);
+ return cached;
}
@@ -5422,12 +5532,6 @@ _ctypes_Simple_value_set_impl(CDataObject *self, PyObject *value)
{
PyObject *result;
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "can't delete attribute");
- return -1;
- }
-
ctypes_state *st = get_module_state_by_def(Py_TYPE(Py_TYPE(self)));
StgInfo *info;
if (PyStgInfo_FromObject(st, (PyObject *)self, &info) < 0) {
@@ -5440,8 +5544,9 @@ _ctypes_Simple_value_set_impl(CDataObject *self, PyObject *value)
if (!result)
return -1;
- /* consumes the refcount the setfunc returns */
- return KeepRef(self, 0, result);
+ /* consumes the refcount the setfunc returns; self is already locked
+ by the critical section taken by the Argument Clinic wrapper */
+ return KeepRef_lock_held(self, 0, result);
}
@@ -5475,7 +5580,7 @@ _ctypes_Simple_value_get_impl(CDataObject *self)
assert(info); /* Cannot be NULL for CDataObject instances */
assert(info->getfunc);
PyObject *res;
- res = info->getfunc(self->b_ptr, self->b_size);
+ res = info->getfunc(self->b_ptr, info->size);
return res;
}
@@ -5509,15 +5614,29 @@ static PyMethodDef Simple_methods[] = {
{ NULL, NULL },
};
+/*[clinic input]
+@critical_section
+_ctypes.Simple.__bool__ as Simple_bool
+[clinic start generated code]*/
+
static int
-Simple_bool(PyObject *op)
+Simple_bool_impl(CDataObject *self)
+/*[clinic end generated code: output=c4466ece6a99fe8b input=326a1c8b24d8918e]*/
{
- int cmp;
- CDataObject *self = _CDataObject_CAST(op);
- Py_BEGIN_CRITICAL_SECTION(self);
- cmp = memcmp(self->b_ptr, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", self->b_size);
- Py_END_CRITICAL_SECTION();
- return cmp;
+ ctypes_state *st = get_module_state_by_def(Py_TYPE(Py_TYPE(self)));
+ StgInfo *info;
+ if (PyStgInfo_FromObject(st, (PyObject *)self, &info) < 0) {
+ return -1;
+ }
+ assert(info != NULL);
+
+ assert(info->size <= self->b_size);
+ for (Py_ssize_t i = 0; i < info->size; i++) {
+ if (self->b_ptr[i]) {
+ return 1;
+ }
+ }
+ return 0;
}
/* "%s(%s)" % (self.__class__.__name__, self.value) */
@@ -5544,7 +5663,12 @@ Simple_repr(PyObject *self)
static PyType_Slot pycsimple_slots[] = {
{Py_tp_repr, &Simple_repr},
- {Py_tp_doc, PyDoc_STR("XXX to be provided")},
+ {Py_tp_doc, PyDoc_STR("This non-public class is the base class of all "
+ "fundamental ctypes data types.\n"
+ "It contains the common attributes of the fundamental "
+ "ctypes data types.\n"
+ "_SimpleCData is a subclass of _CData, so it inherits "
+ "their methods and attributes.")},
{Py_tp_methods, Simple_methods},
{Py_tp_getset, Simple_getsets},
{Py_tp_init, Simple_init},
@@ -5566,8 +5690,22 @@ static PyType_Spec pycsimple_spec = {
/*
PyCPointer_Type
*/
+/*[clinic input]
+class _ctypes._Pointer "PyObject *" "clinic_state()->PyCPointer_Type"
+[clinic start generated code]*/
+/*[clinic end generated code: output=da39a3ee5e6b4b0d input=452695db70aa7c3e]*/
+
+/*[clinic input]
+@critical_section
+_ctypes._Pointer.__getitem__ as Pointer_item
+ myself: self
+ index: Py_ssize_t
+ /
+[clinic start generated code]*/
+
static PyObject *
-Pointer_item_lock_held(PyObject *myself, Py_ssize_t index)
+Pointer_item_impl(PyObject *myself, Py_ssize_t index)
+/*[clinic end generated code: output=4ae9d566e8038853 input=17943427cd04ed08]*/
{
CDataObject *self = _CDataObject_CAST(myself);
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
@@ -5606,18 +5744,19 @@ Pointer_item_lock_held(PyObject *myself, Py_ssize_t index)
index, size, (char *)((char *)deref + offset));
}
-static PyObject *
-Pointer_item(PyObject *self, Py_ssize_t index)
-{
- PyObject *res;
- Py_BEGIN_CRITICAL_SECTION(self);
- res = Pointer_item_lock_held(self, index);
- Py_END_CRITICAL_SECTION();
- return res;
-}
+/*[clinic input]
+@critical_section
+_ctypes._Pointer.__setitem__ as Pointer_ass_item
+
+ myself: self
+ index: Py_ssize_t
+ value: object
+ /
+[clinic start generated code]*/
static int
-Pointer_ass_item_lock_held(PyObject *myself, Py_ssize_t index, PyObject *value)
+Pointer_ass_item_impl(PyObject *myself, Py_ssize_t index, PyObject *value)
+/*[clinic end generated code: output=4503430bd55b6c69 input=344ad19b3094558c]*/
{
CDataObject *self = _CDataObject_CAST(myself);
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
@@ -5662,16 +5801,6 @@ Pointer_ass_item_lock_held(PyObject *myself, Py_ssize_t index, PyObject *value)
index, size, ((char *)deref + offset));
}
-static int
-Pointer_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
-{
- int res;
- Py_BEGIN_CRITICAL_SECTION(self);
- res = Pointer_ass_item_lock_held(self, index, value);
- Py_END_CRITICAL_SECTION();
- return res;
-}
-
static PyObject *
Pointer_get_contents_lock_held(PyObject *self, void *closure)
{
@@ -5711,11 +5840,6 @@ Pointer_set_contents_lock_held(PyObject *op, PyObject *value, void *closure)
PyObject *keep;
CDataObject *self = _CDataObject_CAST(op);
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "Pointer does not support item deletion");
- return -1;
- }
ctypes_state *st = get_module_state_by_def(Py_TYPE(Py_TYPE(self)));
StgInfo *stginfo;
if (PyStgInfo_FromObject(st, op, &stginfo) < 0) {
@@ -5745,20 +5869,25 @@ Pointer_set_contents_lock_held(PyObject *op, PyObject *value, void *closure)
'value' itself as the second item of the b_objects list, additionally.
*/
Py_INCREF(value);
- if (-1 == KeepRef(self, 1, value))
+ if (-1 == KeepRef_lock_held(self, 1, value))
return -1;
- keep = GetKeepedObjects(dst);
+ keep = GetKeepedObjects_lock_held(dst);
if (keep == NULL)
return -1;
Py_INCREF(keep);
- return KeepRef(self, 0, keep);
+ return KeepRef_lock_held(self, 0, keep);
}
static int
Pointer_set_contents(PyObject *op, PyObject *value, void *closure)
{
+ if (value == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "Pointer does not support item deletion");
+ return -1;
+ }
int res;
Py_BEGIN_CRITICAL_SECTION2(op, value);
res = Pointer_set_contents_lock_held(op, value, closure);
@@ -5807,7 +5936,7 @@ copy_pointer_to_list_lock_held(PyObject *myself, PyObject *np, Py_ssize_t len,
Py_ssize_t i;
size_t cur;
for (cur = start, i = 0; i < len; cur += step, i++) {
- PyObject *v = Pointer_item_lock_held(myself, cur);
+ PyObject *v = Pointer_item_impl(myself, cur);
if (!v) {
return -1;
}
@@ -5898,8 +6027,6 @@ Pointer_subscript(PyObject *myself, PyObject *item)
}
assert(iteminfo);
if (iteminfo->getfunc == _ctypes_get_fielddesc("c")->getfunc) {
- char *dest;
-
if (len <= 0)
return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
if (step == 1) {
@@ -5911,18 +6038,18 @@ Pointer_subscript(PyObject *myself, PyObject *item)
Py_END_CRITICAL_SECTION();
return res;
}
- dest = (char *)PyMem_Malloc(len);
- if (dest == NULL)
- return PyErr_NoMemory();
+ PyBytesWriter *writer = PyBytesWriter_Create(len);
+ if (writer == NULL) {
+ return NULL;
+ }
+ char *dest = PyBytesWriter_GetData(writer);
Py_BEGIN_CRITICAL_SECTION(self);
char *ptr = *(void **)self->b_ptr;
for (cur = start, i = 0; i < len; cur += step, i++) {
dest[i] = ptr[cur];
}
Py_END_CRITICAL_SECTION();
- np = PyBytes_FromStringAndSize(dest, len);
- PyMem_Free(dest);
- return np;
+ return PyBytesWriter_Finish(writer);
}
if (iteminfo->getfunc == _ctypes_get_fielddesc("u")->getfunc) {
wchar_t *dest;
@@ -5974,18 +6101,32 @@ Pointer_subscript(PyObject *myself, PyObject *item)
}
}
+/*[clinic input]
+@critical_section
+_ctypes._Pointer.__bool__ as Pointer_bool
+[clinic start generated code]*/
+
static int
-Pointer_bool(PyObject *self)
+Pointer_bool_impl(PyObject *self)
+/*[clinic end generated code: output=0139acaf4d395a69 input=672b8d35e7e0752d]*/
{
- int res;
- Py_BEGIN_CRITICAL_SECTION(self);
- res = *(void **)_CDataObject_CAST(self)->b_ptr != NULL;
- Py_END_CRITICAL_SECTION();
- return res;
+ return *(void **)_CDataObject_CAST(self)->b_ptr != NULL;
}
static PyType_Slot pycpointer_slots[] = {
- {Py_tp_doc, (void *)PyDoc_STR("XXX to be provided")},
+ {Py_tp_doc, (void *)PyDoc_STR(
+ "Private, abstract base class for pointers.\n"
+ "\n"
+ "Concrete pointer types are created by calling POINTER() "
+ "with the type that will be pointed to; this is done "
+ "automatically by pointer().\n"
+ "\n"
+ "If a pointer points to an array, its elements can be read "
+ "and written using standard subscript and slice accesses. "
+ "Pointer objects have no size, so len() will raise "
+ "TypeError. Negative subscripts will read from the memory "
+ "before the pointer (as in C), and out-of-range subscripts "
+ "will probably crash with an access violation (if you’re lucky).")},
{Py_tp_getset, Pointer_getsets},
{Py_tp_init, Pointer_init},
{Py_tp_new, Pointer_new},
@@ -6268,7 +6409,10 @@ _ctypes_add_types(PyObject *mod)
*/
CREATE_TYPE(st->PyCArg_Type, &carg_spec, NULL, NULL);
CREATE_TYPE(st->PyCThunk_Type, &cthunk_spec, NULL, NULL);
- CREATE_TYPE(st->PyCData_Type, &pycdata_spec, NULL, NULL);
+ st->PyCData_Type = (PyTypeObject *)PyCData_create_type(mod);
+ if (st->PyCData_Type == NULL) {
+ return -1;
+ }
// Common Metaclass
CREATE_TYPE(st->PyCType_Type, &pyctype_type_spec,
@@ -6384,21 +6528,92 @@ _ctypes_add_objects(PyObject *mod)
}
+#ifdef FFI_VERSION_NUMBER
+PyDoc_STRVAR(libffi_version_info__doc__,
+"ctypes.libffi_version_info\n\
+\n\
+libffi version information as a named tuple.");
+
+static PyStructSequence_Field libffi_version_info_fields[] = {
+ {"major", "Major release number"},
+ {"minor", "Minor release number"},
+ {"patch", "Patch release number"},
+ {0}
+};
+
+static PyStructSequence_Desc libffi_version_info_desc = {
+ "ctypes.libffi_version_info", /* name */
+ libffi_version_info__doc__, /* doc */
+ libffi_version_info_fields, /* fields */
+ 3
+};
+
+static PyObject *
+make_libffi_version_info(PyTypeObject *type, unsigned long number)
+{
+ PyObject *version;
+ int pos = 0;
+ unsigned long major = number / 10000;
+ unsigned long minor = (number % 10000) / 100;
+ unsigned long patch = number % 100;
+
+ version = PyStructSequence_New(type);
+ if (version == NULL) {
+ return NULL;
+ }
+
+#define SetItem(VALUE) \
+ PyStructSequence_SET_ITEM(version, pos++, VALUE); \
+ if (PyErr_Occurred()) { \
+ Py_DECREF(version); \
+ return NULL; \
+ }
+
+ SetItem(PyLong_FromUnsignedLong(major))
+ SetItem(PyLong_FromUnsignedLong(minor))
+ SetItem(PyLong_FromUnsignedLong(patch))
+#undef SetItem
+
+ return version;
+}
+
static int
-_ctypes_mod_exec(PyObject *mod)
+_ctypes_add_version_constants(PyObject *mod)
{
- // See https://github.com/python/cpython/issues/128485
- // This allocates some memory and then frees it to ensure that the
- // the dlmalloc allocator initializes itself to avoid data races
- // in free-threading.
- void *codeloc = NULL;
- void *ptr = Py_ffi_closure_alloc(sizeof(void *), &codeloc);
- if (ptr == NULL) {
- PyErr_NoMemory();
+ if (PyModule_AddStringConstant(mod, "LIBFFI_VERSION",
+ FFI_VERSION_STRING) < 0) {
return -1;
}
- Py_ffi_closure_free(ptr);
+ if (PyModule_AddStringConstant(mod, "libffi_version",
+ ffi_get_version()) < 0) {
+ return -1;
+ }
+ PyTypeObject *version_type;
+ version_type = PyStructSequence_NewType(&libffi_version_info_desc);
+ if (version_type == NULL) {
+ return -1;
+ }
+ if (PyModule_Add(mod, "LIBFFI_VERSION_INFO",
+ make_libffi_version_info(version_type, FFI_VERSION_NUMBER)) < 0)
+ {
+ Py_DECREF(version_type);
+ return -1;
+ }
+ if (PyModule_Add(mod, "libffi_version_info",
+ make_libffi_version_info(version_type,
+ ffi_get_version_number())) < 0)
+ {
+ Py_DECREF(version_type);
+ return -1;
+ }
+ Py_DECREF(version_type);
+ return 0;
+}
+#endif
+static int
+_ctypes_mod_exec(PyObject *mod)
+{
_ctypes_init_fielddesc();
ctypes_state *st = get_module_state(mod);
@@ -6438,6 +6653,11 @@ _ctypes_mod_exec(PyObject *mod)
if (_ctypes_add_objects(mod) < 0) {
return -1;
}
+#ifdef FFI_VERSION_NUMBER
+ if (_ctypes_add_version_constants(mod) < 0) {
+ return -1;
+ }
+#endif
return 0;
}
diff --git a/Modules/_ctypes/_ctypes_test.c b/Modules/_ctypes/_ctypes_test.c
index 991ff0d675c2f1c..900dba34fc72967 100644
--- a/Modules/_ctypes/_ctypes_test.c
+++ b/Modules/_ctypes/_ctypes_test.c
@@ -13,16 +13,6 @@
#include
-#ifdef thread_local
-# define _Py_thread_local thread_local
-#elif __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__)
-# define _Py_thread_local _Thread_local
-#elif defined(_MSC_VER) /* AKA NT_THREADS */
-# define _Py_thread_local __declspec(thread)
-#elif defined(__GNUC__) /* includes clang */
-# define _Py_thread_local __thread
-#endif
-
#if defined(_Py_FFI_SUPPORT_C_COMPLEX)
# include // csqrt()
# undef I // for _ctypes_test_generated.c.h
@@ -72,6 +62,79 @@ _testfunc_cbk_large_struct(Test in, void (*func)(Test))
func(in);
}
+/*
+ * gh-49960: callbacks returning structs and unions by value.
+ *
+ * Each of these exercises a different ABI return class, since struct
+ * return conventions are highly platform-specific:
+ * - SmallRet: small integer struct, returned in registers
+ * - Test: >8 bytes (reused from above), returned via hidden pointer
+ * - FloatRet: all-float struct, SSE class on x86-64 / HFA on AArch64
+ * - UnionRet: union
+ * - PtrRet: struct containing a pointer
+ */
+
+typedef struct {
+ int a;
+ int b;
+} SmallRet;
+
+EXPORT(SmallRet)
+_testfunc_cbk_ret_small_struct(SmallRet (*func)(void))
+{
+ return func();
+}
+
+/* Returns a scalar derived from the struct, so a test can prove the bytes
+ actually reached the C caller rather than only round-tripping in Python. */
+EXPORT(long)
+_testfunc_cbk_ret_small_struct_sum(SmallRet (*func)(void))
+{
+ SmallRet s = func();
+ return (long)s.a + (long)s.b;
+}
+
+EXPORT(Test)
+_testfunc_cbk_ret_large_struct(Test (*func)(void))
+{
+ return func();
+}
+
+typedef struct {
+ double x;
+ double y;
+} FloatRet;
+
+EXPORT(FloatRet)
+_testfunc_cbk_ret_float_struct(FloatRet (*func)(void))
+{
+ return func();
+}
+
+typedef union {
+ int i;
+ float f;
+} UnionRet;
+
+EXPORT(UnionRet)
+_testfunc_cbk_ret_union(UnionRet (*func)(void))
+{
+ return func();
+}
+
+/* Struct containing a pointer, for the documented pointer-lifetime contract:
+ the struct is copied by value, so the pointed-to memory must outlive the
+ callback. */
+typedef struct {
+ const char *s;
+} PtrRet;
+
+EXPORT(PtrRet)
+_testfunc_cbk_ret_ptr_struct(PtrRet (*func)(void))
+{
+ return func();
+}
+
/*
* See issue 29565. Update a structure passed by value;
* the caller should not see any change.
@@ -638,6 +701,11 @@ EXPORT(long long) _testfunc_callback_q_qf(long long value,
return sum;
}
+EXPORT(long long) _testfunc_callback_int_to_longlong(int (*func)(void))
+{
+ return func();
+}
+
typedef struct {
char *name;
char *value;
diff --git a/Modules/_ctypes/callbacks.c b/Modules/_ctypes/callbacks.c
index fd508ae61f2e040..e54111b8a4fab44 100644
--- a/Modules/_ctypes/callbacks.c
+++ b/Modules/_ctypes/callbacks.c
@@ -9,6 +9,7 @@
#endif
#include "pycore_call.h" // _PyObject_CallNoArgs()
+#include "pycore_lock.h" // _PyOnceFlag_CallOnce()
#include "pycore_runtime.h" // _Py_ID()
#include
@@ -101,6 +102,22 @@ TryAddRef(PyObject *cnv, CDataObject *obj)
}
#endif
+static int
+is_narrow_int_ffi_type(int type)
+{
+ switch (type) {
+ case FFI_TYPE_SINT8:
+ case FFI_TYPE_UINT8:
+ case FFI_TYPE_SINT16:
+ case FFI_TYPE_UINT16:
+ case FFI_TYPE_SINT32:
+ case FFI_TYPE_UINT32:
+ return 1;
+ default:
+ return 0;
+ }
+}
+
/******************************************************************************
*
* Call the python object with all arguments
@@ -111,6 +128,7 @@ TryAddRef(PyObject *cnv, CDataObject *obj)
static void _CallPythonObject(ctypes_state *st,
void *mem,
ffi_type *restype,
+ PyObject *restype_obj,
SETFUNC setfunc,
PyObject *callable,
PyObject *converters,
@@ -220,47 +238,113 @@ static void _CallPythonObject(ctypes_state *st,
Py_XDECREF(error_object);
if (restype != &ffi_type_void && result) {
- assert(setfunc);
-
-#ifdef WORDS_BIGENDIAN
- /* See the corresponding code in _ctypes_callproc():
- in callproc.c, around line 1219. */
- if (restype->type != FFI_TYPE_FLOAT && restype->size < sizeof(ffi_arg)) {
- mem = (char *)mem + sizeof(ffi_arg) - restype->size;
- }
-#endif
- /* keep is an object we have to keep alive so that the result
- stays valid. If there is no such object, the setfunc will
- have returned Py_None.
-
- If there is such an object, we have no choice than to keep
- it alive forever - but a refcount and/or memory leak will
- be the result. EXCEPT when restype is py_object - Python
- itself knows how to manage the refcount of these objects.
- */
- PyObject *keep = setfunc(mem, result, restype->size);
-
- if (keep == NULL) {
- /* Could not convert callback result. */
- PyErr_FormatUnraisable(
- "Exception ignored while converting result "
- "of ctypes callback function %R",
- callable);
+ /* libffi's closure contract requires integral results narrower
+ than ffi_arg to fill a whole register, sign-extended if signed;
+ setfunc() only writes restype->size bytes. Structs and unions
+ are never narrow integers, so they always write to mem directly. */
+ union {
+ ffi_arg arg;
+ int8_t s8;
+ uint8_t u8;
+ int16_t s16;
+ uint16_t u16;
+ int32_t s32;
+ uint32_t u32;
+ } narrow_res = {0};
+ int narrow = restype->size < sizeof(ffi_arg) &&
+ is_narrow_int_ffi_type(restype->type);
+ void *resmem = narrow ? (void *)&narrow_res : mem;
+
+ if (setfunc == NULL) {
+ /* gh-49960: struct/union return. There is no setfunc for these
+ types, so copy the bytes out of the CData object directly.
+ The struct is copied by value and no object is kept alive, so
+ any pointer it contains must reference memory the caller keeps
+ alive - the same contract C imposes. */
+ assert(!narrow);
+ /* Use a real subtype check rather than PyObject_IsInstance():
+ a metaclass __instancecheck__ could otherwise accept an object
+ whose buffer is smaller than restype->size. */
+ if (PyObject_TypeCheck(result, (PyTypeObject *)restype_obj)) {
+ /* restype_obj is a struct or union type (enforced in
+ _ctypes_alloc_callback), so its instances are CData. */
+ assert(CDataObject_Check(st, result));
+ CDataObject *cd = (CDataObject *)result;
+ Py_BEGIN_CRITICAL_SECTION(cd);
+ memcpy(mem, cd->b_ptr, restype->size);
+ Py_END_CRITICAL_SECTION();
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "ctypes callback function returned unexpected "
+ "type %T", result);
+ PyErr_FormatUnraisable(
+ "Exception ignored while converting result "
+ "of ctypes callback function %R",
+ callable);
+ }
}
- else if (setfunc != _ctypes_get_fielddesc("O")->setfunc) {
- if (keep == Py_None) {
- /* Nothing to keep */
- Py_DECREF(keep);
+ else {
+ /* keep is an object we have to keep alive so that the result
+ stays valid. If there is no such object, the setfunc will
+ have returned Py_None.
+
+ If there is such an object, we have no choice than to keep
+ it alive forever - but a refcount and/or memory leak will
+ be the result. EXCEPT when restype is py_object - Python
+ itself knows how to manage the refcount of these objects.
+ */
+ PyObject *keep = setfunc(resmem, result, restype->size);
+
+ if (narrow && keep != NULL) {
+ ffi_arg widened;
+ switch (restype->type) {
+ case FFI_TYPE_SINT8:
+ widened = (ffi_arg)(ffi_sarg)narrow_res.s8;
+ break;
+ case FFI_TYPE_SINT16:
+ widened = (ffi_arg)(ffi_sarg)narrow_res.s16;
+ break;
+ case FFI_TYPE_SINT32:
+ widened = (ffi_arg)(ffi_sarg)narrow_res.s32;
+ break;
+ case FFI_TYPE_UINT8:
+ widened = narrow_res.u8;
+ break;
+ case FFI_TYPE_UINT16:
+ widened = narrow_res.u16;
+ break;
+ case FFI_TYPE_UINT32:
+ widened = narrow_res.u32;
+ break;
+ default:
+ Py_UNREACHABLE();
+ }
+ memcpy(mem, &widened, sizeof(ffi_arg));
}
- else if (PyErr_WarnEx(PyExc_RuntimeWarning,
- "memory leak in callback function.",
- 1) == -1) {
+
+ if (keep == NULL) {
+ /* Could not convert callback result. */
PyErr_FormatUnraisable(
"Exception ignored while converting result "
"of ctypes callback function %R",
callable);
}
+ else if (setfunc != _ctypes_get_fielddesc("O")->setfunc) {
+ if (keep == Py_None) {
+ /* Nothing to keep */
+ Py_DECREF(keep);
+ }
+ else if (PyErr_WarnEx(PyExc_RuntimeWarning,
+ "memory leak in callback function.",
+ 1) == -1) {
+ PyErr_FormatUnraisable(
+ "Exception ignored while converting result "
+ "of ctypes callback function %R",
+ callable);
+ }
+ }
}
}
@@ -293,6 +377,7 @@ static void closure_fcn(ffi_cif *cif,
_CallPythonObject(st,
resp,
p->ffi_restype,
+ p->restype,
p->setfunc,
p->callable,
p->converters,
@@ -328,6 +413,27 @@ static CThunkObject* CThunkObject_new(ctypes_state *st, Py_ssize_t nargs)
return p;
}
+static _PyOnceFlag closure_alloc_init_once = {0};
+
+// This is done lazily with a once flag rather than in the module exec function,
+// because allocating a closure can have some side effects that affect the whole
+// process (gh-135893).
+static int
+closure_alloc_init(void *Py_UNUSED(arg))
+{
+ // See https://github.com/python/cpython/issues/128485
+ // This allocates some memory and then frees it to ensure that libffi's
+ // dlmalloc allocator initializes itself exactly once, avoiding data races
+ // between threads that don't share a GIL.
+ void *codeloc = NULL;
+ void *ptr = Py_ffi_closure_alloc(sizeof(void *), &codeloc);
+ if (ptr == NULL) {
+ return -1;
+ }
+ Py_ffi_closure_free(ptr);
+ return 0;
+}
+
CThunkObject *_ctypes_alloc_callback(ctypes_state *st,
PyObject *callable,
PyObject *converters,
@@ -347,6 +453,12 @@ CThunkObject *_ctypes_alloc_callback(ctypes_state *st,
assert(CThunk_CheckExact(st, (PyObject *)p));
+ if (_PyOnceFlag_CallOnce(&closure_alloc_init_once,
+ closure_alloc_init, NULL) < 0) {
+ PyErr_NoMemory();
+ goto error;
+ }
+
p->pcl_write = Py_ffi_closure_alloc(sizeof(ffi_closure), &p->pcl_exec);
if (p->pcl_write == NULL) {
PyErr_NoMemory();
@@ -371,10 +483,25 @@ CThunkObject *_ctypes_alloc_callback(ctypes_state *st,
goto error;
}
- if (info == NULL || info->setfunc == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "invalid result type for callback function");
- goto error;
+ /* gh-49960: structs and unions have no setfunc (that is reserved for
+ "simple" types), but can still be returned by value. Leaving
+ p->setfunc as NULL signals the struct-return path in
+ _CallPythonObject. */
+ if (info == NULL
+ || (
+ info->setfunc == NULL
+ && !PyCStructTypeObject_Check(st, restype)
+ && !PyObject_TypeCheck(restype, st->UnionType_Type)
+ )
+ ) {
+ PyErr_SetString(PyExc_TypeError,
+ "invalid result type for callback function");
+ goto error;
+ }
+ if (info->setfunc == NULL) {
+ /* The cif built below depends on the struct/union layout, so
+ _fields_ must not be (re)assigned after this point. */
+ stginfo_set_dict_final(info);
}
p->setfunc = info->setfunc;
p->ffi_restype = &info->ffi_type_pointer;
diff --git a/Modules/_ctypes/callproc.c b/Modules/_ctypes/callproc.c
index ccc57e347b07acf..c8a54b0cec83a77 100644
--- a/Modules/_ctypes/callproc.c
+++ b/Modules/_ctypes/callproc.c
@@ -91,10 +91,30 @@ module _ctypes
#define DONT_USE_SEH
#endif
+#include "pycore_ceval.h" // _Py_EnterRecursiveCall()
#include "pycore_runtime.h" // _PyRuntime
#include "pycore_global_objects.h"// _Py_ID()
#include "pycore_traceback.h" // _PyTraceback_Add()
+#ifndef MS_WIN32
+# if HAVE_DECL_RTLD_LOCAL
+# define DLOPEN_DEFAULT_MODE (RTLD_NOW | RTLD_LOCAL)
+# else
+ /* cygwin doesn't define RTLD_LOCAL */
+# define DLOPEN_DEFAULT_MODE RTLD_NOW
+# endif
+#endif
+
+static int _parse_voidp(PyObject *obj, void *arg);
+static int _parse_voidp_object(PyObject *obj, void *arg);
+
+/*[python input]
+class voidp_converter(CConverter):
+ type = 'void *'
+ converter = '_parse_voidp'
+[python start generated code]*/
+/*[python end generated code: output=da39a3ee5e6b4b0d input=c230831f53ec0946]*/
+
#define clinic_state() (get_module_state(module))
#include "clinic/callproc.c.h"
#undef clinic_state
@@ -186,10 +206,10 @@ _ctypes_get_errobj(ctypes_state *st, int **pspace)
}
static PyObject *
-get_error_internal(PyObject *self, PyObject *args, int index)
+get_error_internal(PyObject *module, int index)
{
int *space;
- ctypes_state *st = get_module_state(self);
+ ctypes_state *st = get_module_state(module);
PyObject *errobj = _ctypes_get_errobj(st, &space);
PyObject *result;
@@ -201,16 +221,13 @@ get_error_internal(PyObject *self, PyObject *args, int index)
}
static PyObject *
-set_error_internal(PyObject *self, PyObject *args, int index)
+set_error_internal(PyObject *module, int new_errno, int index)
{
- int new_errno, old_errno;
+ int old_errno;
PyObject *errobj;
int *space;
- if (!PyArg_ParseTuple(args, "i", &new_errno)) {
- return NULL;
- }
- ctypes_state *st = get_module_state(self);
+ ctypes_state *st = get_module_state(module);
errobj = _ctypes_get_errobj(st, &space);
if (errobj == NULL)
return NULL;
@@ -220,42 +237,72 @@ set_error_internal(PyObject *self, PyObject *args, int index)
return PyLong_FromLong(old_errno);
}
+/*[clinic input]
+_ctypes.get_errno
+
+Return the current value of the ctypes-private copy of errno.
+[clinic start generated code]*/
+
static PyObject *
-get_errno(PyObject *self, PyObject *args)
+_ctypes_get_errno_impl(PyObject *module)
+/*[clinic end generated code: output=82992e823984b48e input=bf578c7a7608b0f4]*/
{
if (PySys_Audit("ctypes.get_errno", NULL) < 0) {
return NULL;
}
- return get_error_internal(self, args, 0);
+ return get_error_internal(module, 0);
}
+/*[clinic input]
+_ctypes.set_errno
+
+ value: int
+ /
+[clinic start generated code]*/
+
static PyObject *
-set_errno(PyObject *self, PyObject *args)
+_ctypes_set_errno_impl(PyObject *module, int value)
+/*[clinic end generated code: output=0c85e07ccf0749c2 input=b2550d9d2cdfab20]*/
{
- if (PySys_Audit("ctypes.set_errno", "O", args) < 0) {
+ if (PySys_Audit("ctypes.set_errno", "i", value) < 0) {
return NULL;
}
- return set_error_internal(self, args, 0);
+ return set_error_internal(module, value, 0);
}
#ifdef MS_WIN32
+/*[clinic input]
+_ctypes.get_last_error
+
+Return the current value of the ctypes-private copy of the last error.
+[clinic start generated code]*/
+
static PyObject *
-get_last_error(PyObject *self, PyObject *args)
+_ctypes_get_last_error_impl(PyObject *module)
+/*[clinic end generated code: output=e237c4d3b75eb1eb input=d25599a79c030bb4]*/
{
if (PySys_Audit("ctypes.get_last_error", NULL) < 0) {
return NULL;
}
- return get_error_internal(self, args, 1);
+ return get_error_internal(module, 1);
}
+/*[clinic input]
+_ctypes.set_last_error
+
+ value: int
+ /
+[clinic start generated code]*/
+
static PyObject *
-set_last_error(PyObject *self, PyObject *args)
+_ctypes_set_last_error_impl(PyObject *module, int value)
+/*[clinic end generated code: output=dce5b4be6255bcb5 input=1a3f4ba970902db7]*/
{
- if (PySys_Audit("ctypes.set_last_error", "O", args) < 0) {
+ if (PySys_Audit("ctypes.set_last_error", "i", value) < 0) {
return NULL;
}
- return set_error_internal(self, args, 1);
+ return set_error_internal(module, value, 1);
}
static WCHAR *FormatError(DWORD code)
@@ -446,12 +493,17 @@ static DWORD HandleException(EXCEPTION_POINTERS *ptrs,
}
#endif
+/*[clinic input]
+_ctypes._check_HRESULT
+
+ hresult as hr: int
+ /
+[clinic start generated code]*/
+
static PyObject *
-check_hresult(PyObject *self, PyObject *args)
+_ctypes__check_HRESULT_impl(PyObject *module, int hr)
+/*[clinic end generated code: output=ba872ad9e32b2d1f input=75e2334791d6cf29]*/
{
- HRESULT hr;
- if (!PyArg_ParseTuple(args, "i", &hr))
- return NULL;
if (FAILED(hr))
return PyErr_SetFromWindowsErr(hr);
return PyLong_FromLong(hr);
@@ -744,8 +796,12 @@ static int ConvParam(ctypes_state *st,
attribute)
*/
if (arg) {
- int result;
- result = ConvParam(st, arg, index, pa);
+ if (_Py_EnterRecursiveCall(" while processing _as_parameter_")) {
+ Py_DECREF(arg);
+ return -1;
+ }
+ int result = ConvParam(st, arg, index, pa);
+ _Py_LeaveRecursiveCall();
Py_DECREF(arg);
return result;
}
@@ -1082,8 +1138,7 @@ void _ctypes_extend_error(PyObject *exc_class, const char *fmt, ...)
}
-#ifdef MS_WIN32
-
+#ifdef MS_WINDOWS_DESKTOP
static PyObject *
GetComError(ctypes_state *st, HRESULT errcode, GUID *riid, IUnknown *pIunk)
{
@@ -1337,9 +1392,11 @@ PyObject *_ctypes_callproc(ctypes_state *st,
#ifdef MS_WIN32
if (iid && pIunk) {
+#ifdef MS_WINDOWS_DESKTOP
if (*(int *)resbuf & 0x80000000)
retval = GetComError(st, *(HRESULT *)resbuf, iid, pIunk);
else
+#endif
retval = PyLong_FromLong(*(int *)resbuf);
} else if (flags & FUNCFLAG_HRESULT) {
if (*(int *)resbuf & 0x80000000)
@@ -1367,18 +1424,25 @@ _parse_voidp(PyObject *obj, void *arg)
#ifdef MS_WIN32
-PyDoc_STRVAR(format_error_doc,
-"FormatError([integer]) -> string\n\
-\n\
-Convert a win32 error code into a string. If the error code is not\n\
-given, the return value of a call to GetLastError() is used.\n");
-static PyObject *format_error(PyObject *self, PyObject *args)
+/*[clinic input]
+_ctypes.FormatError
+
+ code: int = 0
+ /
+
+Convert a win32 error code into a string.
+
+If the error code is not given, the return value of a call to
+GetLastError() is used.
+[clinic start generated code]*/
+
+static PyObject *
+_ctypes_FormatError_impl(PyObject *module, int code)
+/*[clinic end generated code: output=ccc560dddfd0b3d7 input=e0c98f1c644e5153]*/
{
PyObject *result;
wchar_t *lpMsgBuf;
- DWORD code = 0;
- if (!PyArg_ParseTuple(args, "|i:FormatError", &code))
- return NULL;
+
if (code == 0)
code = GetLastError();
lpMsgBuf = FormatError(code);
@@ -1391,23 +1455,26 @@ static PyObject *format_error(PyObject *self, PyObject *args)
return result;
}
-PyDoc_STRVAR(load_library_doc,
-"LoadLibrary(name, load_flags) -> handle\n\
-\n\
-Load an executable (usually a DLL), and return a handle to it.\n\
-The handle may be used to locate exported functions in this\n\
-module. load_flags are as defined for LoadLibraryEx in the\n\
-Windows API.\n");
-static PyObject *load_library(PyObject *self, PyObject *args)
+/*[clinic input]
+_ctypes.LoadLibrary
+
+ name as nameobj: unicode
+ load_flags: int = 0
+ /
+
+Load an executable (usually a DLL), and return a handle to it.
+
+The handle may be used to locate exported functions in this module.
+load_flags are as defined for LoadLibraryEx in the Windows API.
+[clinic start generated code]*/
+
+static PyObject *
+_ctypes_LoadLibrary_impl(PyObject *module, PyObject *nameobj, int load_flags)
+/*[clinic end generated code: output=4e33b2cda4b12af6 input=69e4b6512653825e]*/
{
- PyObject *nameobj;
- int load_flags = 0;
HMODULE hMod;
DWORD err;
- if (!PyArg_ParseTuple(args, "U|i:LoadLibrary", &nameobj, &load_flags))
- return NULL;
-
if (PySys_Audit("ctypes.dlopen", "O", nameobj) < 0) {
return NULL;
}
@@ -1442,17 +1509,21 @@ static PyObject *load_library(PyObject *self, PyObject *args)
#endif
}
-PyDoc_STRVAR(free_library_doc,
-"FreeLibrary(handle) -> void\n\
-\n\
-Free the handle of an executable previously loaded by LoadLibrary.\n");
-static PyObject *free_library(PyObject *self, PyObject *args)
+/*[clinic input]
+_ctypes.FreeLibrary
+
+ handle as hMod: voidp
+ /
+
+Free the handle of an executable previously loaded by LoadLibrary.
+[clinic start generated code]*/
+
+static PyObject *
+_ctypes_FreeLibrary_impl(PyObject *module, void *hMod)
+/*[clinic end generated code: output=2424a8daf3fe93df input=e722e432560e849a]*/
{
- void *hMod;
BOOL result;
DWORD err;
- if (!PyArg_ParseTuple(args, "O&:FreeLibrary", &_parse_voidp, &hMod))
- return NULL;
Py_BEGIN_ALLOW_THREADS
result = FreeLibrary((HMODULE)hMod);
@@ -1465,20 +1536,27 @@ static PyObject *free_library(PyObject *self, PyObject *args)
Py_RETURN_NONE;
}
-PyDoc_STRVAR(copy_com_pointer_doc,
-"CopyComPointer(src, dst) -> HRESULT value\n");
+/*[clinic input]
+_ctypes.CopyComPointer
+
+ src as p1: object
+ dst as p2: object
+ /
+
+Copy a COM pointer and return the HRESULT value.
+[clinic start generated code]*/
static PyObject *
-copy_com_pointer(PyObject *self, PyObject *args)
+_ctypes_CopyComPointer_impl(PyObject *module, PyObject *p1, PyObject *p2)
+/*[clinic end generated code: output=bbe731fea856eba2 input=296c1f3e026bbf27]*/
{
- PyObject *p1, *p2, *r = NULL;
+ PyObject *r = NULL;
struct argument a, b;
IUnknown *src, **pdst;
- if (!PyArg_ParseTuple(args, "OO:CopyComPointer", &p1, &p2))
- return NULL;
+
a.keep = b.keep = NULL;
- ctypes_state *st = get_module_state(self);
+ ctypes_state *st = get_module_state(module);
if (ConvParam(st, p1, 0, &a) < 0 || ConvParam(st, p2, 1, &b) < 0) {
goto done;
}
@@ -1529,17 +1607,25 @@ __attribute__((destructor)) void unload_dyld_shared_cache_contains_path(void) {
_dyld_shared_cache_contains_path != NULL
#endif
-static PyObject *py_dyld_shared_cache_contains_path(PyObject *self, PyObject *args)
+/*[clinic input]
+_ctypes._dyld_shared_cache_contains_path
+
+ path as name: object
+ /
+
+Check whether a path is in the shared cache.
+[clinic start generated code]*/
+
+static PyObject *
+_ctypes__dyld_shared_cache_contains_path(PyObject *module, PyObject *name)
+/*[clinic end generated code: output=1d3fed04c0490294 input=bb910a42599d991f]*/
{
- PyObject *name, *name2;
+ PyObject *name2;
char *name_str;
if (HAVE_DYLD_SHARED_CACHE_CONTAINS_PATH_RUNTIME) {
int r;
- if (!PyArg_ParseTuple(args, "O", &name))
- return NULL;
-
if (name == Py_None)
Py_RETURN_FALSE;
@@ -1564,19 +1650,24 @@ static PyObject *py_dyld_shared_cache_contains_path(PyObject *self, PyObject *ar
}
#endif
-static PyObject *py_dl_open(PyObject *self, PyObject *args)
+/*[clinic input]
+_ctypes.dlopen
+
+ name: object
+ mode: int(c_default="DLOPEN_DEFAULT_MODE") = RTLD_NOW | RTLD_LOCAL
+ /
+
+Open a shared library.
+[clinic start generated code]*/
+
+static PyObject *
+_ctypes_dlopen_impl(PyObject *module, PyObject *name, int mode)
+/*[clinic end generated code: output=d68f1775017199b8 input=df6aa38a12f91cfe]*/
{
- PyObject *name, *name2;
+ PyObject *name2;
const char *name_str;
void * handle;
-#if HAVE_DECL_RTLD_LOCAL
- int mode = RTLD_NOW | RTLD_LOCAL;
-#else
- /* cygwin doesn't define RTLD_LOCAL */
- int mode = RTLD_NOW;
-#endif
- if (!PyArg_ParseTuple(args, "O|i:dlopen", &name, &mode))
- return NULL;
+
mode |= RTLD_NOW;
if (name != Py_None) {
if (PyUnicode_FSConverter(name, &name2) == 0)
@@ -1603,12 +1694,19 @@ static PyObject *py_dl_open(PyObject *self, PyObject *args)
return PyLong_FromVoidPtr(handle);
}
-static PyObject *py_dl_close(PyObject *self, PyObject *args)
-{
- void *handle;
+/*[clinic input]
+_ctypes.dlclose
- if (!PyArg_ParseTuple(args, "O&:dlclose", &_parse_voidp, &handle))
- return NULL;
+ handle: voidp
+ /
+
+Close a shared library.
+[clinic start generated code]*/
+
+static PyObject *
+_ctypes_dlclose_impl(PyObject *module, void *handle)
+/*[clinic end generated code: output=80a4d433a7c81348 input=b8a3d95439746deb]*/
+{
if (dlclose(handle)) {
const char *errmsg = dlerror();
if (errmsg) {
@@ -1621,16 +1719,24 @@ static PyObject *py_dl_close(PyObject *self, PyObject *args)
Py_RETURN_NONE;
}
-static PyObject *py_dl_sym(PyObject *self, PyObject *args)
+/*[clinic input]
+_ctypes.dlsym
+
+ handle: voidp
+ name: str
+ /
+
+Find a symbol in a shared library.
+[clinic start generated code]*/
+
+static PyObject *
+_ctypes_dlsym_impl(PyObject *module, void *handle, const char *name)
+/*[clinic end generated code: output=fada3d0f0447614c input=ee37a4935a19550c]*/
{
- char *name;
- void *handle;
void *ptr;
- if (!PyArg_ParseTuple(args, "O&s:dlsym",
- &_parse_voidp, &handle, &name))
- return NULL;
- if (PySys_Audit("ctypes.dlsym/handle", "O", args) < 0) {
+ if (PySys_Audit("ctypes.dlsym/handle", "ns", (Py_ssize_t)handle,
+ name) < 0) {
return NULL;
}
#undef USE_DLERROR
@@ -1660,6 +1766,49 @@ static PyObject *py_dl_sym(PyObject *self, PyObject *args)
PyErr_Format(PyExc_OSError, "symbol '%s' not found", name);
return NULL;
}
+
+// Apple platforms use the dyld API in ctypes.util instead.
+#if defined(HAVE_DL_ITERATE_PHDR) && !defined(__APPLE__)
+#include
+
+static int
+_dllist_callback(struct dl_phdr_info *info, size_t size, void *data)
+{
+ PyObject *list = (PyObject *)data;
+ PyObject *name = PyUnicode_DecodeFSDefault(info->dlpi_name);
+ if (name == NULL) {
+ return -1;
+ }
+ int res = PyList_Append(list, name);
+ Py_DECREF(name);
+ return res;
+}
+
+/*[clinic input]
+_ctypes.dllist
+
+Return a list of loaded shared libraries.
+[clinic start generated code]*/
+
+static PyObject *
+_ctypes_dllist_impl(PyObject *module)
+/*[clinic end generated code: output=7b4eaaecc7abf21a input=5bfb4e345425f59f]*/
+{
+ // On NetBSD dl_iterate_phdr() only reports the link-map group of the
+ // caller, so it cannot be called via a libffi trampoline.
+ PyObject *list = PyList_New(0);
+ if (list == NULL) {
+ return NULL;
+ }
+ // The return value only echoes the callback result.
+ dl_iterate_phdr(_dllist_callback, list);
+ if (PyErr_Occurred()) {
+ Py_DECREF(list);
+ return NULL;
+ }
+ return list;
+}
+#endif
#endif
/*
@@ -1667,20 +1816,21 @@ static PyObject *py_dl_sym(PyObject *self, PyObject *args)
*
* XXX Needs to accept more arguments: flags, argtypes, restype
*/
+/*[clinic input]
+_ctypes.call_function
+
+ func: voidp
+ arguments: object(subclass_of='&PyTuple_Type')
+ /
+[clinic start generated code]*/
+
static PyObject *
-call_function(PyObject *self, PyObject *args)
+_ctypes_call_function_impl(PyObject *module, void *func, PyObject *arguments)
+/*[clinic end generated code: output=e90059bba8e0f0de input=2f2a7a5ea1b4031f]*/
{
- void *func;
- PyObject *arguments;
PyObject *result;
- if (!PyArg_ParseTuple(args,
- "O&O!",
- &_parse_voidp, &func,
- &PyTuple_Type, &arguments))
- return NULL;
-
- ctypes_state *st = get_module_state(self);
+ ctypes_state *st = get_module_state(module);
result = _ctypes_callproc(st,
(PPROC)func,
arguments,
@@ -1700,20 +1850,22 @@ call_function(PyObject *self, PyObject *args)
*
* XXX Needs to accept more arguments: flags, argtypes, restype
*/
+/*[clinic input]
+_ctypes.call_cdeclfunction
+
+ func: voidp
+ arguments: object(subclass_of='&PyTuple_Type')
+ /
+[clinic start generated code]*/
+
static PyObject *
-call_cdeclfunction(PyObject *self, PyObject *args)
+_ctypes_call_cdeclfunction_impl(PyObject *module, void *func,
+ PyObject *arguments)
+/*[clinic end generated code: output=697e21ce2e298acd input=bc3260e856aa7416]*/
{
- void *func;
- PyObject *arguments;
PyObject *result;
- if (!PyArg_ParseTuple(args,
- "O&O!",
- &_parse_voidp, &func,
- &PyTuple_Type, &arguments))
- return NULL;
-
- ctypes_state *st = get_module_state(self);
+ ctypes_state *st = get_module_state(module);
result = _ctypes_callproc(st,
(PPROC)func,
arguments,
@@ -1766,15 +1918,22 @@ _ctypes_sizeof(PyObject *module, PyObject *obj)
return NULL;
}
-PyDoc_STRVAR(alignment_doc,
-"alignment(C type) -> integer\n"
-"alignment(C instance) -> integer\n"
-"Return the alignment requirements of a C instance");
+/*[clinic input]
+_ctypes.alignment
+
+ obj: object
+ /
+
+Return the alignment requirements of a C instance.
+
+The argument is a C type or a C instance.
+[clinic start generated code]*/
static PyObject *
-align_func(PyObject *self, PyObject *obj)
+_ctypes_alignment(PyObject *module, PyObject *obj)
+/*[clinic end generated code: output=a7abe04d98641d93 input=3c78c5425bc83928]*/
{
- ctypes_state *st = get_module_state(self);
+ ctypes_state *st = get_module_state(module);
StgInfo *info;
if (PyStgInfo_FromAny(st, obj, &info) < 0) {
return NULL;
@@ -1836,36 +1995,60 @@ _ctypes_addressof_impl(PyObject *module, PyObject *obj)
}
static int
-converter(PyObject *obj, void *arg)
+_parse_voidp_object(PyObject *obj, void *arg)
{
- void **address = (void **)arg;
+ PyObject **address = (PyObject **)arg;
*address = PyLong_AsVoidPtr(obj);
return *address != NULL;
}
+/*[clinic input]
+_ctypes.PyObj_FromPtr
+
+ address as ob: object(converter="_parse_voidp_object")
+ /
+[clinic start generated code]*/
+
static PyObject *
-My_PyObj_FromPtr(PyObject *self, PyObject *args)
+_ctypes_PyObj_FromPtr_impl(PyObject *module, PyObject *ob)
+/*[clinic end generated code: output=225d11c8e84c2926 input=1baea4849458fe7c]*/
{
- PyObject *ob;
- if (!PyArg_ParseTuple(args, "O&:PyObj_FromPtr", converter, &ob)) {
- return NULL;
- }
if (PySys_Audit("ctypes.PyObj_FromPtr", "(O)", ob) < 0) {
return NULL;
}
return Py_NewRef(ob);
}
+/*[clinic input]
+_ctypes.Py_INCREF
+
+ obj as arg: object
+ /
+
+Increment the reference count of the object and return it.
+[clinic start generated code]*/
+
static PyObject *
-My_Py_INCREF(PyObject *self, PyObject *arg)
+_ctypes_Py_INCREF(PyObject *module, PyObject *arg)
+/*[clinic end generated code: output=ebf05a7f9ba69657 input=04fcd9c30fee39ea]*/
{
Py_INCREF(arg); /* that's what this function is for */
Py_INCREF(arg); /* that for returning it */
return arg;
}
+/*[clinic input]
+_ctypes.Py_DECREF
+
+ obj as arg: object
+ /
+
+Decrement the reference count of the object and return it.
+[clinic start generated code]*/
+
static PyObject *
-My_Py_DECREF(PyObject *self, PyObject *arg)
+_ctypes_Py_DECREF(PyObject *module, PyObject *arg)
+/*[clinic end generated code: output=d7933cd7be22ccde input=108543079a732003]*/
{
Py_DECREF(arg); /* that's what this function is for */
Py_INCREF(arg); /* that's for returning it */
@@ -1932,13 +2115,20 @@ _ctypes_resize_impl(PyObject *module, CDataObject *obj, Py_ssize_t size)
Py_RETURN_NONE;
}
+/*[clinic input]
+_ctypes._unpickle
+
+ cls as typ: object
+ state: object(subclass_of='&PyTuple_Type')
+ /
+[clinic start generated code]*/
+
static PyObject *
-unpickle(PyObject *self, PyObject *args)
+_ctypes__unpickle_impl(PyObject *module, PyObject *typ, PyObject *state)
+/*[clinic end generated code: output=358df408ddcf5145 input=1cdb32990e0ef9b8]*/
{
- PyObject *typ, *state, *meth, *obj, *result;
+ PyObject *meth, *obj, *result;
- if (!PyArg_ParseTuple(args, "OO!", &typ, &PyTuple_Type, &state))
- return NULL;
obj = PyObject_CallMethodOneArg(typ, &_Py_ID(__new__), typ);
if (obj == NULL)
return NULL;
@@ -1962,13 +2152,23 @@ unpickle(PyObject *self, PyObject *args)
return NULL;
}
+/*[clinic input]
+_ctypes.buffer_info
+
+ obj as arg: object
+ /
+
+Return buffer interface information.
+[clinic start generated code]*/
+
static PyObject *
-buffer_info(PyObject *self, PyObject *arg)
+_ctypes_buffer_info(PyObject *module, PyObject *arg)
+/*[clinic end generated code: output=31f942a6fce6d671 input=cb023e7f9c959f72]*/
{
PyObject *shape;
Py_ssize_t i;
- ctypes_state *st = get_module_state(self);
+ ctypes_state *st = get_module_state(module);
StgInfo *info;
if (PyStgInfo_FromAny(st, arg, &info) < 0) {
return NULL;
@@ -1993,13 +2193,8 @@ buffer_info(PyObject *self, PyObject *arg)
static PyObject *
-_ctypes_getattr(PyObject *Py_UNUSED(self), PyObject *args)
+_ctypes_getattr(PyObject *Py_UNUSED(module), PyObject *name)
{
- PyObject *name;
- if (!PyArg_UnpackTuple(args, "__getattr__", 1, 1, &name)) {
- return NULL;
- }
-
if (PyUnicode_Check(name) && PyUnicode_EqualToUTF8(name, "__version__")) {
if (PyErr_WarnEx(PyExc_DeprecationWarning,
"'__version__' is deprecated and slated for "
@@ -2017,37 +2212,39 @@ _ctypes_getattr(PyObject *Py_UNUSED(self), PyObject *args)
PyMethodDef _ctypes_module_methods[] = {
- {"__getattr__", _ctypes_getattr, METH_VARARGS},
- {"get_errno", get_errno, METH_NOARGS},
- {"set_errno", set_errno, METH_VARARGS},
- {"_unpickle", unpickle, METH_VARARGS },
- {"buffer_info", buffer_info, METH_O, "Return buffer interface information"},
+ {"__getattr__", _ctypes_getattr, METH_O},
+ _CTYPES_GET_ERRNO_METHODDEF
+ _CTYPES_SET_ERRNO_METHODDEF
+ _CTYPES__UNPICKLE_METHODDEF
+ _CTYPES_BUFFER_INFO_METHODDEF
_CTYPES_RESIZE_METHODDEF
#ifdef MS_WIN32
- {"get_last_error", get_last_error, METH_NOARGS},
- {"set_last_error", set_last_error, METH_VARARGS},
- {"CopyComPointer", copy_com_pointer, METH_VARARGS, copy_com_pointer_doc},
- {"FormatError", format_error, METH_VARARGS, format_error_doc},
- {"LoadLibrary", load_library, METH_VARARGS, load_library_doc},
- {"FreeLibrary", free_library, METH_VARARGS, free_library_doc},
- {"_check_HRESULT", check_hresult, METH_VARARGS},
+ _CTYPES_GET_LAST_ERROR_METHODDEF
+ _CTYPES_SET_LAST_ERROR_METHODDEF
+ _CTYPES_COPYCOMPOINTER_METHODDEF
+ _CTYPES_FORMATERROR_METHODDEF
+ _CTYPES_LOADLIBRARY_METHODDEF
+ _CTYPES_FREELIBRARY_METHODDEF
+ _CTYPES__CHECK_HRESULT_METHODDEF
#else
- {"dlopen", py_dl_open, METH_VARARGS,
- "dlopen(name, flag={RTLD_GLOBAL|RTLD_LOCAL}) open a shared library"},
- {"dlclose", py_dl_close, METH_VARARGS, "dlclose a library"},
- {"dlsym", py_dl_sym, METH_VARARGS, "find symbol in shared library"},
+ _CTYPES_DLOPEN_METHODDEF
+ _CTYPES_DLCLOSE_METHODDEF
+ _CTYPES_DLSYM_METHODDEF
+#if defined(HAVE_DL_ITERATE_PHDR) && !defined(__APPLE__)
+ _CTYPES_DLLIST_METHODDEF
+#endif
#endif
#ifdef __APPLE__
- {"_dyld_shared_cache_contains_path", py_dyld_shared_cache_contains_path, METH_VARARGS, "check if path is in the shared cache"},
+ _CTYPES__DYLD_SHARED_CACHE_CONTAINS_PATH_METHODDEF
#endif
- {"alignment", align_func, METH_O, alignment_doc},
+ _CTYPES_ALIGNMENT_METHODDEF
_CTYPES_SIZEOF_METHODDEF
_CTYPES_BYREF_METHODDEF
_CTYPES_ADDRESSOF_METHODDEF
- {"call_function", call_function, METH_VARARGS },
- {"call_cdeclfunction", call_cdeclfunction, METH_VARARGS },
- {"PyObj_FromPtr", My_PyObj_FromPtr, METH_VARARGS },
- {"Py_INCREF", My_Py_INCREF, METH_O },
- {"Py_DECREF", My_Py_DECREF, METH_O },
+ _CTYPES_CALL_FUNCTION_METHODDEF
+ _CTYPES_CALL_CDECLFUNCTION_METHODDEF
+ _CTYPES_PYOBJ_FROMPTR_METHODDEF
+ _CTYPES_PY_INCREF_METHODDEF
+ _CTYPES_PY_DECREF_METHODDEF
{NULL, NULL} /* Sentinel */
};
diff --git a/Modules/_ctypes/cfield.c b/Modules/_ctypes/cfield.c
index 00b075bccff6647..193c60a1afee85c 100644
--- a/Modules/_ctypes/cfield.c
+++ b/Modules/_ctypes/cfield.c
@@ -865,14 +865,14 @@ Zf_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
return NULL;
}
#ifdef WORDS_BIGENDIAN
- if (PyFloat_Pack4(c.real, ptr, 1)
- || PyFloat_Pack4(c.imag, ptr + sizeof(float), 1))
+ if (PyFloat_Pack4((float)c.real, ptr, 1)
+ || PyFloat_Pack4((float)c.imag, ptr + sizeof(float), 1))
{
return NULL;
}
#else
- if (PyFloat_Pack4(c.real, ptr, 0)
- || PyFloat_Pack4(c.imag, ptr + sizeof(float), 0))
+ if (PyFloat_Pack4((float)c.real, ptr, 0)
+ || PyFloat_Pack4((float)c.imag, ptr + sizeof(float), 0))
{
return NULL;
}
diff --git a/Modules/_ctypes/clinic/_ctypes.c.h b/Modules/_ctypes/clinic/_ctypes.c.h
index 529872f0f17ebe9..7a3c4bba9fc2090 100644
--- a/Modules/_ctypes/clinic/_ctypes.c.h
+++ b/Modules/_ctypes/clinic/_ctypes.c.h
@@ -2,12 +2,10 @@
preserve
[clinic start generated code]*/
-#if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
-# include "pycore_runtime.h" // _Py_SINGLETON()
-#endif
#include "pycore_abstract.h" // _PyNumber_Index()
#include "pycore_critical_section.h"// Py_BEGIN_CRITICAL_SECTION()
-#include "pycore_modsupport.h" // _PyArg_UnpackKeywords()
+#include "pycore_modsupport.h" // _PyArg_CheckPositional()
+#include "pycore_unicodeobject.h" // _PyUnicode_AsUTF8NoNUL()
PyDoc_STRVAR(_ctypes_CType_Type___sizeof____doc__,
"__sizeof__($self, /)\n"
@@ -31,16 +29,6 @@ _ctypes_CType_Type___sizeof__(PyObject *self, PyTypeObject *cls, PyObject *const
return _ctypes_CType_Type___sizeof___impl(self, cls);
}
-#if !defined(_ctypes_CType_Type___pointer_type___DOCSTR)
-# define _ctypes_CType_Type___pointer_type___DOCSTR NULL
-#endif
-#if defined(_CTYPES_CTYPE_TYPE___POINTER_TYPE___GETSETDEF)
-# undef _CTYPES_CTYPE_TYPE___POINTER_TYPE___GETSETDEF
-# define _CTYPES_CTYPE_TYPE___POINTER_TYPE___GETSETDEF {"__pointer_type__", (getter)_ctypes_CType_Type___pointer_type___get, (setter)_ctypes_CType_Type___pointer_type___set, _ctypes_CType_Type___pointer_type___DOCSTR},
-#else
-# define _CTYPES_CTYPE_TYPE___POINTER_TYPE___GETSETDEF {"__pointer_type__", (getter)_ctypes_CType_Type___pointer_type___get, NULL, _ctypes_CType_Type___pointer_type___DOCSTR},
-#endif
-
static PyObject *
_ctypes_CType_Type___pointer_type___get_impl(PyObject *self);
@@ -50,24 +38,18 @@ _ctypes_CType_Type___pointer_type___get(PyObject *self, void *Py_UNUSED(context)
return _ctypes_CType_Type___pointer_type___get_impl(self);
}
-#if !defined(_ctypes_CType_Type___pointer_type___DOCSTR)
-# define _ctypes_CType_Type___pointer_type___DOCSTR NULL
-#endif
-#if defined(_CTYPES_CTYPE_TYPE___POINTER_TYPE___GETSETDEF)
-# undef _CTYPES_CTYPE_TYPE___POINTER_TYPE___GETSETDEF
-# define _CTYPES_CTYPE_TYPE___POINTER_TYPE___GETSETDEF {"__pointer_type__", (getter)_ctypes_CType_Type___pointer_type___get, (setter)_ctypes_CType_Type___pointer_type___set, _ctypes_CType_Type___pointer_type___DOCSTR},
-#else
-# define _CTYPES_CTYPE_TYPE___POINTER_TYPE___GETSETDEF {"__pointer_type__", NULL, (setter)_ctypes_CType_Type___pointer_type___set, NULL},
-#endif
-
static int
_ctypes_CType_Type___pointer_type___set_impl(PyObject *self, PyObject *value);
static int
-_ctypes_CType_Type___pointer_type___set(PyObject *self, PyObject *value, void *Py_UNUSED(context))
+_ctypes_CType_Type___pointer_type___set(PyObject *self, PyObject *arg, void *Py_UNUSED(context))
{
- int return_value;
+ int return_value = -1;
+ PyObject *value = NULL;
+ if (arg != NULL) {
+ value = arg;
+ }
return_value = _ctypes_CType_Type___pointer_type___set_impl(self, value);
return return_value;
@@ -92,25 +74,12 @@ static PyObject *
CDataType_from_address(PyObject *type, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "from_address",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *value;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("from_address", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("from_address", nargs, 1, 1)) {
goto exit;
}
value = args[0];
@@ -139,31 +108,18 @@ static PyObject *
CDataType_from_buffer(PyObject *type, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", "", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "from_buffer",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[2];
PyObject *obj;
Py_ssize_t offset = 0;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 2, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("from_buffer", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("from_buffer", nargs, 1, 2)) {
goto exit;
}
obj = args[0];
if (nargs < 2) {
- goto skip_optional_posonly;
+ goto skip_optional;
}
{
Py_ssize_t ival = -1;
@@ -182,7 +138,7 @@ CDataType_from_buffer(PyObject *type, PyTypeObject *cls, PyObject *const *args,
goto exit;
}
}
-skip_optional_posonly:
+skip_optional:
return_value = CDataType_from_buffer_impl(type, cls, obj, offset);
exit:
@@ -208,33 +164,20 @@ static PyObject *
CDataType_from_buffer_copy(PyObject *type, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", "", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "from_buffer_copy",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[2];
Py_buffer buffer = {NULL, NULL};
Py_ssize_t offset = 0;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 2, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("from_buffer_copy", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("from_buffer_copy", nargs, 1, 2)) {
goto exit;
}
if (PyObject_GetBuffer(args[0], &buffer, PyBUF_SIMPLE) != 0) {
goto exit;
}
if (nargs < 2) {
- goto skip_optional_posonly;
+ goto skip_optional;
}
{
Py_ssize_t ival = -1;
@@ -253,7 +196,7 @@ CDataType_from_buffer_copy(PyObject *type, PyTypeObject *cls, PyObject *const *a
goto exit;
}
}
-skip_optional_posonly:
+skip_optional:
return_value = CDataType_from_buffer_copy_impl(type, cls, &buffer, offset);
exit:
@@ -284,26 +227,13 @@ static PyObject *
CDataType_in_dll(PyObject *type, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", "", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "in_dll",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[2];
PyObject *dll;
const char *name;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 2, /*maxpos*/ 2, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("in_dll", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("in_dll", nargs, 2, 2)) {
goto exit;
}
dll = args[0];
@@ -311,15 +241,10 @@ CDataType_in_dll(PyObject *type, PyTypeObject *cls, PyObject *const *args, Py_ss
_PyArg_BadArgument("in_dll", "argument 2", "str", args[1]);
goto exit;
}
- Py_ssize_t name_length;
- name = PyUnicode_AsUTF8AndSize(args[1], &name_length);
+ name = _PyUnicode_AsUTF8NoNUL(args[1]);
if (name == NULL) {
goto exit;
}
- if (strlen(name) != (size_t)name_length) {
- PyErr_SetString(PyExc_ValueError, "embedded null character");
- goto exit;
- }
return_value = CDataType_in_dll_impl(type, cls, dll, name);
exit:
@@ -342,25 +267,12 @@ static PyObject *
CDataType_from_param(PyObject *type, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "from_param",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *value;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("from_param", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("from_param", nargs, 1, 1)) {
goto exit;
}
value = args[0];
@@ -386,25 +298,12 @@ static PyObject *
PyCPointerType_set_type(PyObject *self, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "set_type",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *type;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("set_type", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("set_type", nargs, 1, 1)) {
goto exit;
}
type = args[0];
@@ -431,25 +330,12 @@ static PyObject *
PyCPointerType_from_param(PyObject *type, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "from_param",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *value;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("from_param", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("from_param", nargs, 1, 1)) {
goto exit;
}
value = args[0];
@@ -459,41 +345,37 @@ PyCPointerType_from_param(PyObject *type, PyTypeObject *cls, PyObject *const *ar
return return_value;
}
-#if !defined(_ctypes_PyCArrayType_Type_raw_DOCSTR)
-# define _ctypes_PyCArrayType_Type_raw_DOCSTR NULL
-#endif
-#if defined(_CTYPES_PYCARRAYTYPE_TYPE_RAW_GETSETDEF)
-# undef _CTYPES_PYCARRAYTYPE_TYPE_RAW_GETSETDEF
-# define _CTYPES_PYCARRAYTYPE_TYPE_RAW_GETSETDEF {"raw", (getter)_ctypes_PyCArrayType_Type_raw_get, (setter)_ctypes_PyCArrayType_Type_raw_set, _ctypes_PyCArrayType_Type_raw_DOCSTR},
-#else
-# define _CTYPES_PYCARRAYTYPE_TYPE_RAW_GETSETDEF {"raw", NULL, (setter)_ctypes_PyCArrayType_Type_raw_set, NULL},
-#endif
-
static int
-_ctypes_PyCArrayType_Type_raw_set_impl(CDataObject *self, PyObject *value);
+_ctypes_PyCArrayType_Type_raw_set_impl(CDataObject *self, Py_buffer *value);
static int
-_ctypes_PyCArrayType_Type_raw_set(PyObject *self, PyObject *value, void *Py_UNUSED(context))
+_ctypes_PyCArrayType_Type_raw_set(PyObject *self, PyObject *arg, void *Py_UNUSED(context))
{
- int return_value;
-
+ int return_value = -1;
+ Py_buffer value = {NULL, NULL};
+
+ if (arg == NULL) {
+ PyErr_Format(PyExc_AttributeError,
+ "attribute 'raw' of '%.100s' objects cannot be deleted",
+ Py_TYPE(self)->tp_name);
+ return -1;
+ }
+ if (PyObject_GetBuffer(arg, &value, PyBUF_SIMPLE) != 0) {
+ goto exit;
+ }
Py_BEGIN_CRITICAL_SECTION(self);
- return_value = _ctypes_PyCArrayType_Type_raw_set_impl((CDataObject *)self, value);
+ return_value = _ctypes_PyCArrayType_Type_raw_set_impl((CDataObject *)self, &value);
Py_END_CRITICAL_SECTION();
+exit:
+ /* Cleanup for value */
+ if (value.obj) {
+ PyBuffer_Release(&value);
+ }
+
return return_value;
}
-#if !defined(_ctypes_PyCArrayType_Type_raw_DOCSTR)
-# define _ctypes_PyCArrayType_Type_raw_DOCSTR NULL
-#endif
-#if defined(_CTYPES_PYCARRAYTYPE_TYPE_RAW_GETSETDEF)
-# undef _CTYPES_PYCARRAYTYPE_TYPE_RAW_GETSETDEF
-# define _CTYPES_PYCARRAYTYPE_TYPE_RAW_GETSETDEF {"raw", (getter)_ctypes_PyCArrayType_Type_raw_get, (setter)_ctypes_PyCArrayType_Type_raw_set, _ctypes_PyCArrayType_Type_raw_DOCSTR},
-#else
-# define _CTYPES_PYCARRAYTYPE_TYPE_RAW_GETSETDEF {"raw", (getter)_ctypes_PyCArrayType_Type_raw_get, NULL, _ctypes_PyCArrayType_Type_raw_DOCSTR},
-#endif
-
static PyObject *
_ctypes_PyCArrayType_Type_raw_get_impl(CDataObject *self);
@@ -509,16 +391,6 @@ _ctypes_PyCArrayType_Type_raw_get(PyObject *self, void *Py_UNUSED(context))
return return_value;
}
-#if !defined(_ctypes_PyCArrayType_Type_value_DOCSTR)
-# define _ctypes_PyCArrayType_Type_value_DOCSTR NULL
-#endif
-#if defined(_CTYPES_PYCARRAYTYPE_TYPE_VALUE_GETSETDEF)
-# undef _CTYPES_PYCARRAYTYPE_TYPE_VALUE_GETSETDEF
-# define _CTYPES_PYCARRAYTYPE_TYPE_VALUE_GETSETDEF {"value", (getter)_ctypes_PyCArrayType_Type_value_get, (setter)_ctypes_PyCArrayType_Type_value_set, _ctypes_PyCArrayType_Type_value_DOCSTR},
-#else
-# define _CTYPES_PYCARRAYTYPE_TYPE_VALUE_GETSETDEF {"value", (getter)_ctypes_PyCArrayType_Type_value_get, NULL, _ctypes_PyCArrayType_Type_value_DOCSTR},
-#endif
-
static PyObject *
_ctypes_PyCArrayType_Type_value_get_impl(CDataObject *self);
@@ -534,28 +406,32 @@ _ctypes_PyCArrayType_Type_value_get(PyObject *self, void *Py_UNUSED(context))
return return_value;
}
-#if !defined(_ctypes_PyCArrayType_Type_value_DOCSTR)
-# define _ctypes_PyCArrayType_Type_value_DOCSTR NULL
-#endif
-#if defined(_CTYPES_PYCARRAYTYPE_TYPE_VALUE_GETSETDEF)
-# undef _CTYPES_PYCARRAYTYPE_TYPE_VALUE_GETSETDEF
-# define _CTYPES_PYCARRAYTYPE_TYPE_VALUE_GETSETDEF {"value", (getter)_ctypes_PyCArrayType_Type_value_get, (setter)_ctypes_PyCArrayType_Type_value_set, _ctypes_PyCArrayType_Type_value_DOCSTR},
-#else
-# define _CTYPES_PYCARRAYTYPE_TYPE_VALUE_GETSETDEF {"value", NULL, (setter)_ctypes_PyCArrayType_Type_value_set, NULL},
-#endif
-
static int
-_ctypes_PyCArrayType_Type_value_set_impl(CDataObject *self, PyObject *value);
+_ctypes_PyCArrayType_Type_value_set_impl(CDataObject *self,
+ PyBytesObject *value);
static int
-_ctypes_PyCArrayType_Type_value_set(PyObject *self, PyObject *value, void *Py_UNUSED(context))
+_ctypes_PyCArrayType_Type_value_set(PyObject *self, PyObject *arg, void *Py_UNUSED(context))
{
- int return_value;
-
+ int return_value = -1;
+ PyBytesObject *value;
+
+ if (arg == NULL) {
+ PyErr_Format(PyExc_AttributeError,
+ "attribute 'value' of '%.100s' objects cannot be deleted",
+ Py_TYPE(self)->tp_name);
+ return -1;
+ }
+ if (!PyBytes_Check(arg)) {
+ PyErr_Format(PyExc_TypeError, "attribute 'value' must be bytes, not %T", arg);
+ goto exit;
+ }
+ value = (PyBytesObject *)arg;
Py_BEGIN_CRITICAL_SECTION(self);
return_value = _ctypes_PyCArrayType_Type_value_set_impl((CDataObject *)self, value);
Py_END_CRITICAL_SECTION();
+exit:
return return_value;
}
@@ -574,25 +450,12 @@ static PyObject *
c_wchar_p_from_param(PyObject *type, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "from_param",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *value;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("from_param", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("from_param", nargs, 1, 1)) {
goto exit;
}
value = args[0];
@@ -617,25 +480,12 @@ static PyObject *
c_char_p_from_param(PyObject *type, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "from_param",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *value;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("from_param", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("from_param", nargs, 1, 1)) {
goto exit;
}
value = args[0];
@@ -660,25 +510,12 @@ static PyObject *
c_void_p_from_param(PyObject *type, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "from_param",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *value;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("from_param", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("from_param", nargs, 1, 1)) {
goto exit;
}
value = args[0];
@@ -705,25 +542,12 @@ static PyObject *
PyCSimpleType_from_param(PyObject *type, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "from_param",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *value;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("from_param", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("from_param", nargs, 1, 1)) {
goto exit;
}
value = args[0];
@@ -781,7 +605,7 @@ _ctypes_PyCData___setstate__(PyObject *myself, PyObject *const *args, Py_ssize_t
const char *data;
Py_ssize_t data_length;
- if (!_PyArg_ParseStack(args, nargs, "O!s#:__setstate__",
+ if (!PyArg_ParseArray(args, nargs, "O!s#:__setstate__",
&PyDict_Type, &dict, &data, &data_length)) {
goto exit;
}
@@ -811,24 +635,18 @@ _ctypes_PyCData___ctypes_from_outparam__(PyObject *self, PyObject *Py_UNUSED(ign
return _ctypes_PyCData___ctypes_from_outparam___impl(self);
}
-#if !defined(_ctypes_CFuncPtr_errcheck_DOCSTR)
-# define _ctypes_CFuncPtr_errcheck_DOCSTR NULL
-#endif
-#if defined(_CTYPES_CFUNCPTR_ERRCHECK_GETSETDEF)
-# undef _CTYPES_CFUNCPTR_ERRCHECK_GETSETDEF
-# define _CTYPES_CFUNCPTR_ERRCHECK_GETSETDEF {"errcheck", (getter)_ctypes_CFuncPtr_errcheck_get, (setter)_ctypes_CFuncPtr_errcheck_set, _ctypes_CFuncPtr_errcheck_DOCSTR},
-#else
-# define _CTYPES_CFUNCPTR_ERRCHECK_GETSETDEF {"errcheck", NULL, (setter)_ctypes_CFuncPtr_errcheck_set, NULL},
-#endif
-
static int
_ctypes_CFuncPtr_errcheck_set_impl(PyCFuncPtrObject *self, PyObject *value);
static int
-_ctypes_CFuncPtr_errcheck_set(PyObject *self, PyObject *value, void *Py_UNUSED(context))
+_ctypes_CFuncPtr_errcheck_set(PyObject *self, PyObject *arg, void *Py_UNUSED(context))
{
- int return_value;
+ int return_value = -1;
+ PyObject *value = NULL;
+ if (arg != NULL) {
+ value = arg;
+ }
Py_BEGIN_CRITICAL_SECTION(self);
return_value = _ctypes_CFuncPtr_errcheck_set_impl((PyCFuncPtrObject *)self, value);
Py_END_CRITICAL_SECTION();
@@ -838,20 +656,6 @@ _ctypes_CFuncPtr_errcheck_set(PyObject *self, PyObject *value, void *Py_UNUSED(c
PyDoc_STRVAR(_ctypes_CFuncPtr_errcheck__doc__,
"a function to check for errors");
-#if defined(_ctypes_CFuncPtr_errcheck_DOCSTR)
-# undef _ctypes_CFuncPtr_errcheck_DOCSTR
-#endif
-#define _ctypes_CFuncPtr_errcheck_DOCSTR _ctypes_CFuncPtr_errcheck__doc__
-
-#if !defined(_ctypes_CFuncPtr_errcheck_DOCSTR)
-# define _ctypes_CFuncPtr_errcheck_DOCSTR NULL
-#endif
-#if defined(_CTYPES_CFUNCPTR_ERRCHECK_GETSETDEF)
-# undef _CTYPES_CFUNCPTR_ERRCHECK_GETSETDEF
-# define _CTYPES_CFUNCPTR_ERRCHECK_GETSETDEF {"errcheck", (getter)_ctypes_CFuncPtr_errcheck_get, (setter)_ctypes_CFuncPtr_errcheck_set, _ctypes_CFuncPtr_errcheck_DOCSTR},
-#else
-# define _CTYPES_CFUNCPTR_ERRCHECK_GETSETDEF {"errcheck", (getter)_ctypes_CFuncPtr_errcheck_get, NULL, _ctypes_CFuncPtr_errcheck_DOCSTR},
-#endif
static PyObject *
_ctypes_CFuncPtr_errcheck_get_impl(PyCFuncPtrObject *self);
@@ -868,24 +672,18 @@ _ctypes_CFuncPtr_errcheck_get(PyObject *self, void *Py_UNUSED(context))
return return_value;
}
-#if !defined(_ctypes_CFuncPtr_restype_DOCSTR)
-# define _ctypes_CFuncPtr_restype_DOCSTR NULL
-#endif
-#if defined(_CTYPES_CFUNCPTR_RESTYPE_GETSETDEF)
-# undef _CTYPES_CFUNCPTR_RESTYPE_GETSETDEF
-# define _CTYPES_CFUNCPTR_RESTYPE_GETSETDEF {"restype", (getter)_ctypes_CFuncPtr_restype_get, (setter)_ctypes_CFuncPtr_restype_set, _ctypes_CFuncPtr_restype_DOCSTR},
-#else
-# define _CTYPES_CFUNCPTR_RESTYPE_GETSETDEF {"restype", NULL, (setter)_ctypes_CFuncPtr_restype_set, NULL},
-#endif
-
static int
_ctypes_CFuncPtr_restype_set_impl(PyCFuncPtrObject *self, PyObject *value);
static int
-_ctypes_CFuncPtr_restype_set(PyObject *self, PyObject *value, void *Py_UNUSED(context))
+_ctypes_CFuncPtr_restype_set(PyObject *self, PyObject *arg, void *Py_UNUSED(context))
{
- int return_value;
+ int return_value = -1;
+ PyObject *value = NULL;
+ if (arg != NULL) {
+ value = arg;
+ }
Py_BEGIN_CRITICAL_SECTION(self);
return_value = _ctypes_CFuncPtr_restype_set_impl((PyCFuncPtrObject *)self, value);
Py_END_CRITICAL_SECTION();
@@ -895,20 +693,6 @@ _ctypes_CFuncPtr_restype_set(PyObject *self, PyObject *value, void *Py_UNUSED(co
PyDoc_STRVAR(_ctypes_CFuncPtr_restype__doc__,
"specify the result type");
-#if defined(_ctypes_CFuncPtr_restype_DOCSTR)
-# undef _ctypes_CFuncPtr_restype_DOCSTR
-#endif
-#define _ctypes_CFuncPtr_restype_DOCSTR _ctypes_CFuncPtr_restype__doc__
-
-#if !defined(_ctypes_CFuncPtr_restype_DOCSTR)
-# define _ctypes_CFuncPtr_restype_DOCSTR NULL
-#endif
-#if defined(_CTYPES_CFUNCPTR_RESTYPE_GETSETDEF)
-# undef _CTYPES_CFUNCPTR_RESTYPE_GETSETDEF
-# define _CTYPES_CFUNCPTR_RESTYPE_GETSETDEF {"restype", (getter)_ctypes_CFuncPtr_restype_get, (setter)_ctypes_CFuncPtr_restype_set, _ctypes_CFuncPtr_restype_DOCSTR},
-#else
-# define _CTYPES_CFUNCPTR_RESTYPE_GETSETDEF {"restype", (getter)_ctypes_CFuncPtr_restype_get, NULL, _ctypes_CFuncPtr_restype_DOCSTR},
-#endif
static PyObject *
_ctypes_CFuncPtr_restype_get_impl(PyCFuncPtrObject *self);
@@ -925,24 +709,18 @@ _ctypes_CFuncPtr_restype_get(PyObject *self, void *Py_UNUSED(context))
return return_value;
}
-#if !defined(_ctypes_CFuncPtr_argtypes_DOCSTR)
-# define _ctypes_CFuncPtr_argtypes_DOCSTR NULL
-#endif
-#if defined(_CTYPES_CFUNCPTR_ARGTYPES_GETSETDEF)
-# undef _CTYPES_CFUNCPTR_ARGTYPES_GETSETDEF
-# define _CTYPES_CFUNCPTR_ARGTYPES_GETSETDEF {"argtypes", (getter)_ctypes_CFuncPtr_argtypes_get, (setter)_ctypes_CFuncPtr_argtypes_set, _ctypes_CFuncPtr_argtypes_DOCSTR},
-#else
-# define _CTYPES_CFUNCPTR_ARGTYPES_GETSETDEF {"argtypes", NULL, (setter)_ctypes_CFuncPtr_argtypes_set, NULL},
-#endif
-
static int
_ctypes_CFuncPtr_argtypes_set_impl(PyCFuncPtrObject *self, PyObject *value);
static int
-_ctypes_CFuncPtr_argtypes_set(PyObject *self, PyObject *value, void *Py_UNUSED(context))
+_ctypes_CFuncPtr_argtypes_set(PyObject *self, PyObject *arg, void *Py_UNUSED(context))
{
- int return_value;
+ int return_value = -1;
+ PyObject *value = NULL;
+ if (arg != NULL) {
+ value = arg;
+ }
Py_BEGIN_CRITICAL_SECTION(self);
return_value = _ctypes_CFuncPtr_argtypes_set_impl((PyCFuncPtrObject *)self, value);
Py_END_CRITICAL_SECTION();
@@ -952,20 +730,6 @@ _ctypes_CFuncPtr_argtypes_set(PyObject *self, PyObject *value, void *Py_UNUSED(c
PyDoc_STRVAR(_ctypes_CFuncPtr_argtypes__doc__,
"specify the argument types");
-#if defined(_ctypes_CFuncPtr_argtypes_DOCSTR)
-# undef _ctypes_CFuncPtr_argtypes_DOCSTR
-#endif
-#define _ctypes_CFuncPtr_argtypes_DOCSTR _ctypes_CFuncPtr_argtypes__doc__
-
-#if !defined(_ctypes_CFuncPtr_argtypes_DOCSTR)
-# define _ctypes_CFuncPtr_argtypes_DOCSTR NULL
-#endif
-#if defined(_CTYPES_CFUNCPTR_ARGTYPES_GETSETDEF)
-# undef _CTYPES_CFUNCPTR_ARGTYPES_GETSETDEF
-# define _CTYPES_CFUNCPTR_ARGTYPES_GETSETDEF {"argtypes", (getter)_ctypes_CFuncPtr_argtypes_get, (setter)_ctypes_CFuncPtr_argtypes_set, _ctypes_CFuncPtr_argtypes_DOCSTR},
-#else
-# define _CTYPES_CFUNCPTR_ARGTYPES_GETSETDEF {"argtypes", (getter)_ctypes_CFuncPtr_argtypes_get, NULL, _ctypes_CFuncPtr_argtypes_DOCSTR},
-#endif
static PyObject *
_ctypes_CFuncPtr_argtypes_get_impl(PyCFuncPtrObject *self);
@@ -982,24 +746,82 @@ _ctypes_CFuncPtr_argtypes_get(PyObject *self, void *Py_UNUSED(context))
return return_value;
}
-#if !defined(_ctypes_Simple_value_DOCSTR)
-# define _ctypes_Simple_value_DOCSTR NULL
-#endif
-#if defined(_CTYPES_SIMPLE_VALUE_GETSETDEF)
-# undef _CTYPES_SIMPLE_VALUE_GETSETDEF
-# define _CTYPES_SIMPLE_VALUE_GETSETDEF {"value", (getter)_ctypes_Simple_value_get, (setter)_ctypes_Simple_value_set, _ctypes_Simple_value_DOCSTR},
-#else
-# define _CTYPES_SIMPLE_VALUE_GETSETDEF {"value", NULL, (setter)_ctypes_Simple_value_set, NULL},
-#endif
+static PyObject *
+Array_item_impl(PyObject *myself, Py_ssize_t index);
+
+static PyObject *
+Array_item(PyObject *myself, Py_ssize_t index)
+{
+ PyObject *return_value = NULL;
+
+ Py_BEGIN_CRITICAL_SECTION(myself);
+ return_value = Array_item_impl(myself, index);
+ Py_END_CRITICAL_SECTION();
+
+ return return_value;
+}
+
+static PyObject *
+Array_subscript_impl(PyObject *myself, PyObject *item);
+
+static PyObject *
+Array_subscript(PyObject *myself, PyObject *item)
+{
+ PyObject *return_value = NULL;
+
+ Py_BEGIN_CRITICAL_SECTION(myself);
+ return_value = Array_subscript_impl(myself, item);
+ Py_END_CRITICAL_SECTION();
+
+ return return_value;
+}
+
+static int
+Array_ass_item_impl(PyObject *myself, Py_ssize_t index, PyObject *value);
+
+static int
+Array_ass_item(PyObject *myself, Py_ssize_t index, PyObject *value)
+{
+ int return_value = -1;
+
+ Py_BEGIN_CRITICAL_SECTION(myself);
+ return_value = Array_ass_item_impl(myself, index, value);
+ Py_END_CRITICAL_SECTION();
+
+ return return_value;
+}
+
+static int
+Array_ass_subscript_impl(PyObject *myself, PyObject *item, PyObject *value);
+
+static int
+Array_ass_subscript(PyObject *myself, PyObject *item, PyObject *value)
+{
+ int return_value = -1;
+
+ Py_BEGIN_CRITICAL_SECTION(myself);
+ return_value = Array_ass_subscript_impl(myself, item, value);
+ Py_END_CRITICAL_SECTION();
+
+ return return_value;
+}
static int
_ctypes_Simple_value_set_impl(CDataObject *self, PyObject *value);
static int
-_ctypes_Simple_value_set(PyObject *self, PyObject *value, void *Py_UNUSED(context))
+_ctypes_Simple_value_set(PyObject *self, PyObject *arg, void *Py_UNUSED(context))
{
- int return_value;
+ int return_value = -1;
+ PyObject *value;
+ if (arg == NULL) {
+ PyErr_Format(PyExc_AttributeError,
+ "attribute 'value' of '%.100s' objects cannot be deleted",
+ Py_TYPE(self)->tp_name);
+ return -1;
+ }
+ value = arg;
Py_BEGIN_CRITICAL_SECTION(self);
return_value = _ctypes_Simple_value_set_impl((CDataObject *)self, value);
Py_END_CRITICAL_SECTION();
@@ -1007,16 +829,6 @@ _ctypes_Simple_value_set(PyObject *self, PyObject *value, void *Py_UNUSED(contex
return return_value;
}
-#if !defined(_ctypes_Simple_value_DOCSTR)
-# define _ctypes_Simple_value_DOCSTR NULL
-#endif
-#if defined(_CTYPES_SIMPLE_VALUE_GETSETDEF)
-# undef _CTYPES_SIMPLE_VALUE_GETSETDEF
-# define _CTYPES_SIMPLE_VALUE_GETSETDEF {"value", (getter)_ctypes_Simple_value_get, (setter)_ctypes_Simple_value_set, _ctypes_Simple_value_DOCSTR},
-#else
-# define _CTYPES_SIMPLE_VALUE_GETSETDEF {"value", (getter)_ctypes_Simple_value_get, NULL, _ctypes_Simple_value_DOCSTR},
-#endif
-
static PyObject *
_ctypes_Simple_value_get_impl(CDataObject *self);
@@ -1052,4 +864,78 @@ Simple_from_outparm(PyObject *self, PyTypeObject *cls, PyObject *const *args, Py
}
return Simple_from_outparm_impl(self, cls);
}
-/*[clinic end generated code: output=22105663d71237ca input=a9049054013a1b77]*/
+
+static int
+Simple_bool_impl(CDataObject *self);
+
+static int
+Simple_bool(PyObject *self)
+{
+ int return_value = -1;
+
+ Py_BEGIN_CRITICAL_SECTION(self);
+ return_value = Simple_bool_impl((CDataObject *)self);
+ Py_END_CRITICAL_SECTION();
+
+ return return_value;
+}
+
+static PyObject *
+Pointer_item_impl(PyObject *myself, Py_ssize_t index);
+
+static PyObject *
+Pointer_item(PyObject *myself, Py_ssize_t index)
+{
+ PyObject *return_value = NULL;
+
+ Py_BEGIN_CRITICAL_SECTION(myself);
+ return_value = Pointer_item_impl(myself, index);
+ Py_END_CRITICAL_SECTION();
+
+ return return_value;
+}
+
+static int
+Pointer_ass_item_impl(PyObject *myself, Py_ssize_t index, PyObject *value);
+
+static int
+Pointer_ass_item(PyObject *myself, Py_ssize_t index, PyObject *value)
+{
+ int return_value = -1;
+
+ Py_BEGIN_CRITICAL_SECTION(myself);
+ return_value = Pointer_ass_item_impl(myself, index, value);
+ Py_END_CRITICAL_SECTION();
+
+ return return_value;
+}
+
+static int
+Pointer_bool_impl(PyObject *self);
+
+static int
+Pointer_bool(PyObject *self)
+{
+ int return_value = -1;
+
+ Py_BEGIN_CRITICAL_SECTION(self);
+ return_value = Pointer_bool_impl(self);
+ Py_END_CRITICAL_SECTION();
+
+ return return_value;
+}
+#define _CTYPES_CTYPE_TYPE___POINTER_TYPE___GETSETDEF {"__pointer_type__", (getter)_ctypes_CType_Type___pointer_type___get, (setter)_ctypes_CType_Type___pointer_type___set, NULL},
+
+#define _CTYPES_PYCARRAYTYPE_TYPE_RAW_GETSETDEF {"raw", (getter)_ctypes_PyCArrayType_Type_raw_get, (setter)_ctypes_PyCArrayType_Type_raw_set, NULL},
+
+#define _CTYPES_PYCARRAYTYPE_TYPE_VALUE_GETSETDEF {"value", (getter)_ctypes_PyCArrayType_Type_value_get, (setter)_ctypes_PyCArrayType_Type_value_set, NULL},
+
+#define _CTYPES_CFUNCPTR_ERRCHECK_GETSETDEF {"errcheck", (getter)_ctypes_CFuncPtr_errcheck_get, (setter)_ctypes_CFuncPtr_errcheck_set, _ctypes_CFuncPtr_errcheck__doc__},
+
+#define _CTYPES_CFUNCPTR_RESTYPE_GETSETDEF {"restype", (getter)_ctypes_CFuncPtr_restype_get, (setter)_ctypes_CFuncPtr_restype_set, _ctypes_CFuncPtr_restype__doc__},
+
+#define _CTYPES_CFUNCPTR_ARGTYPES_GETSETDEF {"argtypes", (getter)_ctypes_CFuncPtr_argtypes_get, (setter)_ctypes_CFuncPtr_argtypes_set, _ctypes_CFuncPtr_argtypes__doc__},
+
+#define _CTYPES_SIMPLE_VALUE_GETSETDEF {"value", (getter)_ctypes_Simple_value_get, (setter)_ctypes_Simple_value_set, NULL},
+
+/*[clinic end generated code: output=5d9dd4bbae13cfca input=a9049054013a1b77]*/
diff --git a/Modules/_ctypes/clinic/callproc.c.h b/Modules/_ctypes/clinic/callproc.c.h
index e0cfcc6f38def7e..82cb08ff00dfb03 100644
--- a/Modules/_ctypes/clinic/callproc.c.h
+++ b/Modules/_ctypes/clinic/callproc.c.h
@@ -5,6 +5,512 @@ preserve
#include "pycore_abstract.h" // _PyNumber_Index()
#include "pycore_critical_section.h"// Py_BEGIN_CRITICAL_SECTION()
#include "pycore_modsupport.h" // _PyArg_CheckPositional()
+#include "pycore_unicodeobject.h" // _PyUnicode_AsUTF8NoNUL()
+
+PyDoc_STRVAR(_ctypes_get_errno__doc__,
+"get_errno($module, /)\n"
+"--\n"
+"\n"
+"Return the current value of the ctypes-private copy of errno.");
+
+#define _CTYPES_GET_ERRNO_METHODDEF \
+ {"get_errno", (PyCFunction)_ctypes_get_errno, METH_NOARGS, _ctypes_get_errno__doc__},
+
+static PyObject *
+_ctypes_get_errno_impl(PyObject *module);
+
+static PyObject *
+_ctypes_get_errno(PyObject *module, PyObject *Py_UNUSED(ignored))
+{
+ return _ctypes_get_errno_impl(module);
+}
+
+PyDoc_STRVAR(_ctypes_set_errno__doc__,
+"set_errno($module, value, /)\n"
+"--\n"
+"\n");
+
+#define _CTYPES_SET_ERRNO_METHODDEF \
+ {"set_errno", (PyCFunction)_ctypes_set_errno, METH_O, _ctypes_set_errno__doc__},
+
+static PyObject *
+_ctypes_set_errno_impl(PyObject *module, int value);
+
+static PyObject *
+_ctypes_set_errno(PyObject *module, PyObject *arg)
+{
+ PyObject *return_value = NULL;
+ int value;
+
+ value = PyLong_AsInt(arg);
+ if (value == -1 && PyErr_Occurred()) {
+ goto exit;
+ }
+ return_value = _ctypes_set_errno_impl(module, value);
+
+exit:
+ return return_value;
+}
+
+#if defined(MS_WIN32)
+
+PyDoc_STRVAR(_ctypes_get_last_error__doc__,
+"get_last_error($module, /)\n"
+"--\n"
+"\n"
+"Return the current value of the ctypes-private copy of the last error.");
+
+#define _CTYPES_GET_LAST_ERROR_METHODDEF \
+ {"get_last_error", (PyCFunction)_ctypes_get_last_error, METH_NOARGS, _ctypes_get_last_error__doc__},
+
+static PyObject *
+_ctypes_get_last_error_impl(PyObject *module);
+
+static PyObject *
+_ctypes_get_last_error(PyObject *module, PyObject *Py_UNUSED(ignored))
+{
+ return _ctypes_get_last_error_impl(module);
+}
+
+#endif /* defined(MS_WIN32) */
+
+#if defined(MS_WIN32)
+
+PyDoc_STRVAR(_ctypes_set_last_error__doc__,
+"set_last_error($module, value, /)\n"
+"--\n"
+"\n");
+
+#define _CTYPES_SET_LAST_ERROR_METHODDEF \
+ {"set_last_error", (PyCFunction)_ctypes_set_last_error, METH_O, _ctypes_set_last_error__doc__},
+
+static PyObject *
+_ctypes_set_last_error_impl(PyObject *module, int value);
+
+static PyObject *
+_ctypes_set_last_error(PyObject *module, PyObject *arg)
+{
+ PyObject *return_value = NULL;
+ int value;
+
+ value = PyLong_AsInt(arg);
+ if (value == -1 && PyErr_Occurred()) {
+ goto exit;
+ }
+ return_value = _ctypes_set_last_error_impl(module, value);
+
+exit:
+ return return_value;
+}
+
+#endif /* defined(MS_WIN32) */
+
+#if defined(MS_WIN32)
+
+PyDoc_STRVAR(_ctypes__check_HRESULT__doc__,
+"_check_HRESULT($module, hresult, /)\n"
+"--\n"
+"\n");
+
+#define _CTYPES__CHECK_HRESULT_METHODDEF \
+ {"_check_HRESULT", (PyCFunction)_ctypes__check_HRESULT, METH_O, _ctypes__check_HRESULT__doc__},
+
+static PyObject *
+_ctypes__check_HRESULT_impl(PyObject *module, int hr);
+
+static PyObject *
+_ctypes__check_HRESULT(PyObject *module, PyObject *arg)
+{
+ PyObject *return_value = NULL;
+ int hr;
+
+ hr = PyLong_AsInt(arg);
+ if (hr == -1 && PyErr_Occurred()) {
+ goto exit;
+ }
+ return_value = _ctypes__check_HRESULT_impl(module, hr);
+
+exit:
+ return return_value;
+}
+
+#endif /* defined(MS_WIN32) */
+
+#if defined(MS_WIN32)
+
+PyDoc_STRVAR(_ctypes_FormatError__doc__,
+"FormatError($module, code=0, /)\n"
+"--\n"
+"\n"
+"Convert a win32 error code into a string.\n"
+"\n"
+"If the error code is not given, the return value of a call to\n"
+"GetLastError() is used.");
+
+#define _CTYPES_FORMATERROR_METHODDEF \
+ {"FormatError", _PyCFunction_CAST(_ctypes_FormatError), METH_FASTCALL, _ctypes_FormatError__doc__},
+
+static PyObject *
+_ctypes_FormatError_impl(PyObject *module, int code);
+
+static PyObject *
+_ctypes_FormatError(PyObject *module, PyObject *const *args, Py_ssize_t nargs)
+{
+ PyObject *return_value = NULL;
+ int code = 0;
+
+ if (!_PyArg_CheckPositional("FormatError", nargs, 0, 1)) {
+ goto exit;
+ }
+ if (nargs < 1) {
+ goto skip_optional;
+ }
+ code = PyLong_AsInt(args[0]);
+ if (code == -1 && PyErr_Occurred()) {
+ goto exit;
+ }
+skip_optional:
+ return_value = _ctypes_FormatError_impl(module, code);
+
+exit:
+ return return_value;
+}
+
+#endif /* defined(MS_WIN32) */
+
+#if defined(MS_WIN32)
+
+PyDoc_STRVAR(_ctypes_LoadLibrary__doc__,
+"LoadLibrary($module, name, load_flags=0, /)\n"
+"--\n"
+"\n"
+"Load an executable (usually a DLL), and return a handle to it.\n"
+"\n"
+"The handle may be used to locate exported functions in this module.\n"
+"load_flags are as defined for LoadLibraryEx in the Windows API.");
+
+#define _CTYPES_LOADLIBRARY_METHODDEF \
+ {"LoadLibrary", _PyCFunction_CAST(_ctypes_LoadLibrary), METH_FASTCALL, _ctypes_LoadLibrary__doc__},
+
+static PyObject *
+_ctypes_LoadLibrary_impl(PyObject *module, PyObject *nameobj, int load_flags);
+
+static PyObject *
+_ctypes_LoadLibrary(PyObject *module, PyObject *const *args, Py_ssize_t nargs)
+{
+ PyObject *return_value = NULL;
+ PyObject *nameobj;
+ int load_flags = 0;
+
+ if (!_PyArg_CheckPositional("LoadLibrary", nargs, 1, 2)) {
+ goto exit;
+ }
+ if (!PyUnicode_Check(args[0])) {
+ _PyArg_BadArgument("LoadLibrary", "argument 1", "str", args[0]);
+ goto exit;
+ }
+ nameobj = args[0];
+ if (nargs < 2) {
+ goto skip_optional;
+ }
+ load_flags = PyLong_AsInt(args[1]);
+ if (load_flags == -1 && PyErr_Occurred()) {
+ goto exit;
+ }
+skip_optional:
+ return_value = _ctypes_LoadLibrary_impl(module, nameobj, load_flags);
+
+exit:
+ return return_value;
+}
+
+#endif /* defined(MS_WIN32) */
+
+#if defined(MS_WIN32)
+
+PyDoc_STRVAR(_ctypes_FreeLibrary__doc__,
+"FreeLibrary($module, handle, /)\n"
+"--\n"
+"\n"
+"Free the handle of an executable previously loaded by LoadLibrary.");
+
+#define _CTYPES_FREELIBRARY_METHODDEF \
+ {"FreeLibrary", (PyCFunction)_ctypes_FreeLibrary, METH_O, _ctypes_FreeLibrary__doc__},
+
+static PyObject *
+_ctypes_FreeLibrary_impl(PyObject *module, void *hMod);
+
+static PyObject *
+_ctypes_FreeLibrary(PyObject *module, PyObject *arg)
+{
+ PyObject *return_value = NULL;
+ void *hMod;
+
+ if (!_parse_voidp(arg, &hMod)) {
+ goto exit;
+ }
+ return_value = _ctypes_FreeLibrary_impl(module, hMod);
+
+exit:
+ return return_value;
+}
+
+#endif /* defined(MS_WIN32) */
+
+#if defined(MS_WIN32)
+
+PyDoc_STRVAR(_ctypes_CopyComPointer__doc__,
+"CopyComPointer($module, src, dst, /)\n"
+"--\n"
+"\n"
+"Copy a COM pointer and return the HRESULT value.");
+
+#define _CTYPES_COPYCOMPOINTER_METHODDEF \
+ {"CopyComPointer", _PyCFunction_CAST(_ctypes_CopyComPointer), METH_FASTCALL, _ctypes_CopyComPointer__doc__},
+
+static PyObject *
+_ctypes_CopyComPointer_impl(PyObject *module, PyObject *p1, PyObject *p2);
+
+static PyObject *
+_ctypes_CopyComPointer(PyObject *module, PyObject *const *args, Py_ssize_t nargs)
+{
+ PyObject *return_value = NULL;
+ PyObject *p1;
+ PyObject *p2;
+
+ if (!_PyArg_CheckPositional("CopyComPointer", nargs, 2, 2)) {
+ goto exit;
+ }
+ p1 = args[0];
+ p2 = args[1];
+ return_value = _ctypes_CopyComPointer_impl(module, p1, p2);
+
+exit:
+ return return_value;
+}
+
+#endif /* defined(MS_WIN32) */
+
+#if !defined(MS_WIN32) && defined(__APPLE__)
+
+PyDoc_STRVAR(_ctypes__dyld_shared_cache_contains_path__doc__,
+"_dyld_shared_cache_contains_path($module, path, /)\n"
+"--\n"
+"\n"
+"Check whether a path is in the shared cache.");
+
+#define _CTYPES__DYLD_SHARED_CACHE_CONTAINS_PATH_METHODDEF \
+ {"_dyld_shared_cache_contains_path", (PyCFunction)_ctypes__dyld_shared_cache_contains_path, METH_O, _ctypes__dyld_shared_cache_contains_path__doc__},
+
+#endif /* !defined(MS_WIN32) && defined(__APPLE__) */
+
+#if !defined(MS_WIN32)
+
+PyDoc_STRVAR(_ctypes_dlopen__doc__,
+"dlopen($module, name, mode=RTLD_NOW | RTLD_LOCAL, /)\n"
+"--\n"
+"\n"
+"Open a shared library.");
+
+#define _CTYPES_DLOPEN_METHODDEF \
+ {"dlopen", _PyCFunction_CAST(_ctypes_dlopen), METH_FASTCALL, _ctypes_dlopen__doc__},
+
+static PyObject *
+_ctypes_dlopen_impl(PyObject *module, PyObject *name, int mode);
+
+static PyObject *
+_ctypes_dlopen(PyObject *module, PyObject *const *args, Py_ssize_t nargs)
+{
+ PyObject *return_value = NULL;
+ PyObject *name;
+ int mode = DLOPEN_DEFAULT_MODE;
+
+ if (!_PyArg_CheckPositional("dlopen", nargs, 1, 2)) {
+ goto exit;
+ }
+ name = args[0];
+ if (nargs < 2) {
+ goto skip_optional;
+ }
+ mode = PyLong_AsInt(args[1]);
+ if (mode == -1 && PyErr_Occurred()) {
+ goto exit;
+ }
+skip_optional:
+ return_value = _ctypes_dlopen_impl(module, name, mode);
+
+exit:
+ return return_value;
+}
+
+#endif /* !defined(MS_WIN32) */
+
+#if !defined(MS_WIN32)
+
+PyDoc_STRVAR(_ctypes_dlclose__doc__,
+"dlclose($module, handle, /)\n"
+"--\n"
+"\n"
+"Close a shared library.");
+
+#define _CTYPES_DLCLOSE_METHODDEF \
+ {"dlclose", (PyCFunction)_ctypes_dlclose, METH_O, _ctypes_dlclose__doc__},
+
+static PyObject *
+_ctypes_dlclose_impl(PyObject *module, void *handle);
+
+static PyObject *
+_ctypes_dlclose(PyObject *module, PyObject *arg)
+{
+ PyObject *return_value = NULL;
+ void *handle;
+
+ if (!_parse_voidp(arg, &handle)) {
+ goto exit;
+ }
+ return_value = _ctypes_dlclose_impl(module, handle);
+
+exit:
+ return return_value;
+}
+
+#endif /* !defined(MS_WIN32) */
+
+#if !defined(MS_WIN32)
+
+PyDoc_STRVAR(_ctypes_dlsym__doc__,
+"dlsym($module, handle, name, /)\n"
+"--\n"
+"\n"
+"Find a symbol in a shared library.");
+
+#define _CTYPES_DLSYM_METHODDEF \
+ {"dlsym", _PyCFunction_CAST(_ctypes_dlsym), METH_FASTCALL, _ctypes_dlsym__doc__},
+
+static PyObject *
+_ctypes_dlsym_impl(PyObject *module, void *handle, const char *name);
+
+static PyObject *
+_ctypes_dlsym(PyObject *module, PyObject *const *args, Py_ssize_t nargs)
+{
+ PyObject *return_value = NULL;
+ void *handle;
+ const char *name;
+
+ if (!_PyArg_CheckPositional("dlsym", nargs, 2, 2)) {
+ goto exit;
+ }
+ if (!_parse_voidp(args[0], &handle)) {
+ goto exit;
+ }
+ if (!PyUnicode_Check(args[1])) {
+ _PyArg_BadArgument("dlsym", "argument 2", "str", args[1]);
+ goto exit;
+ }
+ name = _PyUnicode_AsUTF8NoNUL(args[1]);
+ if (name == NULL) {
+ goto exit;
+ }
+ return_value = _ctypes_dlsym_impl(module, handle, name);
+
+exit:
+ return return_value;
+}
+
+#endif /* !defined(MS_WIN32) */
+
+#if !defined(MS_WIN32) && (defined(HAVE_DL_ITERATE_PHDR) && !defined(__APPLE__))
+
+PyDoc_STRVAR(_ctypes_dllist__doc__,
+"dllist($module, /)\n"
+"--\n"
+"\n"
+"Return a list of loaded shared libraries.");
+
+#define _CTYPES_DLLIST_METHODDEF \
+ {"dllist", (PyCFunction)_ctypes_dllist, METH_NOARGS, _ctypes_dllist__doc__},
+
+static PyObject *
+_ctypes_dllist_impl(PyObject *module);
+
+static PyObject *
+_ctypes_dllist(PyObject *module, PyObject *Py_UNUSED(ignored))
+{
+ return _ctypes_dllist_impl(module);
+}
+
+#endif /* !defined(MS_WIN32) && (defined(HAVE_DL_ITERATE_PHDR) && !defined(__APPLE__)) */
+
+PyDoc_STRVAR(_ctypes_call_function__doc__,
+"call_function($module, func, arguments, /)\n"
+"--\n"
+"\n");
+
+#define _CTYPES_CALL_FUNCTION_METHODDEF \
+ {"call_function", _PyCFunction_CAST(_ctypes_call_function), METH_FASTCALL, _ctypes_call_function__doc__},
+
+static PyObject *
+_ctypes_call_function_impl(PyObject *module, void *func, PyObject *arguments);
+
+static PyObject *
+_ctypes_call_function(PyObject *module, PyObject *const *args, Py_ssize_t nargs)
+{
+ PyObject *return_value = NULL;
+ void *func;
+ PyObject *arguments;
+
+ if (!_PyArg_CheckPositional("call_function", nargs, 2, 2)) {
+ goto exit;
+ }
+ if (!_parse_voidp(args[0], &func)) {
+ goto exit;
+ }
+ if (!PyTuple_Check(args[1])) {
+ _PyArg_BadArgument("call_function", "argument 2", "tuple", args[1]);
+ goto exit;
+ }
+ arguments = args[1];
+ return_value = _ctypes_call_function_impl(module, func, arguments);
+
+exit:
+ return return_value;
+}
+
+PyDoc_STRVAR(_ctypes_call_cdeclfunction__doc__,
+"call_cdeclfunction($module, func, arguments, /)\n"
+"--\n"
+"\n");
+
+#define _CTYPES_CALL_CDECLFUNCTION_METHODDEF \
+ {"call_cdeclfunction", _PyCFunction_CAST(_ctypes_call_cdeclfunction), METH_FASTCALL, _ctypes_call_cdeclfunction__doc__},
+
+static PyObject *
+_ctypes_call_cdeclfunction_impl(PyObject *module, void *func,
+ PyObject *arguments);
+
+static PyObject *
+_ctypes_call_cdeclfunction(PyObject *module, PyObject *const *args, Py_ssize_t nargs)
+{
+ PyObject *return_value = NULL;
+ void *func;
+ PyObject *arguments;
+
+ if (!_PyArg_CheckPositional("call_cdeclfunction", nargs, 2, 2)) {
+ goto exit;
+ }
+ if (!_parse_voidp(args[0], &func)) {
+ goto exit;
+ }
+ if (!PyTuple_Check(args[1])) {
+ _PyArg_BadArgument("call_cdeclfunction", "argument 2", "tuple", args[1]);
+ goto exit;
+ }
+ arguments = args[1];
+ return_value = _ctypes_call_cdeclfunction_impl(module, func, arguments);
+
+exit:
+ return return_value;
+}
PyDoc_STRVAR(_ctypes_sizeof__doc__,
"sizeof($module, obj, /)\n"
@@ -15,6 +521,17 @@ PyDoc_STRVAR(_ctypes_sizeof__doc__,
#define _CTYPES_SIZEOF_METHODDEF \
{"sizeof", (PyCFunction)_ctypes_sizeof, METH_O, _ctypes_sizeof__doc__},
+PyDoc_STRVAR(_ctypes_alignment__doc__,
+"alignment($module, obj, /)\n"
+"--\n"
+"\n"
+"Return the alignment requirements of a C instance.\n"
+"\n"
+"The argument is a C type or a C instance.");
+
+#define _CTYPES_ALIGNMENT_METHODDEF \
+ {"alignment", (PyCFunction)_ctypes_alignment, METH_O, _ctypes_alignment__doc__},
+
PyDoc_STRVAR(_ctypes_byref__doc__,
"byref($module, obj, offset=0, /)\n"
"--\n"
@@ -97,6 +614,50 @@ _ctypes_addressof(PyObject *module, PyObject *arg)
return return_value;
}
+PyDoc_STRVAR(_ctypes_PyObj_FromPtr__doc__,
+"PyObj_FromPtr($module, address, /)\n"
+"--\n"
+"\n");
+
+#define _CTYPES_PYOBJ_FROMPTR_METHODDEF \
+ {"PyObj_FromPtr", (PyCFunction)_ctypes_PyObj_FromPtr, METH_O, _ctypes_PyObj_FromPtr__doc__},
+
+static PyObject *
+_ctypes_PyObj_FromPtr_impl(PyObject *module, PyObject *ob);
+
+static PyObject *
+_ctypes_PyObj_FromPtr(PyObject *module, PyObject *arg)
+{
+ PyObject *return_value = NULL;
+ PyObject *ob;
+
+ if (!_parse_voidp_object(arg, &ob)) {
+ goto exit;
+ }
+ return_value = _ctypes_PyObj_FromPtr_impl(module, ob);
+
+exit:
+ return return_value;
+}
+
+PyDoc_STRVAR(_ctypes_Py_INCREF__doc__,
+"Py_INCREF($module, obj, /)\n"
+"--\n"
+"\n"
+"Increment the reference count of the object and return it.");
+
+#define _CTYPES_PY_INCREF_METHODDEF \
+ {"Py_INCREF", (PyCFunction)_ctypes_Py_INCREF, METH_O, _ctypes_Py_INCREF__doc__},
+
+PyDoc_STRVAR(_ctypes_Py_DECREF__doc__,
+"Py_DECREF($module, obj, /)\n"
+"--\n"
+"\n"
+"Decrement the reference count of the object and return it.");
+
+#define _CTYPES_PY_DECREF_METHODDEF \
+ {"Py_DECREF", (PyCFunction)_ctypes_Py_DECREF, METH_O, _ctypes_Py_DECREF__doc__},
+
PyDoc_STRVAR(_ctypes_resize__doc__,
"resize($module, obj, size, /)\n"
"--\n"
@@ -142,4 +703,94 @@ _ctypes_resize(PyObject *module, PyObject *const *args, Py_ssize_t nargs)
exit:
return return_value;
}
-/*[clinic end generated code: output=23c74aced603977d input=a9049054013a1b77]*/
+
+PyDoc_STRVAR(_ctypes__unpickle__doc__,
+"_unpickle($module, cls, state, /)\n"
+"--\n"
+"\n");
+
+#define _CTYPES__UNPICKLE_METHODDEF \
+ {"_unpickle", _PyCFunction_CAST(_ctypes__unpickle), METH_FASTCALL, _ctypes__unpickle__doc__},
+
+static PyObject *
+_ctypes__unpickle_impl(PyObject *module, PyObject *typ, PyObject *state);
+
+static PyObject *
+_ctypes__unpickle(PyObject *module, PyObject *const *args, Py_ssize_t nargs)
+{
+ PyObject *return_value = NULL;
+ PyObject *typ;
+ PyObject *state;
+
+ if (!_PyArg_CheckPositional("_unpickle", nargs, 2, 2)) {
+ goto exit;
+ }
+ typ = args[0];
+ if (!PyTuple_Check(args[1])) {
+ _PyArg_BadArgument("_unpickle", "argument 2", "tuple", args[1]);
+ goto exit;
+ }
+ state = args[1];
+ return_value = _ctypes__unpickle_impl(module, typ, state);
+
+exit:
+ return return_value;
+}
+
+PyDoc_STRVAR(_ctypes_buffer_info__doc__,
+"buffer_info($module, obj, /)\n"
+"--\n"
+"\n"
+"Return buffer interface information.");
+
+#define _CTYPES_BUFFER_INFO_METHODDEF \
+ {"buffer_info", (PyCFunction)_ctypes_buffer_info, METH_O, _ctypes_buffer_info__doc__},
+
+#ifndef _CTYPES_GET_LAST_ERROR_METHODDEF
+ #define _CTYPES_GET_LAST_ERROR_METHODDEF
+#endif /* !defined(_CTYPES_GET_LAST_ERROR_METHODDEF) */
+
+#ifndef _CTYPES_SET_LAST_ERROR_METHODDEF
+ #define _CTYPES_SET_LAST_ERROR_METHODDEF
+#endif /* !defined(_CTYPES_SET_LAST_ERROR_METHODDEF) */
+
+#ifndef _CTYPES__CHECK_HRESULT_METHODDEF
+ #define _CTYPES__CHECK_HRESULT_METHODDEF
+#endif /* !defined(_CTYPES__CHECK_HRESULT_METHODDEF) */
+
+#ifndef _CTYPES_FORMATERROR_METHODDEF
+ #define _CTYPES_FORMATERROR_METHODDEF
+#endif /* !defined(_CTYPES_FORMATERROR_METHODDEF) */
+
+#ifndef _CTYPES_LOADLIBRARY_METHODDEF
+ #define _CTYPES_LOADLIBRARY_METHODDEF
+#endif /* !defined(_CTYPES_LOADLIBRARY_METHODDEF) */
+
+#ifndef _CTYPES_FREELIBRARY_METHODDEF
+ #define _CTYPES_FREELIBRARY_METHODDEF
+#endif /* !defined(_CTYPES_FREELIBRARY_METHODDEF) */
+
+#ifndef _CTYPES_COPYCOMPOINTER_METHODDEF
+ #define _CTYPES_COPYCOMPOINTER_METHODDEF
+#endif /* !defined(_CTYPES_COPYCOMPOINTER_METHODDEF) */
+
+#ifndef _CTYPES__DYLD_SHARED_CACHE_CONTAINS_PATH_METHODDEF
+ #define _CTYPES__DYLD_SHARED_CACHE_CONTAINS_PATH_METHODDEF
+#endif /* !defined(_CTYPES__DYLD_SHARED_CACHE_CONTAINS_PATH_METHODDEF) */
+
+#ifndef _CTYPES_DLOPEN_METHODDEF
+ #define _CTYPES_DLOPEN_METHODDEF
+#endif /* !defined(_CTYPES_DLOPEN_METHODDEF) */
+
+#ifndef _CTYPES_DLCLOSE_METHODDEF
+ #define _CTYPES_DLCLOSE_METHODDEF
+#endif /* !defined(_CTYPES_DLCLOSE_METHODDEF) */
+
+#ifndef _CTYPES_DLSYM_METHODDEF
+ #define _CTYPES_DLSYM_METHODDEF
+#endif /* !defined(_CTYPES_DLSYM_METHODDEF) */
+
+#ifndef _CTYPES_DLLIST_METHODDEF
+ #define _CTYPES_DLLIST_METHODDEF
+#endif /* !defined(_CTYPES_DLLIST_METHODDEF) */
+/*[clinic end generated code: output=615c411ddc01d0a4 input=a9049054013a1b77]*/
diff --git a/Modules/_ctypes/ctypes.h b/Modules/_ctypes/ctypes.h
index 248559aa364a198..98d8b660850b0d9 100644
--- a/Modules/_ctypes/ctypes.h
+++ b/Modules/_ctypes/ctypes.h
@@ -24,7 +24,7 @@
// Do we support C99 complex types in ffi?
// For Apple's libffi, this must be determined at runtime (see gh-128156).
#if defined(_Py_FFI_SUPPORT_C_COMPLEX)
-# if USING_APPLE_OS_LIBFFI && defined(__has_builtin)
+# if defined(USING_APPLE_OS_LIBFFI) && defined(__has_builtin)
# if __has_builtin(__builtin_available)
# define Py_FFI_COMPLEX_AVAILABLE __builtin_available(macOS 10.15, *)
# else
diff --git a/Modules/_ctypes/malloc_closure.c b/Modules/_ctypes/malloc_closure.c
index 62c7aa5d6affbfb..3abab8873acbd01 100644
--- a/Modules/_ctypes/malloc_closure.c
+++ b/Modules/_ctypes/malloc_closure.c
@@ -68,10 +68,25 @@ static void more_core(void)
/* allocate a memory block */
#ifdef MS_WIN32
+#ifdef MS_WINDOWS_DESKTOP
item = (ITEM *)VirtualAlloc(NULL,
count * sizeof(ITEM),
MEM_COMMIT,
PAGE_EXECUTE_READWRITE);
+#else // UWP
+ /* Due security restrictions, UWP not allows request Read-Write-Execute permissions at once.
+ The correct flow in UWP for execute dynamic code in memmory is:
+ 1. Alloate as Read-Write (PAGE_READWRITE) and write dynamic code to memmory.
+ 2. Change to Executable (PAGE_EXECUTE_READ) with 'VirtualProtectFromApp'.
+ 3. Flush cache with 'FlushInstructionCache' to ensure CPU instruction cache coherency
+ before executing the generated code.
+ TODO: Implement 2 and 3 in the appropriate places. For now, this defers
+ the error from import time to time of use (or never, if an app avoids it). */
+ item = (ITEM*)VirtualAllocFromApp(NULL,
+ count * sizeof(ITEM),
+ MEM_COMMIT | MEM_RESERVE,
+ PAGE_READWRITE);
+#endif // !MS_WINDOWS_DESKTOP
if (item == NULL)
return;
#else
diff --git a/Modules/_ctypes/stgdict.c b/Modules/_ctypes/stgdict.c
index ab955a0b824a2f3..7920c87ebe3cef3 100644
--- a/Modules/_ctypes/stgdict.c
+++ b/Modules/_ctypes/stgdict.c
@@ -28,6 +28,10 @@ PyCStgInfo_clone(StgInfo *dst_info, StgInfo *src_info)
ctype_free_stginfo_members(dst_info);
memcpy(dst_info, src_info, sizeof(StgInfo));
+ /* Owned buffers must not be shared if a subsequent allocation fails. */
+ dst_info->format = NULL;
+ dst_info->shape = NULL;
+ dst_info->ffi_type_pointer.elements = NULL;
#ifdef Py_GIL_DISABLED
dst_info->mutex = (PyMutex){0};
#endif
@@ -679,10 +683,22 @@ _replace_array_elements(ctypes_state *st, PyObject *layout_fields,
structs[struct_index].type = FFI_TYPE_STRUCT;
structs[struct_index].elements = &dummy_types[dummy_index];
++struct_index;
+ ffi_type *etype = &einfo->ffi_type_pointer;
+#if defined(__sparc__) && defined(__arch64__) && !defined(__sun)
+ /* On Linux, GCC and clang pass arrays of floating-point type
+ in a structure in integer registers; only Solaris follows
+ the vendor ABI here (GCC PR target/114416). */
+ if (etype->type == FFI_TYPE_FLOAT) {
+ etype = &ffi_type_uint32;
+ }
+ else if (etype->type == FFI_TYPE_DOUBLE) {
+ etype = &ffi_type_uint64;
+ }
+#endif
/* Copy over the element's type, length times. */
while (length > 0) {
assert(dummy_index < (num_ffi_type_pointers));
- dummy_types[dummy_index++] = &einfo->ffi_type_pointer;
+ dummy_types[dummy_index++] = etype;
length--;
}
assert(dummy_index < (num_ffi_type_pointers));
diff --git a/Modules/_curses_panel.c b/Modules/_curses_panel.c
index 742a3310bc3528a..40d407742b1621d 100644
--- a/Modules/_curses_panel.c
+++ b/Modules/_curses_panel.c
@@ -437,11 +437,11 @@ PyCursesPanel_Clear(PyObject *op)
PyCursesPanelObject *self = _PyCursesPanelObject_CAST(op);
PyObject *extra = (PyObject *)panel_userptr(self->pan);
if (extra != NULL) {
- Py_DECREF(extra);
if (set_panel_userptr(self->pan, NULL) == ERR) {
curses_panel_panel_set_error(self, "set_panel_userptr", NULL);
return -1;
}
+ Py_DECREF(extra);
}
// self->wo should not be cleared because an associated WINDOW may exist
return 0;
@@ -454,20 +454,21 @@ PyCursesPanel_Dealloc(PyObject *self)
PyObject_GC_UnTrack(self);
PyCursesPanelObject *po = _PyCursesPanelObject_CAST(self);
- if (PyCursesPanel_Clear(self) < 0) {
+ PyObject *extra = (PyObject *)panel_userptr(po->pan);
+ if (extra != NULL && set_panel_userptr(po->pan, NULL) == ERR) {
+ curses_panel_panel_set_error(po, "set_panel_userptr", "__del__");
+ PyErr_FormatUnraisable("Exception ignored in PyCursesPanel_Dealloc()");
+ }
+ if (po->wo != NULL && remove_lop(po) < 0) {
+ PyErr_SetString(PyExc_RuntimeError, "__del__: no panel object to delete");
PyErr_FormatUnraisable("Exception ignored in PyCursesPanel_Dealloc()");
}
if (del_panel(po->pan) == ERR && !PyErr_Occurred()) {
curses_panel_panel_set_error(po, "del_panel", "__del__");
PyErr_FormatUnraisable("Exception ignored in PyCursesPanel_Dealloc()");
}
- if (po->wo != NULL) {
- Py_DECREF(po->wo);
- if (remove_lop(po) < 0) {
- PyErr_SetString(PyExc_RuntimeError, "__del__: no panel object to delete");
- PyErr_FormatUnraisable("Exception ignored in PyCursesPanel_Dealloc()");
- }
- }
+ Py_XDECREF(extra);
+ Py_XDECREF(po->wo);
tp->tp_free(po);
Py_DECREF(tp);
}
@@ -594,6 +595,12 @@ _curses_panel_panel_replace_impl(PyCursesPanelObject *self,
return NULL;
}
+ if (win->win == NULL) {
+ _curses_panel_state *state = get_curses_panel_state_by_panel(self);
+ PyErr_SetString(state->error, "the window has been detached");
+ return NULL;
+ }
+
int rtn = replace_panel(self->pan, win->win);
if (rtn == ERR) {
curses_panel_panel_set_error(self, "replace_panel", "replace");
diff --git a/Modules/_cursesmodule.c b/Modules/_cursesmodule.c
index cc68a51f0bed935..94cad7f02e31bb8 100644
--- a/Modules/_cursesmodule.c
+++ b/Modules/_cursesmodule.c
@@ -107,7 +107,7 @@ static const char PyCursesVersion[] = "2.2";
#define CURSES_MODULE
#include "py_curses.h"
-#if defined(HAVE_TERM_H) || defined(__sgi)
+#ifdef HAVE_TERM_H
/* For termname, longname, putp, tigetflag, tigetnum, tigetstr, tparm
which are not declared in SysV curses and for setupterm. */
#include
@@ -120,7 +120,7 @@ static const char PyCursesVersion[] = "2.2";
#include
#endif
-#if !defined(NCURSES_VERSION) && (defined(sgi) || defined(__sun) || defined(SCO5))
+#if !defined(NCURSES_VERSION) && defined(__sun)
#define STRICT_SYSV_CURSES /* Don't use ncurses extensions */
typedef chtype attr_t; /* No attr_t type is available */
#endif
@@ -159,6 +159,8 @@ typedef struct {
PyTypeObject *complexstr_type; // _curses.complexstr
PyObject *topscreen; // owned ref to the current screen object,
// or NULL for the initscr() screen
+ PyObject *prescreen; // owned ref to the pending new_prescr() screen,
+ // or NULL if there is no pending pre-screen
} cursesmodule_state;
static inline cursesmodule_state *
@@ -207,6 +209,8 @@ static int curses_initscr_called = FALSE;
/* Tells whether start_color() has been called to initialise color usage. */
static int curses_start_color_called = FALSE;
+static int update_lines_cols(PyObject *private_module);
+
/* Encoding of the initial screen, used by module-level functions that have
no window object to take it from (e.g. unctrl(), ungetch()). This is a
private copy: the window object that initscr() returns may be deallocated
@@ -309,6 +313,14 @@ curses_window_set_null_error(PyCursesWindowObject *win,
_curses_set_null_error(state, curses_funcname, python_funcname);
}
+/* ncurses and PDCurses store n characters and add a terminator; NetBSD
+ curses counts the terminator in n. Ask an unknown library for one more. */
+#if defined(NCURSES_VERSION) || defined(PDCURSES)
+# define CURSES_STR_EXTRA 0
+#else
+# define CURSES_STR_EXTRA 1
+#endif
+
/* Utility Checking Procedures */
/*
@@ -356,6 +368,35 @@ _PyCursesStatefulCheckFunction(PyObject *module,
return 0;
}
+/*
+ * Function to check that the current screen has a terminal, by testing
+ * stdscr, which a screen made by new_prescr() does not have. If an error
+ * occurs, a PyCursesError is set and this returns 0. Otherwise this
+ * returns 1.
+ */
+static int
+_PyCursesStatefulCheckTerminal(PyObject *module)
+{
+ if (stdscr != NULL) {
+ return 1;
+ }
+ cursesmodule_state *state = get_cursesmodule_state(module);
+ PyErr_SetString(state->error, "the current screen has no terminal");
+ return 0;
+}
+
+/* Same as _PyCursesStatefulCheckTerminal() for a Window object. */
+static int
+curses_window_check_terminal(PyCursesWindowObject *win)
+{
+ if (stdscr != NULL) {
+ return 1;
+ }
+ cursesmodule_state *state = get_cursesmodule_state_by_win(win);
+ PyErr_SetString(state->error, "the current screen has no terminal");
+ return 0;
+}
+
#define PyCursesStatefulSetupTermCalled(MODULE) \
do { \
if (!_PyCursesStatefulCheckFunction(MODULE, \
@@ -370,7 +411,8 @@ _PyCursesStatefulCheckFunction(PyObject *module,
do { \
if (!_PyCursesStatefulCheckFunction(MODULE, \
curses_initscr_called, \
- "initscr")) \
+ "initscr") \
+ || !_PyCursesStatefulCheckTerminal(MODULE)) \
{ \
return 0; \
} \
@@ -433,7 +475,7 @@ curses_window_check_err(PyCursesWindowObject *win, int code,
static int
PyCurses_ConvertToChtype(PyCursesWindowObject *win, PyObject *obj, chtype *ch)
{
- long value;
+ unsigned long long value;
if (PyBytes_Check(obj)) {
if (PyBytes_GET_SIZE(obj) != 1) {
PyErr_Format(PyExc_TypeError,
@@ -463,20 +505,18 @@ PyCurses_ConvertToChtype(PyCursesWindowObject *win, PyObject *obj, chtype *ch)
bytes = PyUnicode_AsEncodedString(obj, encoding, NULL);
if (bytes == NULL)
return 0;
- if (PyBytes_GET_SIZE(bytes) == 1)
- value = (unsigned char)PyBytes_AS_STRING(bytes)[0];
- else
- value = -1;
- Py_DECREF(bytes);
- if (value < 0)
+ if (PyBytes_GET_SIZE(bytes) != 1) {
+ Py_DECREF(bytes);
goto overflow;
+ }
+ value = (unsigned char)PyBytes_AS_STRING(bytes)[0];
+ Py_DECREF(bytes);
}
}
else if (PyLong_CheckExact(obj)) {
- int long_overflow;
- value = PyLong_AsLongAndOverflow(obj, &long_overflow);
- if (long_overflow)
- goto overflow;
+ value = PyLong_AsUnsignedLongLong(obj);
+ if (value == (unsigned long long)-1 && PyErr_Occurred())
+ return 0;
}
else {
PyErr_Format(PyExc_TypeError,
@@ -485,7 +525,7 @@ PyCurses_ConvertToChtype(PyCursesWindowObject *win, PyObject *obj, chtype *ch)
return 0;
}
*ch = (chtype)value;
- if ((long)*ch != value)
+ if ((unsigned long long)*ch != value)
goto overflow;
return 1;
@@ -533,6 +573,10 @@ PyCurses_ConvertToWideCell(PyObject *obj, wchar_t *wch)
setcchar() would silently drop a trailing spacing character, or fail
with a generic error for a control-character base. */
if (nch > 1) {
+ if (wmemchr(wch, L'\0', nch) != NULL) {
+ PyErr_SetString(PyExc_ValueError, "embedded null character");
+ return -1;
+ }
int bad = wcwidth(wch[0]) < 0;
for (Py_ssize_t i = 1; !bad && i < nch; i++) {
bad = wcwidth(wch[i]) != 0;
@@ -557,7 +601,7 @@ PyCurses_ConvertToCchar_t(PyCursesWindowObject *win, PyObject *obj,
#endif
)
{
- long value;
+ unsigned long long value;
if (PyUnicode_Check(obj)) {
#ifdef HAVE_NCURSESW
@@ -580,11 +624,8 @@ PyCurses_ConvertToCchar_t(PyCursesWindowObject *win, PyObject *obj,
value = (unsigned char)PyBytes_AsString(obj)[0];
}
else if (PyLong_CheckExact(obj)) {
- int overflow;
- value = PyLong_AsLongAndOverflow(obj, &overflow);
- if (overflow) {
- PyErr_SetString(PyExc_OverflowError,
- "int doesn't fit in long");
+ value = PyLong_AsUnsignedLongLong(obj);
+ if (value == (unsigned long long)-1 && PyErr_Occurred()) {
return 0;
}
}
@@ -596,7 +637,7 @@ PyCurses_ConvertToCchar_t(PyCursesWindowObject *win, PyObject *obj,
}
*ch = (chtype)value;
- if ((long)*ch != value) {
+ if ((unsigned long long)*ch != value) {
PyErr_Format(PyExc_OverflowError,
"byte doesn't fit in chtype");
return 0;
@@ -763,7 +804,9 @@ curses_getcchar(const cchar_t *wcval, wchar_t *wstr, attr_t *attrs, int *pair)
/* getcchar() is not guaranteed to write the text of an empty cell, so make
the output an empty string by default. */
wstr[0] = L'\0';
-#if _NCURSES_EXTENDED_COLOR_FUNCS
+ /* getcchar()'s opts slot returns the extended color pair, but ncurses
+ returned ERR for a non-NULL opts until 6.3 (patch 20210116). */
+#if _NCURSES_EXTENDED_COLOR_FUNCS && NCURSES_VERSION_PATCH+0 >= 20210116
int rtn = getcchar(wcval, wstr, attrs, &spair, pair);
#else
int rtn = getcchar(wcval, wstr, attrs, &spair, NULL);
@@ -771,6 +814,9 @@ curses_getcchar(const cchar_t *wcval, wchar_t *wstr, attr_t *attrs, int *pair)
*pair = spair;
}
#endif
+ if (rtn != ERR) {
+ *attrs &= ~(attr_t)A_COLOR;
+ }
return rtn;
}
@@ -878,7 +924,9 @@ curses_cell_text(cursesmodule_state *state, const curses_cell_t *cell)
PyErr_SetString(state->error, "getcchar() returned ERR");
return NULL;
}
- return PyUnicode_FromWideChar(wstr, -1);
+ /* setcchar() stores no text for a NUL (it takes a NUL-terminated string),
+ so an empty cell holds a NUL character, as on a narrow build. */
+ return PyUnicode_FromWideChar(wstr, wstr[0] == L'\0' ? 1 : -1);
#else
char ch = (char)(*cell & A_CHARTEXT);
return PyUnicode_Decode(&ch, 1, curses_screen_encoding, NULL);
@@ -1050,14 +1098,14 @@ attr_converter(PyObject *arg, void *ptr)
{
/* attr_t is unsigned and at least as wide as chtype, so an attribute
value must be a non-negative integer that fits in attr_t. */
- unsigned long attr = PyLong_AsUnsignedLong(arg);
- if (attr == (unsigned long)-1 && PyErr_Occurred()) {
+ unsigned long long attr = PyLong_AsUnsignedLongLong(arg);
+ if (attr == (unsigned long long)-1 && PyErr_Occurred()) {
return 0;
}
- if (attr > (unsigned long)(attr_t)-1) {
+ if (attr > (unsigned long long)(attr_t)-1) {
PyErr_Format(PyExc_OverflowError,
- "attribute value is greater than maximum (%lu)",
- (unsigned long)(attr_t)-1);
+ "attribute value is greater than maximum (%llu)",
+ (unsigned long long)(attr_t)-1);
return 0;
}
*(attr_t *)ptr = (attr_t)attr;
@@ -1192,7 +1240,7 @@ complexchar_get_attr(PyObject *self, void *Py_UNUSED(closure))
&_PyCursesComplexCharObject_CAST(self)->cval, &attrs, &pair) < 0) {
return NULL;
}
- return PyLong_FromUnsignedLong((unsigned long)attrs);
+ return PyLong_FromUnsignedLongLong((unsigned long long)attrs);
}
static PyObject *
@@ -1288,6 +1336,16 @@ static PyObject *
complexstr_from_string(cursesmodule_state *state, PyObject *str,
attr_t attr, int pair)
{
+ /* A NUL cell ends a batch write and a cell array read (add_wchnstr(3X)),
+ so a string of cells cannot hold one, as addstr() cannot either. */
+ Py_ssize_t nul = PyUnicode_FindChar(str, 0, 0, PyUnicode_GET_LENGTH(str), 1);
+ if (nul < -1) {
+ return NULL;
+ }
+ if (nul >= 0) {
+ PyErr_SetString(PyExc_ValueError, "embedded null character");
+ return NULL;
+ }
#ifdef HAVE_NCURSESW
Py_ssize_t n;
wchar_t *wbuf = PyUnicode_AsWideCharString(str, &n);
@@ -1536,7 +1594,10 @@ complexstr_concat(PyObject *a, PyObject *b)
{
cursesmodule_state *state = get_cursesmodule_state_by_cls(Py_TYPE(a));
if (!Py_IS_TYPE(b, state->complexstr_type)) {
- Py_RETURN_NOTIMPLEMENTED;
+ PyErr_Format(PyExc_TypeError,
+ "can only concatenate complexstr to complexstr, not %T",
+ b);
+ return NULL;
}
PyCursesComplexStrObject *sa = _PyCursesComplexStrObject_CAST(a);
PyCursesComplexStrObject *sb = _PyCursesComplexStrObject_CAST(b);
@@ -1791,6 +1852,42 @@ curses_window_put_cells(PyCursesWindowObject *self, PyObject *obj,
Py_RETURN_NONE; \
}
+/* Same as Window_OneArgNoReturnVoidFunction() for a function that needs
+ a terminal. */
+#define Window_OneArgNoReturnVoidTerminalFunction(X, TYPE, PARSESTR) \
+ static PyObject * PyCursesWindow_ ## X \
+ (PyObject *op, PyObject *args) \
+ { \
+ TYPE arg1; \
+ if (!PyArg_ParseTuple(args, PARSESTR, &arg1)) { \
+ return NULL; \
+ } \
+ PyCursesWindowObject *self = _PyCursesWindowObject_CAST(op); \
+ if (!curses_window_check_terminal(self)) { \
+ return NULL; \
+ } \
+ X(self->win, arg1); \
+ Py_RETURN_NONE; \
+ }
+
+/* Same as Window_OneArgNoReturnFunction() for a function that needs
+ a terminal. */
+#define Window_OneArgNoReturnTerminalFunction(X, TYPE, PARSESTR) \
+ static PyObject * PyCursesWindow_ ## X \
+ (PyObject *op, PyObject *args) \
+ { \
+ TYPE arg1; \
+ if (!PyArg_ParseTuple(args, PARSESTR, &arg1)) { \
+ return NULL; \
+ } \
+ PyCursesWindowObject *self = _PyCursesWindowObject_CAST(op); \
+ if (!curses_window_check_terminal(self)) { \
+ return NULL; \
+ } \
+ int code = X(self->win, arg1); \
+ return curses_window_check_err(self, code, # X, NULL); \
+ }
+
#define Window_OneArgNoReturnFunction(X, TYPE, PARSESTR) \
static PyObject * PyCursesWindow_ ## X \
(PyObject *op, PyObject *args) \
@@ -1839,10 +1936,10 @@ Window_NoArgTrueFalseFunction(is_scrollok)
Window_NoArgTrueFalseFunction(is_subwin)
Window_NoArgTrueFalseFunction(is_syncok)
#endif
-#if defined(HAVE_CURSES_IS_KEYPAD) || defined(PDCURSES)
+#if defined(_Py__Py_HAVE_CURSES_IS_KEYPAD) || defined(PDCURSES)
Window_NoArgTrueFalseFunction(is_keypad)
#endif
-#if defined(HAVE_CURSES_IS_LEAVEOK) || defined(PDCURSES)
+#if defined(_Py_HAVE_CURSES_IS_LEAVEOK) || defined(PDCURSES)
Window_NoArgTrueFalseFunction(is_leaveok)
#endif
#if defined(HAVE_CURSES_IS_PAD) || defined(PDCURSES)
@@ -1868,6 +1965,7 @@ PyCursesWindow_getscrreg(PyObject *op, PyObject *Py_UNUSED(ignored))
}
return Py_BuildValue("(ii)", top, bottom);
}
+#endif /* NCURSES_EXT_FUNCS >= 20110404 || PDCURSES */
static PyObject *
PyCursesWindow_getparent(PyObject *op, PyObject *Py_UNUSED(ignored))
@@ -1880,7 +1978,6 @@ PyCursesWindow_getparent(PyObject *op, PyObject *Py_UNUSED(ignored))
}
return Py_NewRef((PyObject *)self->orig);
}
-#endif /* NCURSES_EXT_FUNCS >= 20110404 || PDCURSES */
Window_NoArgNoReturnVoidFunction(wsyncup)
Window_NoArgNoReturnVoidFunction(wsyncdown)
@@ -1891,7 +1988,7 @@ Window_NoArgNoReturnVoidFunction(wclrtoeol)
Window_NoArgNoReturnVoidFunction(wclrtobot)
Window_NoArgNoReturnVoidFunction(wclear)
-Window_OneArgNoReturnVoidFunction(idcok, int, "i;True(1) or False(0)")
+Window_OneArgNoReturnVoidTerminalFunction(idcok, int, "i;True(1) or False(0)")
#ifdef HAVE_CURSES_IMMEDOK
Window_OneArgNoReturnVoidFunction(immedok, int, "i;True(1) or False(0)")
#endif
@@ -1903,8 +2000,8 @@ Window_NoArg2TupleReturnFunction(getmaxyx, int, "ii")
Window_NoArg2TupleReturnFunction(getparyx, int, "ii")
Window_OneArgNoReturnFunction(clearok, int, "i;True(1) or False(0)")
-Window_OneArgNoReturnFunction(idlok, int, "i;True(1) or False(0)")
-Window_OneArgNoReturnFunction(keypad, int, "i;True(1) or False(0)")
+Window_OneArgNoReturnTerminalFunction(idlok, int, "i;True(1) or False(0)")
+Window_OneArgNoReturnTerminalFunction(keypad, int, "i;True(1) or False(0)")
Window_OneArgNoReturnFunction(leaveok, int, "i;True(1) or False(0)")
Window_OneArgNoReturnFunction(nodelay, int, "i;True(1) or False(0)")
Window_OneArgNoReturnFunction(notimeout, int, "i;True(1) or False(0)")
@@ -1930,7 +2027,7 @@ PyCursesWindow_New(cursesmodule_state *state,
{
if (encoding == NULL) {
#if defined(MS_WINDOWS)
- char *buffer[100];
+ char buffer[100];
UINT cp;
cp = GetConsoleOutputCP();
if (cp != 0) {
@@ -2095,6 +2192,56 @@ curses_wattrset(PyCursesWindowObject *self, attr_t attr, const char *funcname)
return 0;
}
+/* Read the rendition a write with an *attr* argument has to put back. The
+ color pair is read apart from the attributes because the A_COLOR field of a
+ chtype holds only pairs 0 to 255, while a window can use a larger one. */
+static int
+curses_wattr_save(PyCursesWindowObject *self, attr_t *attrs, int *pair,
+ const char *funcname)
+{
+#if defined(_Py_HAVE_CURSES_WATTR_GET) && defined(_Py_HAVE_CURSES_WATTR_SET)
+ int rtn;
+#if _NCURSES_EXTENDED_COLOR_FUNCS
+ short legacy_pair;
+ rtn = wattr_get(self->win, attrs, &legacy_pair, pair);
+#else
+ short spair;
+ rtn = wattr_get(self->win, attrs, &spair, NULL);
+ *pair = spair;
+#endif
+ if (rtn == ERR) {
+ curses_window_set_error(self, "wattr_get", funcname);
+ return -1;
+ }
+#else
+ *attrs = getattrs(self->win);
+ *pair = 0;
+#endif
+ return 0;
+}
+
+/* Put the rendition back. The name of the curses function used is
+ _CURSES_WATTR_RESTORE_FUNC, for the caller to name it in an error. */
+#if defined(_Py_HAVE_CURSES_WATTR_GET) && defined(_Py_HAVE_CURSES_WATTR_SET)
+#define _CURSES_WATTR_RESTORE_FUNC "wattr_set"
+#else
+#define _CURSES_WATTR_RESTORE_FUNC "wattrset"
+#endif
+
+static int
+curses_wattr_restore(PyCursesWindowObject *self, attr_t attrs, int pair)
+{
+#if defined(_Py_HAVE_CURSES_WATTR_GET) && defined(_Py_HAVE_CURSES_WATTR_SET)
+#if _NCURSES_EXTENDED_COLOR_FUNCS
+ return wattr_set(self->win, attrs, 0, &pair);
+#else
+ return wattr_set(self->win, attrs, (short)pair, NULL);
+#endif
+#else
+ return wattrset(self->win, attrs);
+#endif
+}
+
/*[clinic input]
_curses.window.addstr
@@ -2135,6 +2282,7 @@ _curses_window_addstr_impl(PyCursesWindowObject *self, int group_left_1,
wchar_t *wstr = NULL;
#endif
attr_t attr_old = A_NORMAL;
+ int pair_old = 0;
int use_xy = group_left_1, use_attr = group_right_1;
const char *funcname;
@@ -2159,8 +2307,9 @@ _curses_window_addstr_impl(PyCursesWindowObject *self, int group_left_1,
return NULL;
}
if (use_attr) {
- attr_old = getattrs(self->win);
- if (curses_wattrset(self, attr, "addstr") < 0) {
+ if (curses_wattr_save(self, &attr_old, &pair_old, "addstr") < 0 ||
+ curses_wattrset(self, attr, "addstr") < 0)
+ {
curses_release_wstr(strtype, wstr);
Py_XDECREF(bytesobj);
return NULL;
@@ -2196,15 +2345,14 @@ _curses_window_addstr_impl(PyCursesWindowObject *self, int group_left_1,
}
Py_DECREF(bytesobj);
}
- if (rtn == ERR) {
- curses_window_set_error(self, funcname, "addstr");
- return NULL;
- }
if (use_attr) {
- rtn = wattrset(self->win, attr_old);
- return curses_window_check_err(self, rtn, "wattrset", "addstr");
+ int attr_rtn = curses_wattr_restore(self, attr_old, pair_old);
+ if (rtn != ERR) {
+ rtn = attr_rtn;
+ funcname = _CURSES_WATTR_RESTORE_FUNC;
+ }
}
- Py_RETURN_NONE;
+ return curses_window_check_err(self, rtn, funcname, "addstr");
}
/*[clinic input]
@@ -2250,6 +2398,7 @@ _curses_window_addnstr_impl(PyCursesWindowObject *self, int group_left_1,
wchar_t *wstr = NULL;
#endif
attr_t attr_old = A_NORMAL;
+ int pair_old = 0;
int use_xy = group_left_1, use_attr = group_right_1;
const char *funcname;
@@ -2274,8 +2423,9 @@ _curses_window_addnstr_impl(PyCursesWindowObject *self, int group_left_1,
return NULL;
if (use_attr) {
- attr_old = getattrs(self->win);
- if (curses_wattrset(self, attr, "addnstr") < 0) {
+ if (curses_wattr_save(self, &attr_old, &pair_old, "addnstr") < 0 ||
+ curses_wattrset(self, attr, "addnstr") < 0)
+ {
curses_release_wstr(strtype, wstr);
Py_XDECREF(bytesobj);
return NULL;
@@ -2307,15 +2457,14 @@ _curses_window_addnstr_impl(PyCursesWindowObject *self, int group_left_1,
}
Py_DECREF(bytesobj);
}
- if (rtn == ERR) {
- curses_window_set_error(self, funcname, "addnstr");
- return NULL;
- }
if (use_attr) {
- rtn = wattrset(self->win, attr_old);
- return curses_window_check_err(self, rtn, "wattrset", "addnstr");
+ int attr_rtn = curses_wattr_restore(self, attr_old, pair_old);
+ if (rtn != ERR) {
+ rtn = attr_rtn;
+ funcname = _CURSES_WATTR_RESTORE_FUNC;
+ }
}
- Py_RETURN_NONE;
+ return curses_window_check_err(self, rtn, funcname, "addnstr");
}
/*[clinic input]
@@ -2409,6 +2558,7 @@ _curses_window_attrset_impl(PyCursesWindowObject *self, attr_t attr)
return curses_window_check_err(self, rtn, "wattrset", "attrset");
}
+#ifdef _Py_HAVE_CURSES_WATTR_GET
/*[clinic input]
_curses.window.attr_get
@@ -2434,7 +2584,9 @@ _curses_window_attr_get_impl(PyCursesWindowObject *self)
}
return Py_BuildValue("(ki)", (unsigned long)attrs, (int)pair);
}
+#endif /* _Py_HAVE_CURSES_WATTR_GET */
+#ifdef _Py_HAVE_CURSES_WATTR_SET
/*[clinic input]
_curses.window.attr_set
@@ -2458,7 +2610,9 @@ _curses_window_attr_set_impl(PyCursesWindowObject *self, attr_t attr,
#endif
return curses_window_check_err(self, rtn, "wattr_set", "attr_set");
}
+#endif /* _Py_HAVE_CURSES_WATTR_SET */
+#ifdef _Py_HAVE_CURSES_WATTR_ON
/*[clinic input]
_curses.window.attr_on
@@ -2475,7 +2629,9 @@ _curses_window_attr_on_impl(PyCursesWindowObject *self, attr_t attr)
int rtn = wattr_on(self->win, attr, NULL);
return curses_window_check_err(self, rtn, "wattr_on", "attr_on");
}
+#endif /* _Py_HAVE_CURSES_WATTR_ON */
+#ifdef _Py_HAVE_CURSES_WATTR_OFF
/*[clinic input]
_curses.window.attr_off
@@ -2492,7 +2648,9 @@ _curses_window_attr_off_impl(PyCursesWindowObject *self, attr_t attr)
int rtn = wattr_off(self->win, attr, NULL);
return curses_window_check_err(self, rtn, "wattr_off", "attr_off");
}
+#endif /* _Py_HAVE_CURSES_WATTR_OFF */
+#ifdef _Py_HAVE_CURSES_WCOLOR_SET
/*[clinic input]
_curses.window.color_set
@@ -2514,6 +2672,7 @@ _curses_window_color_set_impl(PyCursesWindowObject *self, int pair)
#endif
return curses_window_check_err(self, rtn, "wcolor_set", "color_set");
}
+#endif /* _Py_HAVE_CURSES_WCOLOR_SET */
/*[clinic input]
_curses.window.getattrs
@@ -2525,7 +2684,7 @@ static PyObject *
_curses_window_getattrs_impl(PyCursesWindowObject *self)
/*[clinic end generated code: output=835f499205204ec4 input=bf56a0af5b730bd1]*/
{
- return PyLong_FromUnsignedLong((unsigned long)(attr_t)getattrs(self->win));
+ return PyLong_FromUnsignedLongLong((unsigned long long)(attr_t)getattrs(self->win));
}
/*[clinic input]
@@ -2571,21 +2730,21 @@ _curses_window_bkgdset_impl(PyCursesWindowObject *self, PyObject *ch,
/*[clinic input]
_curses.window.border
- ls: object(c_default="NULL") = _curses.ACS_VLINE
+ ls: object(c_default="NULL") = 0
Left side.
- rs: object(c_default="NULL") = _curses.ACS_VLINE
+ rs: object(c_default="NULL") = 0
Right side.
- ts: object(c_default="NULL") = _curses.ACS_HLINE
+ ts: object(c_default="NULL") = 0
Top side.
- bs: object(c_default="NULL") = _curses.ACS_HLINE
+ bs: object(c_default="NULL") = 0
Bottom side.
- tl: object(c_default="NULL") = _curses.ACS_ULCORNER
+ tl: object(c_default="NULL") = 0
Upper-left corner.
- tr: object(c_default="NULL") = _curses.ACS_URCORNER
+ tr: object(c_default="NULL") = 0
Upper-right corner.
- bl: object(c_default="NULL") = _curses.ACS_LLCORNER
+ bl: object(c_default="NULL") = 0
Bottom-left corner.
- br: object(c_default="NULL") = _curses.ACS_LRCORNER
+ br: object(c_default="NULL") = 0
Bottom-right corner.
/
@@ -2602,7 +2761,7 @@ _curses_window_border_impl(PyCursesWindowObject *self, PyObject *ls,
PyObject *rs, PyObject *ts, PyObject *bs,
PyObject *tl, PyObject *tr, PyObject *bl,
PyObject *br)
-/*[clinic end generated code: output=670ef38d3d7c2aa3 input=42568c1458221d24]*/
+/*[clinic end generated code: output=670ef38d3d7c2aa3 input=d826ce9d6335479a]*/
{
chtype ch[8];
int i, rtn;
@@ -2615,36 +2774,49 @@ _curses_window_border_impl(PyCursesWindowObject *self, PyObject *ls,
#ifdef HAVE_NCURSESW
cchar_t wch[8];
const cchar_t *wch_p[8];
- int use_wide = 0;
- int types[8];
+ /* Only wborder_set() draws a complexchar and only wborder() an integer
+ or bytes character; a string character suits both, and so does the
+ integer 0, which asks for the default character. */
+ int has_narrow = 0, has_str = 0, has_cchar = 0;
for (i = 0; i < 8; i++) {
- types[i] = 0;
+ wch_p[i] = NULL; /* use the default character */
if (objs[i] != NULL) {
- types[i] = PyCurses_ConvertToCell(self, objs[i], A_NORMAL, 0,
+ int type = PyCurses_ConvertToCell(self, objs[i], A_NORMAL, 0,
"border", &ch[i], &wch[i]);
- if (types[i] == 0) {
+ if (type == 0) {
return NULL;
}
- if (types[i] == 2) {
- use_wide = 1;
+ if (type == 2) {
+ wch_p[i] = &wch[i];
+ if (PyUnicode_Check(objs[i])) {
+ has_str = 1;
+ }
+ else {
+ has_cchar = 1;
+ }
+ }
+ else if (!PyLong_CheckExact(objs[i]) || ch[i] != 0) {
+ has_narrow = 1; /* b'\0' is a byte character, not the 0 */
}
}
}
- if (use_wide) {
+ if (has_narrow) {
+ if (has_cchar) {
+ PyErr_SetString(PyExc_TypeError,
+ "border() cannot mix complexchar characters "
+ "with integer or bytes characters");
+ return NULL;
+ }
+ /* Narrow the string characters. */
for (i = 0; i < 8; i++) {
- if (objs[i] == NULL) {
- wch_p[i] = NULL; /* use the default character */
- }
- else if (types[i] == 2) {
- wch_p[i] = &wch[i];
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "border() cannot mix integer or bytes "
- "characters with wide string characters");
+ if (objs[i] != NULL && PyUnicode_Check(objs[i]) &&
+ !PyCurses_ConvertToChtype(self, objs[i], &ch[i]))
+ {
return NULL;
}
}
+ }
+ else if (has_str || has_cchar) {
rtn = wborder_set(self->win,
wch_p[0], wch_p[1], wch_p[2], wch_p[3],
wch_p[4], wch_p[5], wch_p[6], wch_p[7]);
@@ -2687,42 +2859,67 @@ _curses_window_box_impl(PyCursesWindowObject *self, int group_right_1,
PyObject *verch, PyObject *horch)
/*[clinic end generated code: output=f3fcb038bb287192 input=e11acb7dbf6790b6]*/
{
- chtype ch1 = 0, ch2 = 0;
+ chtype ch[2] = {0, 0};
+ PyObject *objs[2] = {verch, horch};
+ int i;
#ifdef HAVE_NCURSESW
- cchar_t wch1, wch2;
- int t1 = 0, t2 = 0;
+ cchar_t wch[2];
+ const cchar_t *wch_p[2] = {NULL, NULL};
+ int has_narrow = 0, has_str = 0, has_cchar = 0;
if (group_right_1) {
- t1 = PyCurses_ConvertToCell(self, verch, A_NORMAL, 0, "box", &ch1, &wch1);
- if (t1 == 0) {
- return NULL;
- }
- t2 = PyCurses_ConvertToCell(self, horch, A_NORMAL, 0, "box", &ch2, &wch2);
- if (t2 == 0) {
- return NULL;
+ for (i = 0; i < 2; i++) {
+ int type = PyCurses_ConvertToCell(self, objs[i], A_NORMAL, 0,
+ "box", &ch[i], &wch[i]);
+ if (type == 0) {
+ return NULL;
+ }
+ if (type == 2) {
+ wch_p[i] = &wch[i];
+ if (PyUnicode_Check(objs[i])) {
+ has_str = 1;
+ }
+ else {
+ has_cchar = 1;
+ }
+ }
+ else if (!PyLong_CheckExact(objs[i]) || ch[i] != 0) {
+ has_narrow = 1; /* b'\0' is a byte character, not the 0 */
+ }
}
}
- if (t1 == 2 || t2 == 2) {
- if (t1 != 2 || t2 != 2) {
+ if (has_narrow) {
+ if (has_cchar) {
PyErr_SetString(PyExc_TypeError,
- "box() cannot mix integer or bytes characters "
- "with wide string characters");
+ "box() cannot mix complexchar characters "
+ "with integer or bytes characters");
return NULL;
}
- int rtn = wborder_set(self->win, &wch1, &wch1, &wch2, &wch2,
- NULL, NULL, NULL, NULL);
- return curses_window_check_err(self, rtn, "wborder_set", "box");
+ /* Narrow the string characters. */
+ for (i = 0; i < 2; i++) {
+ if (PyUnicode_Check(objs[i]) &&
+ !PyCurses_ConvertToChtype(self, objs[i], &ch[i]))
+ {
+ return NULL;
+ }
+ }
+ }
+ else if (has_str || has_cchar) {
+ int rtn = box_set(self->win, wch_p[0], wch_p[1]);
+ return curses_window_check_err(self, rtn, "box_set", "box");
}
#else
if (group_right_1) {
- if (!PyCurses_ConvertToCell(self, verch, A_NORMAL, 0, "box", &ch1)) {
- return NULL;
- }
- if (!PyCurses_ConvertToCell(self, horch, A_NORMAL, 0, "box", &ch2)) {
- return NULL;
+ for (i = 0; i < 2; i++) {
+ if (!PyCurses_ConvertToCell(self, objs[i], A_NORMAL, 0, "box",
+ &ch[i]))
+ {
+ return NULL;
+ }
}
}
#endif
- return curses_window_check_err(self, box(self->win, ch1, ch2), "box", NULL);
+ return curses_window_check_err(self, box(self->win, ch[0], ch[1]),
+ "box", NULL);
}
#if defined(HAVE_NCURSES_H) || defined(MVWDELCH_IS_EXPRESSION)
@@ -2748,73 +2945,50 @@ int py_mvwdelch(WINDOW *w, int y, int x)
/* chgat, added by Fabian Kreutz */
#ifdef HAVE_CURSES_WCHGAT
-PyDoc_STRVAR(_curses_window_chgat__doc__,
-"chgat([y, x,] [n=-1,] attr)\n"
-"Set the attributes of characters.\n"
-"\n"
-" y\n"
-" Y-coordinate.\n"
-" x\n"
-" X-coordinate.\n"
-" n\n"
-" Number of characters.\n"
-" attr\n"
-" Attributes for characters.\n"
-"\n"
-"Set the attributes of num characters at the current cursor position, or at\n"
-"position (y, x) if supplied. If no value of num is given or num = -1, the\n"
-"attribute will be set on all the characters to the end of the line. This\n"
-"function does not move the cursor. The changed line will be touched using\n"
-"the touchline() method so that the contents will be redisplayed by the next\n"
-"window refresh.");
+/*[clinic input]
+_curses.window.chgat
+
+ [
+ y: int
+ Y-coordinate.
+ x: int
+ X-coordinate.
+ ]
+ [
+ n: int = -1
+ Number of characters.
+ ]
+ attr: attr
+ Attributes for characters.
+ /
+
+Set the attributes of characters.
+
+Set the attributes of n characters at the current cursor position,
+or at position (y, x) if supplied. If no value of n is given or
+n = -1, the attribute will be set on all the characters to the end
+of the line. This function does not move the cursor. The changed
+line will be touched using the touchline() method so that the
+contents will be redisplayed by the next window refresh.
+[clinic start generated code]*/
static PyObject *
-PyCursesWindow_ChgAt(PyObject *op, PyObject *args)
+_curses_window_chgat_impl(PyCursesWindowObject *self, int group_left_1,
+ int y, int x, int group_left_2, int n, attr_t attr)
+/*[clinic end generated code: output=b990d21c13383874 input=e5ad3c2716927e44]*/
{
- PyCursesWindowObject *self = _PyCursesWindowObject_CAST(op);
-
int rtn;
const char *funcname;
- int x, y;
- int num = -1;
- short color;
- attr_t attr = A_NORMAL;
- int use_xy = FALSE;
-
- switch (PyTuple_Size(args)) {
- case 1:
- if (!PyArg_ParseTuple(args,"O&;attr", attr_converter, &attr))
- return NULL;
- break;
- case 2:
- if (!PyArg_ParseTuple(args,"iO&;n,attr", &num, attr_converter, &attr))
- return NULL;
- break;
- case 3:
- if (!PyArg_ParseTuple(args,"iiO&;y,x,attr", &y, &x, attr_converter, &attr))
- return NULL;
- use_xy = TRUE;
- break;
- case 4:
- if (!PyArg_ParseTuple(args,"iiiO&;y,x,n,attr", &y, &x, &num, attr_converter, &attr))
- return NULL;
- use_xy = TRUE;
- break;
- default:
- PyErr_SetString(PyExc_TypeError,
- "_curses.window.chgat requires 1 to 4 arguments");
- return NULL;
- }
+ short color = (short) PAIR_NUMBER(attr);
- color = (short) PAIR_NUMBER(attr);
attr = attr & A_ATTRIBUTES;
- if (use_xy) {
- rtn = mvwchgat(self->win,y,x,num,attr,color,NULL);
+ if (group_left_1) {
+ rtn = mvwchgat(self->win,y,x,n,attr,color,NULL);
funcname = "mvwchgat";
} else {
getyx(self->win,y,x);
- rtn = wchgat(self->win,num,attr,color,NULL);
+ rtn = wchgat(self->win,n,attr,color,NULL);
funcname = "wchgat";
}
if (rtn == ERR) {
@@ -2948,6 +3122,10 @@ _curses_window_echochar_impl(PyCursesWindowObject *self, PyObject *ch,
int group_right_1, attr_t attr)
/*[clinic end generated code: output=ab03afa580aa6a2a input=cd74c42aadcc7e30]*/
{
+ if (!curses_window_check_terminal(self)) {
+ return NULL;
+ }
+
chtype ch_;
#ifdef HAVE_NCURSESW
cchar_t wch;
@@ -3060,7 +3238,7 @@ _curses_window_getbkgd_impl(PyCursesWindowObject *self)
curses_window_set_error(self, "getbkgd", NULL);
return NULL;
}
- return PyLong_FromLong(rtn);
+ return PyLong_FromUnsignedLongLong(rtn);
}
/*[clinic input]
@@ -3179,21 +3357,32 @@ _curses.window.getch
]
/
-Get a character code from terminal keyboard.
+Read a key press and return it as an integer.
-The integer returned does not have to be in ASCII range: function
-keys, keypad keys and so on return numbers higher than 256. In
-no-delay mode, -1 is returned if there is no input, else getch()
-waits until a key is pressed.
+Wait until a key is pressed, or return -1 if the read is
+non-blocking or times out.
+
+An ordinary key is returned as the code of a single byte of its
+encoding in the current locale, so a character encoded with several
+bytes takes several calls. Use get_wch() to read it as a single
+character.
+
+In keypad mode function keys and other special keys are returned as
+one of the KEY_* constants, which cannot be mistaken for an ordinary
+key. Otherwise their bytes are returned one at a time.
[clinic start generated code]*/
static PyObject *
_curses_window_getch_impl(PyCursesWindowObject *self, int group_right_1,
int y, int x)
-/*[clinic end generated code: output=e1639e87d545e676 input=0dc5ff40e079787a]*/
+/*[clinic end generated code: output=e1639e87d545e676 input=882ddab9b41afbbd]*/
{
int rtn;
+ if (!curses_window_check_terminal(self)) {
+ return NULL;
+ }
+
Py_BEGIN_ALLOW_THREADS
if (!group_right_1) {
rtn = wgetch(self->win);
@@ -3227,21 +3416,25 @@ _curses.window.getkey
]
/
-Get a character (string) from terminal keyboard.
+Read a key press and return it as a str.
-Returning a string instead of an integer, as getch() does. Function
-keys, keypad keys and other special keys return a multibyte string
-containing the key name. In no-delay mode, an exception is raised
-if there is no input.
+Read as getch() does, but return an ordinary key as a one-character
+string, the byte decoded as Latin-1, and a special key as its name,
+such as 'KEY_UP'. Raise curses.error instead of returning -1 if
+there is no input.
[clinic start generated code]*/
static PyObject *
_curses_window_getkey_impl(PyCursesWindowObject *self, int group_right_1,
int y, int x)
-/*[clinic end generated code: output=8490a182db46b10f input=bd24a7da1ed9c73b]*/
+/*[clinic end generated code: output=8490a182db46b10f input=f054cf034c69e879]*/
{
int rtn;
+ if (!curses_window_check_terminal(self)) {
+ return NULL;
+ }
+
Py_BEGIN_ALLOW_THREADS
if (!group_right_1) {
rtn = wgetch(self->win);
@@ -3282,17 +3475,25 @@ _curses.window.get_wch
]
/
-Get a wide character from terminal keyboard.
+Read a key press and return it as a one-character str.
-Return a character for most keys, or an integer for function keys,
-keypad keys, and other special keys.
+Wait until a key is pressed, or raise curses.error if the read is
+non-blocking or times out.
+
+In keypad mode function keys and other special keys are returned as
+one of the KEY_* constants, an integer. Otherwise their characters
+are returned one at a time.
[clinic start generated code]*/
static PyObject *
_curses_window_get_wch_impl(PyCursesWindowObject *self, int group_right_1,
int y, int x)
-/*[clinic end generated code: output=9f4f86e91fe50ef3 input=dd7e5367fb49dc48]*/
+/*[clinic end generated code: output=9f4f86e91fe50ef3 input=77eb2da426ebe71f]*/
{
+ if (!curses_window_check_terminal(self)) {
+ return NULL;
+ }
+
#ifdef HAVE_NCURSESW
int ct;
wint_t rtn;
@@ -3341,71 +3542,37 @@ _curses_window_get_wch_impl(PyCursesWindowObject *self, int group_right_1,
#endif
}
-/*
- * Helper function for parsing parameters from getstr() and instr().
- * This function is necessary because Argument Clinic does not know
- * how to handle nested optional groups with default values inside.
- *
- * Return 1 on success and 0 on failure, similar to PyArg_ParseTuple().
- */
-static int
-curses_clinic_parse_optional_xy_n(PyObject *args,
- int *y, int *x, unsigned int *n, int *use_xy,
- const char *qualname)
-{
- switch (PyTuple_GET_SIZE(args)) {
- case 0: {
- *use_xy = 0;
- return 1;
- }
- case 1: {
- *use_xy = 0;
- return PyArg_ParseTuple(args, "O&;n",
- _PyLong_UnsignedInt_Converter, n);
- }
- case 2: {
- *use_xy = 1;
- return PyArg_ParseTuple(args, "ii;y,x", y, x);
- }
- case 3: {
- *use_xy = 1;
- return PyArg_ParseTuple(args, "iiO&;y,x,n", y, x,
- _PyLong_UnsignedInt_Converter, n);
- }
- default: {
- *use_xy = 0;
- PyErr_Format(PyExc_TypeError, "%s requires 0 to 3 arguments",
- qualname);
- return 0;
- }
+/* Characters one cell can hold. */
+#ifdef HAVE_NCURSESW
+#define CURSES_CELL_CHARS CCHARW_MAX
+#else
+#define CURSES_CELL_CHARS 1
+#endif
+
+/* The columns left on the line, in the unit the caller counts. */
+static unsigned int
+curses_window_read_limit(PyCursesWindowObject *self, int use_xy, int x,
+ unsigned int per_cell)
+{
+ int col = use_xy ? x : getcurx(self->win);
+ int maxx = getmaxx(self->win);
+ if (col < 0) {
+ col = 0;
}
+ if (col > maxx) {
+ return 0;
+ }
+ return ((unsigned int)(maxx - col) + 1) * per_cell;
}
-PyDoc_STRVAR(_curses_window_getstr__doc__,
-"getstr([[y, x,] n=2047])\n"
-"Read a string from the user, with primitive line editing capacity.\n"
-"\n"
-" y\n"
-" Y-coordinate.\n"
-" x\n"
-" X-coordinate.\n"
-" n\n"
-" Maximal number of characters.");
-
/* Read user input into a new bytes object (empty on ERR), with primitive line
editing. Shared by getstr() and, without the wide library, by get_wstr(). */
static PyObject *
-curses_window_getstr_bytes(PyCursesWindowObject *self, PyObject *args,
- const char *funcname)
+curses_window_getstr_bytes(PyCursesWindowObject *self, int use_xy,
+ int y, int x, unsigned int n)
{
- int rtn, use_xy = 0, y = 0, x = 0;
+ int rtn;
unsigned int max_buf_size = 2048;
- unsigned int n = max_buf_size - 1;
-
- if (!curses_clinic_parse_optional_xy_n(args, &y, &x, &n, &use_xy, funcname))
- {
- return NULL;
- }
n = Py_MIN(n, max_buf_size - 1);
PyBytesWriter *writer = PyBytesWriter_Create(n + 1);
@@ -3438,11 +3605,35 @@ curses_window_getstr_bytes(PyCursesWindowObject *self, PyObject *args,
return PyBytesWriter_FinishWithSize(writer, strlen(buf));
}
+/*[clinic input]
+_curses.window.getstr
+
+ [
+ y: int
+ Y-coordinate.
+ x: int
+ X-coordinate.
+ ]
+ n: unsigned_int = 2047
+ Maximal number of bytes.
+ /
+
+Read a line of input and return it as a bytes object.
+
+The input is read with primitive line editing capacity, encoded in
+the current locale, and does not include the terminating newline.
+At most n bytes are read.
+[clinic start generated code]*/
+
static PyObject *
-PyCursesWindow_getstr(PyObject *op, PyObject *args)
+_curses_window_getstr_impl(PyCursesWindowObject *self, int group_left_1,
+ int y, int x, unsigned int n)
+/*[clinic end generated code: output=bea9b0ab7e8f34d9 input=0335501e45f55caf]*/
{
- PyCursesWindowObject *self = _PyCursesWindowObject_CAST(op);
- return curses_window_getstr_bytes(self, args, "_curses.window.getstr");
+ if (!curses_window_check_terminal(self)) {
+ return NULL;
+ }
+ return curses_window_getstr_bytes(self, group_left_1, y, x, n);
}
/*[clinic input]
@@ -3544,6 +3735,24 @@ _curses_window_insch_impl(PyCursesWindowObject *self, int group_left_1,
if (type == 0) {
return NULL;
}
+ if (type == 1) {
+ /* winsch() does not locale-decode a byte above 127 on a wide build,
+ unlike waddch(), so decode it here and insert it as a wide
+ character. (gh-153864) */
+ chtype cch = ch_ & A_CHARTEXT;
+ if (cch > 127) {
+ wint_t wc = btowc((int)cch);
+ if (wc != WEOF) {
+ wchar_t wstr[2] = { (wchar_t)wc, L'\0' };
+ attr_t cattr = (attr_t)((ch_ | attr) & ~(chtype)A_CHARTEXT);
+ if (curses_setcchar(&wch, wstr, cattr, PAIR_NUMBER(cattr)) == ERR) {
+ curses_window_set_error(self, "setcchar", "insch");
+ return NULL;
+ }
+ type = 2;
+ }
+ }
+ }
if (type == 2) {
if (!group_left_1) {
rtn = wins_wch(self->win, &wch);
@@ -3596,7 +3805,39 @@ _curses_window_inch_impl(PyCursesWindowObject *self, int group_right_1,
{
chtype rtn;
const char *funcname;
-
+#ifdef HAVE_NCURSESW
+ /* ncursesw's winch() returns the whole code point, which overflows the
+ chtype's 8-bit character field into the color and attribute bits. */
+ cchar_t cell = {0};
+ int rc;
+ if (!group_right_1) {
+ rc = win_wch(self->win, &cell);
+ funcname = "win_wch";
+ }
+ else {
+ rc = mvwin_wch(self->win, y, x, &cell);
+ funcname = "mvwin_wch";
+ }
+ if (rc == ERR) {
+ curses_window_set_error(self, funcname, "inch");
+ return NULL;
+ }
+ wchar_t wstr[CCHARW_MAX + 1];
+ attr_t attrs;
+ int pair;
+ if (curses_getcchar(&cell, wstr, &attrs, &pair) == ERR) {
+ curses_window_set_error(self, "getcchar", "inch");
+ return NULL;
+ }
+ int byte = 0;
+ if (wstr[0] != L'\0' && wstr[1] == L'\0') {
+ byte = wctob(wstr[0]);
+ if (byte == EOF) {
+ byte = 0;
+ }
+ }
+ rtn = (chtype)byte | attrs | COLOR_PAIR(pair);
+#else
if (!group_right_1) {
rtn = winch(self->win);
funcname = "winch";
@@ -3609,98 +3850,112 @@ _curses_window_inch_impl(PyCursesWindowObject *self, int group_right_1,
curses_window_set_error(self, funcname, "inch");
return NULL;
}
- return PyLong_FromUnsignedLong(rtn);
+#endif
+ return PyLong_FromUnsignedLongLong(rtn);
}
-PyDoc_STRVAR(_curses_window_instr__doc__,
-"instr([y, x,] n=2047)\n"
-"Return a string of characters, extracted from the window.\n"
-"\n"
-" y\n"
-" Y-coordinate.\n"
-" x\n"
-" X-coordinate.\n"
-" n\n"
-" Maximal number of characters.\n"
-"\n"
-"Return a string of characters, extracted from the window starting\n"
-"at the current cursor position, or at y, x if specified, and\n"
-"stopping at the end of the line. Attributes and color\n"
-"information are stripped from the characters. If n is specified,\n"
-"instr() returns a string at most n characters long (exclusive of\n"
-"the trailing NUL).");
-
/* Extract characters from the window into a new bytes object (empty on ERR),
with attributes and color stripped. Shared by instr() and, without the wide
library, by in_wstr(). */
static PyObject *
-curses_window_instr_bytes(PyCursesWindowObject *self, PyObject *args,
- const char *funcname)
+curses_window_instr_bytes(PyCursesWindowObject *self, int use_xy, int use_n,
+ int y, int x, unsigned int n)
{
- int rtn, use_xy = 0, y = 0, x = 0;
- unsigned int max_buf_size = 2048;
- unsigned int n = max_buf_size - 1;
-
- if (!curses_clinic_parse_optional_xy_n(args, &y, &x, &n, &use_xy, funcname))
- {
- return NULL;
- }
-
- n = Py_MIN(n, max_buf_size - 1);
- PyBytesWriter *writer = PyBytesWriter_Create(n + 1);
+ int rtn;
+ unsigned int limit = curses_window_read_limit(self, use_xy, x,
+ CURSES_CELL_CHARS
+ * (unsigned int)MB_CUR_MAX);
+ unsigned int nread = use_n ? Py_MIN(n, limit) : limit;
+ PyBytesWriter *writer = PyBytesWriter_Create(nread + CURSES_STR_EXTRA + 1);
if (writer == NULL) {
return NULL;
}
char *buf = PyBytesWriter_GetData(writer);
- if (use_xy) {
- rtn = mvwinnstr(self->win, y, x, buf, n);
- }
- else {
- rtn = winnstr(self->win, buf, n);
+ /* Read again if the library stored more than asked: truncating could
+ split a multibyte character. */
+ for (unsigned int ask = nread + CURSES_STR_EXTRA; ; ask = nread) {
+ if (use_xy) {
+ rtn = mvwinnstr(self->win, y, x, buf, ask);
+ }
+ else {
+ rtn = winnstr(self->win, buf, ask);
+ }
+ if (rtn == ERR || (unsigned int)rtn <= nread) {
+ break;
+ }
}
if (rtn == ERR) {
PyBytesWriter_Discard(writer);
return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
}
- return PyBytesWriter_FinishWithSize(writer, strlen(buf));
+ return PyBytesWriter_FinishWithSize(writer, rtn);
}
+/*[clinic input]
+_curses.window.instr
+
+ [
+ y: int
+ Y-coordinate.
+ x: int
+ X-coordinate.
+ ]
+ [
+ n: unsigned_int
+ Maximal number of bytes. The rest of the line by default.
+ ]
+ /
+
+Return the text of the window as a bytes object.
+
+Read from the current cursor position, or from y, x if specified, to
+the end of the line or at most n bytes if n is specified, and return
+the text in the encoding of the current locale, with attributes and
+color pairs stripped.
+[clinic start generated code]*/
+
static PyObject *
-PyCursesWindow_instr(PyObject *op, PyObject *args)
+_curses_window_instr_impl(PyCursesWindowObject *self, int group_right_1,
+ int y, int x, int group_right_2, unsigned int n)
+/*[clinic end generated code: output=2428948b44ad10c7 input=9307eca4bd576899]*/
{
- PyCursesWindowObject *self = _PyCursesWindowObject_CAST(op);
- return curses_window_instr_bytes(self, args, "_curses.window.instr");
+ return curses_window_instr_bytes(self, group_right_1, group_right_2,
+ y, x, n);
}
-PyDoc_STRVAR(_curses_window_get_wstr__doc__,
-"get_wstr([[y, x,] n=2047])\n"
-"Read a string from the user, with primitive line editing capacity.\n"
-"\n"
-" y\n"
-" Y-coordinate.\n"
-" x\n"
-" X-coordinate.\n"
-" n\n"
-" Maximal number of characters.\n"
-"\n"
-"This is the wide-character variant of getstr(); it returns a str.");
+/*[clinic input]
+_curses.window.get_wstr
+
+ [
+ y: int
+ Y-coordinate.
+ x: int
+ X-coordinate.
+ ]
+ n: unsigned_int = 2047
+ Maximal number of characters.
+ /
+
+Read a line of input and return it as a str.
+
+This is the wide-character variant of getstr(). The input is read
+with primitive line editing capacity and does not include the
+terminating newline. At most n characters are read.
+[clinic start generated code]*/
static PyObject *
-PyCursesWindow_get_wstr(PyObject *op, PyObject *args)
+_curses_window_get_wstr_impl(PyCursesWindowObject *self, int group_left_1,
+ int y, int x, unsigned int n)
+/*[clinic end generated code: output=e0a6670551cbe79f input=8920c99e9134670b]*/
{
- PyCursesWindowObject *self = _PyCursesWindowObject_CAST(op);
-#ifdef HAVE_NCURSESW
- int rtn, use_xy = 0, y = 0, x = 0;
- unsigned int max_buf_size = 2048;
- unsigned int n = max_buf_size - 1;
-
- if (!curses_clinic_parse_optional_xy_n(args, &y, &x, &n, &use_xy,
- "_curses.window.get_wstr"))
- {
+ if (!curses_window_check_terminal(self)) {
return NULL;
}
+#ifdef HAVE_NCURSESW
+ int rtn;
+ unsigned int max_buf_size = 2048;
n = Py_MIN(n, max_buf_size - 1);
wint_t *buf = PyMem_New(wint_t, n + 1);
@@ -3708,7 +3963,7 @@ PyCursesWindow_get_wstr(PyObject *op, PyObject *args)
return PyErr_NoMemory();
}
- if (use_xy) {
+ if (group_left_1) {
Py_BEGIN_ALLOW_THREADS
rtn = mvwgetn_wstr(self->win, y, x, buf, n);
Py_END_ALLOW_THREADS
@@ -3744,8 +3999,7 @@ PyCursesWindow_get_wstr(PyObject *op, PyObject *args)
#else
/* Without the wide library, read the bytes as getstr() does and decode them
with the window's encoding. */
- PyObject *bytes = curses_window_getstr_bytes(self, args,
- "_curses.window.get_wstr");
+ PyObject *bytes = curses_window_getstr_bytes(self, group_left_1, y, x, n);
if (bytes == NULL) {
return NULL;
}
@@ -3757,59 +4011,70 @@ PyCursesWindow_get_wstr(PyObject *op, PyObject *args)
#endif /* HAVE_NCURSESW */
}
-PyDoc_STRVAR(_curses_window_in_wstr__doc__,
-"in_wstr([y, x,] n=2047)\n"
-"Return a string of characters, extracted from the window.\n"
-"\n"
-" y\n"
-" Y-coordinate.\n"
-" x\n"
-" X-coordinate.\n"
-" n\n"
-" Maximal number of characters.\n"
-"\n"
-"This is the wide-character variant of instr(); it returns a str.");
+/*[clinic input]
+_curses.window.in_wstr
+
+ [
+ y: int
+ Y-coordinate.
+ x: int
+ X-coordinate.
+ ]
+ [
+ n: unsigned_int
+ Maximal number of characters. The rest of the line by default.
+ ]
+ /
+
+Return the text of the window as a str.
+
+This is the wide-character variant of instr(). Read from the
+current cursor position, or from y, x if specified, to the end of
+the line or at most n characters if n is specified, with attributes
+and color pairs stripped.
+[clinic start generated code]*/
static PyObject *
-PyCursesWindow_in_wstr(PyObject *op, PyObject *args)
+_curses_window_in_wstr_impl(PyCursesWindowObject *self, int group_right_1,
+ int y, int x, int group_right_2, unsigned int n)
+/*[clinic end generated code: output=d8c8bcfe8a26f519 input=5ba908338a94bfc8]*/
{
- PyCursesWindowObject *self = _PyCursesWindowObject_CAST(op);
#ifdef HAVE_NCURSESW
- int rtn, use_xy = 0, y = 0, x = 0;
- unsigned int max_buf_size = 2048;
- unsigned int n = max_buf_size - 1;
-
- if (!curses_clinic_parse_optional_xy_n(args, &y, &x, &n, &use_xy,
- "_curses.window.in_wstr"))
- {
- return NULL;
- }
-
- n = Py_MIN(n, max_buf_size - 1);
- wchar_t *buf = PyMem_New(wchar_t, n + 1);
+ int rtn;
+ unsigned int limit = curses_window_read_limit(self, group_right_1, x,
+ CURSES_CELL_CHARS);
+ unsigned int nread = group_right_2 ? Py_MIN(n, limit) : limit;
+ wchar_t *buf = PyMem_New(wchar_t, nread + CURSES_STR_EXTRA + 1);
if (buf == NULL) {
return PyErr_NoMemory();
}
-
- if (use_xy) {
- rtn = mvwinnwstr(self->win, y, x, buf, n);
- }
- else {
- rtn = winnwstr(self->win, buf, n);
+
+ /* Read again if the library stored more than asked: truncating could
+ separate a combining character from its base. */
+ for (unsigned int ask = nread + CURSES_STR_EXTRA; ; ask = nread) {
+ if (group_right_1) {
+ rtn = mvwinnwstr(self->win, y, x, buf, ask);
+ }
+ else {
+ rtn = winnwstr(self->win, buf, ask);
+ }
+ if (rtn == ERR || (unsigned int)rtn <= nread) {
+ break;
+ }
}
if (rtn == ERR) {
PyMem_Free(buf);
return Py_GetConstant(Py_CONSTANT_EMPTY_STR);
}
- PyObject *res = PyUnicode_FromWideChar(buf, -1);
+ PyObject *res = PyUnicode_FromWideChar(buf, rtn);
PyMem_Free(buf);
return res;
#else
/* Without the wide library, read the bytes as instr() does and decode them
with the window's encoding. */
- PyObject *bytes = curses_window_instr_bytes(self, args,
- "_curses.window.in_wstr");
+ PyObject *bytes = curses_window_instr_bytes(self, group_right_1,
+ group_right_2, y, x, n);
if (bytes == NULL) {
return NULL;
}
@@ -3821,50 +4086,55 @@ PyCursesWindow_in_wstr(PyObject *op, PyObject *args)
#endif
}
-PyDoc_STRVAR(_curses_window_in_wchstr__doc__,
-"in_wchstr([y, x,] n=2047)\n"
-"Return a complexstr of the styled cells extracted from the window.\n"
-"\n"
-" y\n"
-" Y-coordinate.\n"
-" x\n"
-" X-coordinate.\n"
-" n\n"
-" Maximal number of cells.\n"
-"\n"
-"This is the wide-character variant of instr() and in_wstr() that keeps\n"
-"each cell's attributes and color pair; it returns a complexstr.");
+/*[clinic input]
+_curses.window.in_wchstr
-static PyObject *
-PyCursesWindow_in_wchstr(PyObject *op, PyObject *args)
-{
- PyCursesWindowObject *self = _PyCursesWindowObject_CAST(op);
- int rtn, use_xy = 0, y = 0, x = 0;
- unsigned int max_buf_size = 2048;
- unsigned int n = max_buf_size - 1;
+ [
+ y: int
+ Y-coordinate.
+ x: int
+ X-coordinate.
+ ]
+ [
+ n: unsigned_int
+ Maximal number of cells. The rest of the line by default.
+ ]
+ /
- if (!curses_clinic_parse_optional_xy_n(args, &y, &x, &n, &use_xy,
- "_curses.window.in_wchstr"))
- {
- return NULL;
- }
+Return the styled cells of the window as a complexstr.
- n = Py_MIN(n, max_buf_size - 1);
+Read from the current cursor position, or from y, x if specified,
+to the end of the line or at most n cells if n is specified.
+Unlike instr() and in_wstr(), each cell keeps its attributes and
+color pair, so the result can be written back unchanged with
+addstr().
+[clinic start generated code]*/
+
+static PyObject *
+_curses_window_in_wchstr_impl(PyCursesWindowObject *self, int group_right_1,
+ int y, int x, int group_right_2,
+ unsigned int n)
+/*[clinic end generated code: output=3807a62d51efd44f input=50400321de1db1da]*/
+{
+ int rtn;
+ unsigned int limit = curses_window_read_limit(self, group_right_1, x, 1);
+ unsigned int nread = group_right_2 ? Py_MIN(n, limit) : limit;
+ unsigned int ask = nread + CURSES_STR_EXTRA;
cursesmodule_state *state = get_cursesmodule_state_by_win(self);
/* Zero the cells: reading a cell back through getcchar() relies on the
cchar_t text array being NUL-terminated, which some curses libraries
only guarantee for the characters they actually write. */
- curses_cell_t *buf = PyMem_Calloc(n + 1, sizeof(curses_cell_t));
+ curses_cell_t *buf = PyMem_Calloc(ask + 1, sizeof(curses_cell_t));
if (buf == NULL) {
return PyErr_NoMemory();
}
#ifdef HAVE_NCURSESW
- if (use_xy) {
- rtn = mvwin_wchnstr(self->win, y, x, buf, n);
+ if (group_right_1) {
+ rtn = mvwin_wchnstr(self->win, y, x, buf, ask);
}
else {
- rtn = win_wchnstr(self->win, buf, n);
+ rtn = win_wchnstr(self->win, buf, ask);
}
if (rtn == ERR) {
@@ -3872,11 +4142,11 @@ PyCursesWindow_in_wchstr(PyObject *op, PyObject *args)
return PyCursesComplexStr_New(state, NULL, 0);
}
- /* win_wchnstr() stores at most n cells and zero-terminates the array at
- the actual count; every real cell holds at least a space, so the first
+ /* win_wchnstr() stores at most nread cells and zero-terminates the array
+ at the actual count; every real cell holds at least a space, so the first
empty cell marks the end of the run. */
Py_ssize_t count = 0;
- while (count < (Py_ssize_t)n) {
+ while (count < (Py_ssize_t)nread) {
wchar_t wstr[CCHARW_MAX + 1];
attr_t attrs;
int pair;
@@ -3891,12 +4161,12 @@ PyCursesWindow_in_wchstr(PyObject *op, PyObject *args)
/* winchnstr() is not guaranteed (SVr4) to terminate the array, so pre-zero
it and stop at the first empty cell; a painted cell always holds at least
a space, never 0. */
- memset(buf, 0, ((size_t)n + 1) * sizeof(curses_cell_t));
- if (use_xy) {
- rtn = mvwinchnstr(self->win, y, x, buf, n);
+ memset(buf, 0, ((size_t)ask + 1) * sizeof(curses_cell_t));
+ if (group_right_1) {
+ rtn = mvwinchnstr(self->win, y, x, buf, ask);
}
else {
- rtn = winchnstr(self->win, buf, n);
+ rtn = winchnstr(self->win, buf, ask);
}
if (rtn == ERR) {
@@ -3905,7 +4175,7 @@ PyCursesWindow_in_wchstr(PyObject *op, PyObject *args)
}
Py_ssize_t count = 0;
- while (count < (Py_ssize_t)n && buf[count] != 0) {
+ while (count < (Py_ssize_t)nread && buf[count] != 0) {
count++;
}
#endif
@@ -3955,6 +4225,7 @@ _curses_window_insstr_impl(PyCursesWindowObject *self, int group_left_1,
wchar_t *wstr = NULL;
#endif
attr_t attr_old = A_NORMAL;
+ int pair_old = 0;
int use_xy = group_left_1, use_attr = group_right_1;
const char *funcname;
@@ -3979,8 +4250,9 @@ _curses_window_insstr_impl(PyCursesWindowObject *self, int group_left_1,
return NULL;
if (use_attr) {
- attr_old = getattrs(self->win);
- if (curses_wattrset(self, attr, "insstr") < 0) {
+ if (curses_wattr_save(self, &attr_old, &pair_old, "insstr") < 0 ||
+ curses_wattrset(self, attr, "insstr") < 0)
+ {
curses_release_wstr(strtype, wstr);
Py_XDECREF(bytesobj);
return NULL;
@@ -3988,7 +4260,7 @@ _curses_window_insstr_impl(PyCursesWindowObject *self, int group_left_1,
}
#ifdef HAVE_NCURSESW
if (strtype == 2) {
- if (use_xy) {
+ if (group_left_1) {
rtn = mvwins_wstr(self->win,y,x,wstr);
funcname = "mvwins_wstr";
}
@@ -4002,7 +4274,7 @@ _curses_window_insstr_impl(PyCursesWindowObject *self, int group_left_1,
#endif
{
const char *str = PyBytes_AS_STRING(bytesobj);
- if (use_xy) {
+ if (group_left_1) {
rtn = mvwinsstr(self->win,y,x,str);
funcname = "mvwinsstr";
}
@@ -4012,15 +4284,14 @@ _curses_window_insstr_impl(PyCursesWindowObject *self, int group_left_1,
}
Py_DECREF(bytesobj);
}
- if (rtn == ERR) {
- curses_window_set_error(self, funcname, "insstr");
- return NULL;
- }
if (use_attr) {
- rtn = wattrset(self->win, attr_old);
- return curses_window_check_err(self, rtn, "wattrset", "insstr");
+ int attr_rtn = curses_wattr_restore(self, attr_old, pair_old);
+ if (rtn != ERR) {
+ rtn = attr_rtn;
+ funcname = _CURSES_WATTR_RESTORE_FUNC;
+ }
}
- Py_RETURN_NONE;
+ return curses_window_check_err(self, rtn, funcname, "insstr");
}
/*[clinic input]
@@ -4068,6 +4339,7 @@ _curses_window_insnstr_impl(PyCursesWindowObject *self, int group_left_1,
wchar_t *wstr = NULL;
#endif
attr_t attr_old = A_NORMAL;
+ int pair_old = 0;
int use_xy = group_left_1, use_attr = group_right_1;
const char *funcname;
@@ -4092,15 +4364,17 @@ _curses_window_insnstr_impl(PyCursesWindowObject *self, int group_left_1,
return NULL;
if (use_attr) {
- attr_old = getattrs(self->win);
- if (curses_wattrset(self, attr, "insnstr") < 0) {
+ if (curses_wattr_save(self, &attr_old, &pair_old, "insnstr") < 0 ||
+ curses_wattrset(self, attr, "insnstr") < 0)
+ {
curses_release_wstr(strtype, wstr);
+ Py_XDECREF(bytesobj);
return NULL;
}
}
#ifdef HAVE_NCURSESW
if (strtype == 2) {
- if (use_xy) {
+ if (group_left_1) {
rtn = mvwins_nwstr(self->win,y,x,wstr,n);
funcname = "mvwins_nwstr";
}
@@ -4114,7 +4388,7 @@ _curses_window_insnstr_impl(PyCursesWindowObject *self, int group_left_1,
#endif
{
const char *str = PyBytes_AS_STRING(bytesobj);
- if (use_xy) {
+ if (group_left_1) {
rtn = mvwinsnstr(self->win,y,x,str,n);
funcname = "mvwinsnstr";
}
@@ -4124,15 +4398,14 @@ _curses_window_insnstr_impl(PyCursesWindowObject *self, int group_left_1,
}
Py_DECREF(bytesobj);
}
- if (rtn == ERR) {
- curses_window_set_error(self, funcname, "insnstr");
- return NULL;
- }
if (use_attr) {
- rtn = wattrset(self->win, attr_old);
- return curses_window_check_err(self, rtn, "wattrset", "insnstr");
+ int attr_rtn = curses_wattr_restore(self, attr_old, pair_old);
+ if (rtn != ERR) {
+ rtn = attr_rtn;
+ funcname = _CURSES_WATTR_RESTORE_FUNC;
+ }
}
- Py_RETURN_NONE;
+ return curses_window_check_err(self, rtn, funcname, "insnstr");
}
/*[clinic input]
@@ -4207,6 +4480,10 @@ _curses_window_noutrefresh_impl(PyCursesWindowObject *self)
{
int rtn;
+ if (!curses_window_check_terminal(self)) {
+ return NULL;
+ }
+
#ifdef py_is_pad
if (py_is_pad(self->win)) {
if (!group_right_1) {
@@ -4437,6 +4714,10 @@ _curses_window_refresh_impl(PyCursesWindowObject *self, int group_right_1,
{
int rtn;
+ if (!curses_window_check_terminal(self)) {
+ return NULL;
+ }
+
#ifdef py_is_pad
if (py_is_pad(self->win)) {
if (!group_right_1) {
@@ -4754,7 +5035,7 @@ static PyType_Spec PyCursesComplexStr_Type_spec = {
};
#undef clinic_state
-#if defined(HAVE_CURSES_USE_SCREEN) || defined(HAVE_CURSES_USE_WINDOW)
+#if defined(_Py_HAVE_CURSES_USE_SCREEN) || defined(_Py_HAVE_CURSES_USE_WINDOW)
/* Shared trampoline for window.use()/screen.use(): call
func(obj, *extra, **kwargs) and store the result (NULL on exception) in
data->result. */
@@ -4804,7 +5085,7 @@ curses_use_parse(PyObject *args, PyObject **func, PyObject **extra)
}
#endif
-#ifdef HAVE_CURSES_USE_WINDOW
+#ifdef _Py_HAVE_CURSES_USE_WINDOW
static int
curses_use_window_cb(WINDOW *Py_UNUSED(win), void *data)
{
@@ -4830,7 +5111,7 @@ PyCursesWindow_use(PyObject *self, PyObject *args, PyObject *kwargs)
Py_DECREF(extra);
return data.result;
}
-#endif /* HAVE_CURSES_USE_WINDOW */
+#endif /* _Py_HAVE_CURSES_USE_WINDOW */
static PyMethodDef PyCursesWindow_methods[] = {
_CURSES_WINDOW_ADDCH_METHODDEF
@@ -4846,12 +5127,7 @@ static PyMethodDef PyCursesWindow_methods[] = {
_CURSES_WINDOW_COLOR_SET_METHODDEF
_CURSES_WINDOW_GETATTRS_METHODDEF
_CURSES_WINDOW_BKGD_METHODDEF
-#ifdef HAVE_CURSES_WCHGAT
- {
- "chgat", PyCursesWindow_ChgAt, METH_VARARGS,
- _curses_window_chgat__doc__
- },
-#endif
+ _CURSES_WINDOW_CHGAT_METHODDEF
_CURSES_WINDOW_BKGDSET_METHODDEF
_CURSES_WINDOW_BORDER_METHODDEF
_CURSES_WINDOW_BOX_METHODDEF
@@ -4899,11 +5175,9 @@ static PyMethodDef PyCursesWindow_methods[] = {
{"getmaxyx", PyCursesWindow_getmaxyx, METH_NOARGS,
"getmaxyx($self, /)\n--\n\n"
"Return a tuple (y, x) of the window height and width."},
-#if (defined(NCURSES_EXT_FUNCS) && NCURSES_EXT_FUNCS >= 20110404) || defined(PDCURSES)
{"getparent", PyCursesWindow_getparent, METH_NOARGS,
"getparent($self, /)\n--\n\n"
"Return the parent window, or None if this is not a subwindow."},
-#endif
{"getparyx", PyCursesWindow_getparyx, METH_NOARGS,
"getparyx($self, /)\n--\n\n"
"Return (y, x) relative to the parent window, or (-1, -1) if none."},
@@ -4912,14 +5186,8 @@ static PyMethodDef PyCursesWindow_methods[] = {
"getscrreg($self, /)\n--\n\n"
"Return a tuple (top, bottom) of the current scrolling region."},
#endif
- {
- "getstr", PyCursesWindow_getstr, METH_VARARGS,
- _curses_window_getstr__doc__
- },
- {
- "get_wstr", PyCursesWindow_get_wstr, METH_VARARGS,
- _curses_window_get_wstr__doc__
- },
+ _CURSES_WINDOW_GETSTR_METHODDEF
+ _CURSES_WINDOW_GET_WSTR_METHODDEF
{"getyx", PyCursesWindow_getyx, METH_NOARGS,
"getyx($self, /)\n--\n\n"
"Return a tuple (y, x) of the current cursor position."},
@@ -4946,18 +5214,9 @@ static PyMethodDef PyCursesWindow_methods[] = {
"Insert a blank line under the cursor; move following lines down."},
_CURSES_WINDOW_INSNSTR_METHODDEF
_CURSES_WINDOW_INSSTR_METHODDEF
- {
- "instr", PyCursesWindow_instr, METH_VARARGS,
- _curses_window_instr__doc__
- },
- {
- "in_wstr", PyCursesWindow_in_wstr, METH_VARARGS,
- _curses_window_in_wstr__doc__
- },
- {
- "in_wchstr", PyCursesWindow_in_wchstr, METH_VARARGS,
- _curses_window_in_wchstr__doc__
- },
+ _CURSES_WINDOW_INSTR_METHODDEF
+ _CURSES_WINDOW_IN_WSTR_METHODDEF
+ _CURSES_WINDOW_IN_WCHSTR_METHODDEF
_CURSES_WINDOW_IS_LINETOUCHED_METHODDEF
{"is_wintouched", PyCursesWindow_is_wintouched, METH_NOARGS,
"is_wintouched($self, /)\n--\n\n"
@@ -4991,12 +5250,12 @@ static PyMethodDef PyCursesWindow_methods[] = {
"is_syncok($self, /)\n--\n\n"
"Return the current value set by syncok()."},
#endif
-#if defined(HAVE_CURSES_IS_KEYPAD) || defined(PDCURSES)
+#if defined(_Py__Py_HAVE_CURSES_IS_KEYPAD) || defined(PDCURSES)
{"is_keypad", PyCursesWindow_is_keypad, METH_NOARGS,
"is_keypad($self, /)\n--\n\n"
"Return the current value set by keypad()."},
#endif
-#if defined(HAVE_CURSES_IS_LEAVEOK) || defined(PDCURSES)
+#if defined(_Py_HAVE_CURSES_IS_LEAVEOK) || defined(PDCURSES)
{"is_leaveok", PyCursesWindow_is_leaveok, METH_NOARGS,
"is_leaveok($self, /)\n--\n\n"
"Return the current value set by leaveok()."},
@@ -5052,7 +5311,8 @@ static PyMethodDef PyCursesWindow_methods[] = {
{"standout", PyCursesWindow_wstandout, METH_NOARGS,
"standout($self, /)\n--\n\n"
"Turn on the A_STANDOUT attribute."},
- {"subpad", _curses_window_subwin, METH_VARARGS, _curses_window_subwin__doc__},
+ {"subpad", _PyCFunction_CAST(_curses_window_subwin), METH_FASTCALL,
+ _curses_window_subwin__doc__},
_CURSES_WINDOW_SUBWIN_METHODDEF
{"syncdown", PyCursesWindow_wsyncdown, METH_NOARGS,
"syncdown($self, /)\n--\n\n"
@@ -5076,7 +5336,7 @@ static PyMethodDef PyCursesWindow_methods[] = {
"untouchwin($self, /)\n--\n\n"
"Mark all lines in the window as unchanged since last refresh()."},
_CURSES_WINDOW_VLINE_METHODDEF
-#ifdef HAVE_CURSES_USE_WINDOW
+#ifdef _Py_HAVE_CURSES_USE_WINDOW
{"use", _PyCFunction_CAST(PyCursesWindow_use),
METH_VARARGS | METH_KEYWORDS, PyCursesWindow_use__doc__},
#endif
@@ -5218,11 +5478,17 @@ static PyGetSetDef PyCursesScreen_getsets[] = {
{NULL, NULL, NULL, NULL, NULL} /* sentinel */
};
-#ifdef HAVE_CURSES_USE_SCREEN
+#ifdef _Py_HAVE_CURSES_USE_SCREEN
static int
curses_use_screen_cb(SCREEN *Py_UNUSED(sp), void *data)
{
- curses_use_call((curses_use_data *)data);
+ curses_use_data *u = (curses_use_data *)data;
+ PyObject *module = PyType_GetModule(Py_TYPE(u->obj));
+ if (module == NULL || !update_lines_cols(module)) {
+ u->result = NULL;
+ return 0;
+ }
+ curses_use_call(u);
return 0;
}
@@ -5235,8 +5501,8 @@ static PyObject *
PyCursesScreen_use(PyObject *self, PyObject *args, PyObject *kwargs)
{
PyCursesScreenObject *so = _PyCursesScreenObject_CAST(self);
+ cursesmodule_state *state = get_cursesmodule_state_by_cls(Py_TYPE(self));
if (so->screen == NULL) {
- cursesmodule_state *state = get_cursesmodule_state_by_cls(Py_TYPE(self));
PyErr_SetString(state->error, "the screen has been deleted");
return NULL;
}
@@ -5244,12 +5510,30 @@ PyCursesScreen_use(PyObject *self, PyObject *args, PyObject *kwargs)
if (curses_use_parse(args, &func, &extra) < 0) {
return NULL;
}
+ PyObject *module = PyType_GetModule(Py_TYPE(self));
+ if (module == NULL) {
+ Py_DECREF(extra);
+ return NULL;
+ }
curses_use_data data = {self, func, extra, kwargs, NULL};
+ PyObject *prev = state->topscreen;
+ state->topscreen = Py_NewRef(self);
use_screen(so->screen, curses_use_screen_cb, &data);
+ Py_SETREF(state->topscreen, prev);
Py_DECREF(extra);
+ if (data.result == NULL) {
+ PyObject *exc = PyErr_GetRaisedException();
+ (void)update_lines_cols(module);
+ _PyErr_ChainExceptions1(exc);
+ }
+ else {
+ if (!update_lines_cols(module)) {
+ Py_CLEAR(data.result);
+ }
+ }
return data.result;
}
-#endif /* HAVE_CURSES_USE_SCREEN */
+#endif /* _Py_HAVE_CURSES_USE_SCREEN */
PyDoc_STRVAR(PyCursesScreen_close__doc__,
"close($self, /)\n--\n\n"
@@ -5268,14 +5552,21 @@ PyCursesScreen_close(PyObject *self, PyObject *Py_UNUSED(ignored))
static PyMethodDef PyCursesScreen_methods[] = {
{"close", PyCursesScreen_close, METH_NOARGS,
PyCursesScreen_close__doc__},
-#ifdef HAVE_CURSES_USE_SCREEN
+#ifdef _Py_HAVE_CURSES_USE_SCREEN
{"use", _PyCFunction_CAST(PyCursesScreen_use),
METH_VARARGS | METH_KEYWORDS, PyCursesScreen_use__doc__},
#endif
{NULL, NULL} /* sentinel */
};
+PyDoc_STRVAR(PyCursesScreen_Type_doc,
+"A curses screen.\n"
+"\n"
+"Screen objects are returned by newterm() and new_prescr(), and represent\n"
+"a terminal together with its standard window, stdscr.");
+
static PyType_Slot PyCursesScreen_Type_slots[] = {
+ {Py_tp_doc, (void *)PyCursesScreen_Type_doc},
{Py_tp_methods, PyCursesScreen_methods},
{Py_tp_getset, PyCursesScreen_getsets},
{Py_tp_dealloc, PyCursesScreen_dealloc},
@@ -5413,7 +5704,7 @@ _curses_filter_impl(PyObject *module)
}
#endif
-#ifdef HAVE_CURSES_NOFILTER
+#ifdef _Py_HAVE_CURSES_NOFILTER
/*[clinic input]
_curses.nofilter
@@ -5616,7 +5907,7 @@ _curses_color_pair_impl(PyObject *module, int pair_number)
pair_number, (int)PAIR_NUMBER(A_COLOR));
return NULL;
}
- return PyLong_FromLong(attr);
+ return PyLong_FromUnsignedLongLong(attr);
}
/*[clinic input]
@@ -5978,7 +6269,7 @@ _curses_getwin(PyObject *module, PyObject *file)
return res;
}
-#ifdef HAVE_CURSES_SCR_DUMP
+#ifdef _Py_HAVE_CURSES_SCR_DUMP
/*[clinic input]
_curses.scr_dump
@@ -6033,6 +6324,7 @@ _curses_scr_init(PyObject *module, PyObject *filename)
/*[clinic end generated code: output=2e861d381d710419 input=81c45e4702124ef6]*/
ScreenDumpFunctionBody(scr_init)
+#ifdef _Py_HAVE_CURSES_SCR_SET
/*[clinic input]
_curses.scr_set
@@ -6049,7 +6341,8 @@ static PyObject *
_curses_scr_set(PyObject *module, PyObject *filename)
/*[clinic end generated code: output=6056fdec12c5935f input=d248c20543cc289b]*/
ScreenDumpFunctionBody(scr_set)
-#endif /* HAVE_CURSES_SCR_DUMP */
+#endif /* _Py_HAVE_CURSES_SCR_SET */
+#endif /* _Py_HAVE_CURSES_SCR_DUMP */
/*[clinic input]
_curses.halfdelay
@@ -6128,7 +6421,7 @@ _curses_has_key_impl(PyObject *module, int key)
}
#endif
-#ifdef HAVE_CURSES_DEFINE_KEY
+#ifdef _Py_HAVE_CURSES_DEFINE_KEY
/*[clinic input]
_curses.define_key
@@ -6154,9 +6447,9 @@ _curses_define_key_impl(PyObject *module, const char *definition,
return curses_check_err(module, define_key(definition, keycode),
"define_key", NULL);
}
-#endif /* HAVE_CURSES_DEFINE_KEY */
+#endif /* _Py_HAVE_CURSES_DEFINE_KEY */
-#ifdef HAVE_CURSES_KEY_DEFINED
+#ifdef _Py_HAVE_CURSES_KEY_DEFINED
/*[clinic input]
_curses.key_defined
@@ -6178,9 +6471,9 @@ _curses_key_defined_impl(PyObject *module, const char *definition)
return PyLong_FromLong(key_defined(definition));
}
-#endif /* HAVE_CURSES_KEY_DEFINED */
+#endif /* _Py_HAVE_CURSES_KEY_DEFINED */
-#ifdef HAVE_CURSES_KEYOK
+#ifdef _Py_HAVE_CURSES_KEYOK
/*[clinic input]
_curses.keyok
@@ -6201,7 +6494,7 @@ _curses_keyok_impl(PyObject *module, int keycode, int enable)
return curses_check_err(module, keyok(keycode, enable), "keyok", NULL);
}
-#endif /* HAVE_CURSES_KEYOK */
+#endif /* _Py_HAVE_CURSES_KEYOK */
/*[clinic input]
_curses.init_color
@@ -6400,9 +6693,13 @@ curses_init_dict(PyObject *module)
}
/* This was moved from initcurses() because it core dumped on SGI,
where they're not defined until you've called initscr() */
+ /* Use unsigned long long, not long: a chtype constant (the A_* attributes,
+ ACS_* and key codes) can set bits beyond a 32-bit long, which is what
+ long is on LLP64 platforms such as Windows -- A_DIM (0x80000000) would
+ otherwise be sign-extended to a negative number. */
#define SetDictInt(NAME, VALUE) \
do { \
- PyObject *value = PyLong_FromLong((long)(VALUE)); \
+ PyObject *value = PyLong_FromUnsignedLongLong((unsigned long long)(VALUE)); \
if (value == NULL) { \
return -1; \
} \
@@ -6480,6 +6777,179 @@ curses_init_dict(PyObject *module)
SetDictInt("ACS_STERLING", (ACS_STERLING));
#endif
+#ifdef HAVE_NCURSESW
+ /* The same graphic symbols as character cells, for the methods that take
+ a complexchar. Unlike the ACS_* codes, these are not restricted to the
+ 8-bit alternate character set. */
+ cursesmodule_state *state = get_cursesmodule_state(module);
+#define SetDictWACS(NAME, VALUE) \
+ do { \
+ PyObject *value = PyCursesComplexChar_New(state, (VALUE)); \
+ if (value == NULL) { \
+ return -1; \
+ } \
+ int rc = PyDict_SetItemString(module_dict, (NAME), value); \
+ Py_DECREF(value); \
+ if (rc < 0) { \
+ return -1; \
+ } \
+ } while (0)
+
+ SetDictWACS("WACS_ULCORNER", WACS_ULCORNER);
+ SetDictWACS("WACS_LLCORNER", WACS_LLCORNER);
+ SetDictWACS("WACS_URCORNER", WACS_URCORNER);
+ SetDictWACS("WACS_LRCORNER", WACS_LRCORNER);
+ SetDictWACS("WACS_LTEE", WACS_LTEE);
+ SetDictWACS("WACS_RTEE", WACS_RTEE);
+ SetDictWACS("WACS_BTEE", WACS_BTEE);
+ SetDictWACS("WACS_TTEE", WACS_TTEE);
+ SetDictWACS("WACS_HLINE", WACS_HLINE);
+ SetDictWACS("WACS_VLINE", WACS_VLINE);
+ SetDictWACS("WACS_PLUS", WACS_PLUS);
+ SetDictWACS("WACS_S1", WACS_S1);
+ SetDictWACS("WACS_S9", WACS_S9);
+ SetDictWACS("WACS_DIAMOND", WACS_DIAMOND);
+ SetDictWACS("WACS_CKBOARD", WACS_CKBOARD);
+ SetDictWACS("WACS_DEGREE", WACS_DEGREE);
+ SetDictWACS("WACS_PLMINUS", WACS_PLMINUS);
+ SetDictWACS("WACS_BULLET", WACS_BULLET);
+ SetDictWACS("WACS_LARROW", WACS_LARROW);
+ SetDictWACS("WACS_RARROW", WACS_RARROW);
+ SetDictWACS("WACS_DARROW", WACS_DARROW);
+ SetDictWACS("WACS_UARROW", WACS_UARROW);
+ SetDictWACS("WACS_BOARD", WACS_BOARD);
+ SetDictWACS("WACS_LANTERN", WACS_LANTERN);
+ SetDictWACS("WACS_BLOCK", WACS_BLOCK);
+
+ SetDictWACS("WACS_BSSB", WACS_ULCORNER);
+ SetDictWACS("WACS_SSBB", WACS_LLCORNER);
+ SetDictWACS("WACS_BBSS", WACS_URCORNER);
+ SetDictWACS("WACS_SBBS", WACS_LRCORNER);
+ SetDictWACS("WACS_SBSS", WACS_RTEE);
+ SetDictWACS("WACS_SSSB", WACS_LTEE);
+ SetDictWACS("WACS_SSBS", WACS_BTEE);
+ SetDictWACS("WACS_BSSS", WACS_TTEE);
+ SetDictWACS("WACS_BSBS", WACS_HLINE);
+ SetDictWACS("WACS_SBSB", WACS_VLINE);
+ SetDictWACS("WACS_SSSS", WACS_PLUS);
+
+ /* The following are never available with strict SYSV curses */
+#ifdef WACS_S3
+ SetDictWACS("WACS_S3", WACS_S3);
+#endif
+#ifdef WACS_S7
+ SetDictWACS("WACS_S7", WACS_S7);
+#endif
+#ifdef WACS_LEQUAL
+ SetDictWACS("WACS_LEQUAL", WACS_LEQUAL);
+#endif
+#ifdef WACS_GEQUAL
+ SetDictWACS("WACS_GEQUAL", WACS_GEQUAL);
+#endif
+#ifdef WACS_PI
+ SetDictWACS("WACS_PI", WACS_PI);
+#endif
+#ifdef WACS_NEQUAL
+ SetDictWACS("WACS_NEQUAL", WACS_NEQUAL);
+#endif
+#ifdef WACS_STERLING
+ SetDictWACS("WACS_STERLING", WACS_STERLING);
+#endif
+
+ /* Double-line and thick-line symbols have no ACS_* counterpart, and are
+ only provided by some implementations. */
+#ifdef WACS_D_ULCORNER
+ SetDictWACS("WACS_D_ULCORNER", WACS_D_ULCORNER);
+ SetDictWACS("WACS_BDDB", WACS_D_ULCORNER);
+#endif
+#ifdef WACS_D_LLCORNER
+ SetDictWACS("WACS_D_LLCORNER", WACS_D_LLCORNER);
+ SetDictWACS("WACS_DDBB", WACS_D_LLCORNER);
+#endif
+#ifdef WACS_D_URCORNER
+ SetDictWACS("WACS_D_URCORNER", WACS_D_URCORNER);
+ SetDictWACS("WACS_BBDD", WACS_D_URCORNER);
+#endif
+#ifdef WACS_D_LRCORNER
+ SetDictWACS("WACS_D_LRCORNER", WACS_D_LRCORNER);
+ SetDictWACS("WACS_DBBD", WACS_D_LRCORNER);
+#endif
+#ifdef WACS_D_LTEE
+ SetDictWACS("WACS_D_LTEE", WACS_D_LTEE);
+ SetDictWACS("WACS_DDDB", WACS_D_LTEE);
+#endif
+#ifdef WACS_D_RTEE
+ SetDictWACS("WACS_D_RTEE", WACS_D_RTEE);
+ SetDictWACS("WACS_DBDD", WACS_D_RTEE);
+#endif
+#ifdef WACS_D_BTEE
+ SetDictWACS("WACS_D_BTEE", WACS_D_BTEE);
+ SetDictWACS("WACS_DDBD", WACS_D_BTEE);
+#endif
+#ifdef WACS_D_TTEE
+ SetDictWACS("WACS_D_TTEE", WACS_D_TTEE);
+ SetDictWACS("WACS_BDDD", WACS_D_TTEE);
+#endif
+#ifdef WACS_D_HLINE
+ SetDictWACS("WACS_D_HLINE", WACS_D_HLINE);
+ SetDictWACS("WACS_BDBD", WACS_D_HLINE);
+#endif
+#ifdef WACS_D_VLINE
+ SetDictWACS("WACS_D_VLINE", WACS_D_VLINE);
+ SetDictWACS("WACS_DBDB", WACS_D_VLINE);
+#endif
+#ifdef WACS_D_PLUS
+ SetDictWACS("WACS_D_PLUS", WACS_D_PLUS);
+ SetDictWACS("WACS_DDDD", WACS_D_PLUS);
+#endif
+
+#ifdef WACS_T_ULCORNER
+ SetDictWACS("WACS_T_ULCORNER", WACS_T_ULCORNER);
+ SetDictWACS("WACS_BTTB", WACS_T_ULCORNER);
+#endif
+#ifdef WACS_T_LLCORNER
+ SetDictWACS("WACS_T_LLCORNER", WACS_T_LLCORNER);
+ SetDictWACS("WACS_TTBB", WACS_T_LLCORNER);
+#endif
+#ifdef WACS_T_URCORNER
+ SetDictWACS("WACS_T_URCORNER", WACS_T_URCORNER);
+ SetDictWACS("WACS_BBTT", WACS_T_URCORNER);
+#endif
+#ifdef WACS_T_LRCORNER
+ SetDictWACS("WACS_T_LRCORNER", WACS_T_LRCORNER);
+ SetDictWACS("WACS_TBBT", WACS_T_LRCORNER);
+#endif
+#ifdef WACS_T_LTEE
+ SetDictWACS("WACS_T_LTEE", WACS_T_LTEE);
+ SetDictWACS("WACS_TTTB", WACS_T_LTEE);
+#endif
+#ifdef WACS_T_RTEE
+ SetDictWACS("WACS_T_RTEE", WACS_T_RTEE);
+ SetDictWACS("WACS_TBTT", WACS_T_RTEE);
+#endif
+#ifdef WACS_T_BTEE
+ SetDictWACS("WACS_T_BTEE", WACS_T_BTEE);
+ SetDictWACS("WACS_TTBT", WACS_T_BTEE);
+#endif
+#ifdef WACS_T_TTEE
+ SetDictWACS("WACS_T_TTEE", WACS_T_TTEE);
+ SetDictWACS("WACS_BTTT", WACS_T_TTEE);
+#endif
+#ifdef WACS_T_HLINE
+ SetDictWACS("WACS_T_HLINE", WACS_T_HLINE);
+ SetDictWACS("WACS_BTBT", WACS_T_HLINE);
+#endif
+#ifdef WACS_T_VLINE
+ SetDictWACS("WACS_T_VLINE", WACS_T_VLINE);
+ SetDictWACS("WACS_TBTB", WACS_T_VLINE);
+#endif
+#ifdef WACS_T_PLUS
+ SetDictWACS("WACS_T_PLUS", WACS_T_PLUS);
+ SetDictWACS("WACS_TTTT", WACS_T_PLUS);
+#endif
+#undef SetDictWACS
+#endif /* HAVE_NCURSESW */
+
SetDictInt("LINES", LINES);
SetDictInt("COLS", COLS);
#undef SetDictInt
@@ -6491,12 +6961,12 @@ _curses.initscr
Initialize the library.
-Return a WindowObject which represents the whole screen.
+Return a window object which represents the whole screen.
[clinic start generated code]*/
static PyObject *
_curses_initscr_impl(PyObject *module)
-/*[clinic end generated code: output=619fb68443810b7b input=514f4bce1821f6b5]*/
+/*[clinic end generated code: output=619fb68443810b7b input=e2bf3a061b7d948a]*/
{
WINDOW *win;
@@ -6507,7 +6977,23 @@ _curses_initscr_impl(PyObject *module)
_curses_set_null_error(state, "wrefresh", "initscr");
return NULL;
}
- PyObject *winobj = PyCursesWindow_New(state, stdscr, NULL, NULL, NULL);
+ if (state->topscreen != NULL) {
+ /* The current screen is one made by newterm(); return its own
+ standard window instead of a second wrapper over the same
+ WINDOW, which would delwin() it on its own. */
+ PyCursesScreenObject *so = (PyCursesScreenObject *)state->topscreen;
+ if (so->stdscr_win != NULL) {
+ if (curses_update_screen_encoding(so->stdscr_win) < 0) {
+ return NULL;
+ }
+ return Py_NewRef(so->stdscr_win);
+ }
+ }
+ /* Attach the current screen, like newwin(), newpad() and getwin() do,
+ so that the window keeps its screen alive. It is NULL for the
+ screen created by initscr(), which has no screen object. */
+ PyObject *winobj = PyCursesWindow_New(state, stdscr, NULL, NULL,
+ state->topscreen);
if (winobj == NULL) {
return NULL;
}
@@ -6525,13 +7011,21 @@ _curses_initscr_impl(PyObject *module)
return NULL;
}
+ cursesmodule_state *state = get_cursesmodule_state(module);
+ if (state->prescreen != NULL) {
+ PyCursesScreenObject *prescreen =
+ _PyCursesScreenObject_CAST(state->prescreen);
+ assert(prescreen->screen != NULL);
+ prescreen->screen = NULL;
+ Py_CLEAR(state->prescreen);
+ }
+
curses_initscr_called = curses_setupterm_called = TRUE;
if (curses_init_dict(module) < 0) {
return NULL;
}
- cursesmodule_state *state = get_cursesmodule_state(module);
PyObject *winobj = PyCursesWindow_New(state, win, NULL, NULL, NULL);
if (winobj == NULL) {
return NULL;
@@ -6602,8 +7096,6 @@ _curses_setupterm_impl(PyObject *module, const char *term, int fd)
Py_RETURN_NONE;
}
-static int update_lines_cols(PyObject *private_module); /* defined below */
-
/* Return a file descriptor for obj, or, if obj is NULL or None, for the
sys. stream. Returns -1 with an exception set on error. */
static int
@@ -6707,6 +7199,13 @@ _curses_newterm_impl(PyObject *module, const char *type, PyObject *fd,
cursesmodule_state *state = get_cursesmodule_state(module);
/* The screen object owns the SCREEN and the streams; deleting it (when it
is no longer referenced) calls delscreen() and closes the streams. */
+ if (state->prescreen != NULL) {
+ PyCursesScreenObject *prescreen =
+ _PyCursesScreenObject_CAST(state->prescreen);
+ assert(prescreen->screen == screen);
+ prescreen->screen = NULL;
+ Py_CLEAR(state->prescreen);
+ }
PyObject *screenobj = PyCursesScreen_New(state, screen, outfp, infp, NULL);
if (screenobj == NULL) {
delscreen(screen);
@@ -6768,17 +7267,23 @@ _curses_set_term(PyObject *module, PyObject *screen)
if (so == NULL) {
return NULL;
}
+ cursesmodule_state *state = get_cursesmodule_state(module);
+ if (so->stdscr_win == NULL) {
+ /* A screen from new_prescr() has no terminal, so it cannot become the
+ current one: a later refresh would dereference NULL in curses. */
+ PyErr_SetString(state->error, "the screen has no terminal");
+ return NULL;
+ }
set_term(so->screen);
if (!update_lines_cols(module)) {
return NULL;
}
- cursesmodule_state *state = get_cursesmodule_state(module);
PyObject *prev = state->topscreen; /* steal the owned reference */
state->topscreen = Py_NewRef(screen);
return prev != NULL ? prev : Py_NewRef(Py_None);
}
-#ifdef HAVE_CURSES_NEW_PRESCR
+#ifdef _Py_HAVE_CURSES_NEW_PRESCR
/*[clinic input]
_curses.new_prescr
@@ -6792,15 +7297,27 @@ static PyObject *
_curses_new_prescr_impl(PyObject *module)
/*[clinic end generated code: output=e7de5031da7511e2 input=1a3a89d630b641c3]*/
{
+ cursesmodule_state *state = get_cursesmodule_state(module);
+ if (state->prescreen != NULL) {
+ return Py_NewRef(state->prescreen);
+ }
+
SCREEN *screen = new_prescr();
if (screen == NULL) {
curses_set_null_error(module, "new_prescr", NULL);
return NULL;
}
- cursesmodule_state *state = get_cursesmodule_state(module);
- return PyCursesScreen_New(state, screen, NULL, NULL, NULL);
+
+ PyObject *screenobj = PyCursesScreen_New(state, screen, NULL, NULL, NULL);
+ if (screenobj == NULL) {
+ delscreen(screen);
+ return NULL;
+ }
+
+ state->prescreen = Py_NewRef(screenobj);
+ return screenobj;
}
-#endif /* HAVE_CURSES_NEW_PRESCR */
+#endif /* _Py_HAVE_CURSES_NEW_PRESCR */
#ifdef HAVE_CURSES_ESCDELAY
/*[clinic input]
@@ -7056,7 +7573,7 @@ _curses_meta_impl(PyObject *module, int yes)
}
#if defined(HAVE_CURSES_GETMOUSE) || defined(PDCURSES)
-#if defined(HAVE_CURSES_HAS_MOUSE) || defined(PDCURSES)
+#if defined(_Py_HAVE_CURSES_HAS_MOUSE) || defined(PDCURSES)
/*[clinic input]
_curses.has_mouse
@@ -7071,7 +7588,7 @@ _curses_has_mouse_impl(PyObject *module)
return PyBool_FromLong(has_mouse());
}
-#endif /* HAVE_CURSES_HAS_MOUSE || PDCURSES */
+#endif /* _Py_HAVE_CURSES_HAS_MOUSE || PDCURSES */
/*[clinic input]
_curses.mouseinterval
@@ -7347,7 +7864,7 @@ _curses_pair_content_impl(PyObject *module, int pair_number)
@permit_long_summary
_curses.pair_number
- attr: int
+ attr: attr
/
Return the number of the color-pair set by the specified attribute value.
@@ -7356,8 +7873,8 @@ color_pair() is the counterpart to this function.
[clinic start generated code]*/
static PyObject *
-_curses_pair_number_impl(PyObject *module, int attr)
-/*[clinic end generated code: output=85bce7d65c0aa3f4 input=b11152a78c2f9abf]*/
+_curses_pair_number_impl(PyObject *module, attr_t attr)
+/*[clinic end generated code: output=04cafc9083329197 input=562273b1a12a06d2]*/
{
PyCursesStatefulInitialised(module);
PyCursesStatefulInitialisedColor(module);
@@ -7412,9 +7929,10 @@ _curses_qiflush_impl(PyObject *module, int flag)
Py_RETURN_NONE;
}
-#if defined(HAVE_CURSES_RESIZETERM) || defined(HAVE_CURSES_RESIZE_TERM)
/* Internal helper used for updating curses.LINES, curses.COLS, _curses.LINES
- * and _curses.COLS. Returns 1 on success and 0 on failure. */
+ * and _curses.COLS. Returns 1 on success and 0 on failure. Used
+ * unconditionally (e.g. by set_term()), so it must not be gated on resizeterm().
+ */
static int
update_lines_cols(PyObject *private_module)
{
@@ -7433,7 +7951,11 @@ update_lines_cols(PyObject *private_module)
goto error;
}
- o = PyLong_FromLong(LINES);
+ int lines = LINES;
+ if (stdscr != NULL) {
+ lines = getmaxy(stdscr);
+ }
+ o = PyLong_FromLong(lines);
if (o == NULL) {
goto error;
}
@@ -7445,7 +7967,11 @@ update_lines_cols(PyObject *private_module)
}
Py_DECREF(o);
- o = PyLong_FromLong(COLS);
+ int cols = COLS;
+ if (stdscr != NULL) {
+ cols = getmaxx(stdscr);
+ }
+ o = PyLong_FromLong(cols);
if (o == NULL) {
goto error;
}
@@ -7456,6 +7982,32 @@ update_lines_cols(PyObject *private_module)
goto error;
}
Py_DECREF(o);
+
+ if (curses_start_color_called) {
+ o = PyLong_FromUnsignedLongLong((unsigned long long)COLORS);
+ if (o == NULL) {
+ goto error;
+ }
+ if (PyDict_SetItemString(exposed_module_dict, "COLORS", o) < 0) {
+ goto error;
+ }
+ if (PyDict_SetItemString(private_module_dict, "COLORS", o) < 0) {
+ goto error;
+ }
+ Py_DECREF(o);
+
+ o = PyLong_FromUnsignedLongLong((unsigned long long)COLOR_PAIRS);
+ if (o == NULL) {
+ goto error;
+ }
+ if (PyDict_SetItemString(exposed_module_dict, "COLOR_PAIRS", o) < 0) {
+ goto error;
+ }
+ if (PyDict_SetItemString(private_module_dict, "COLOR_PAIRS", o) < 0) {
+ goto error;
+ }
+ Py_DECREF(o);
+ }
Py_DECREF(exposed_module);
return 1;
@@ -7483,8 +8035,6 @@ _curses_update_lines_cols_impl(PyObject *module)
Py_RETURN_NONE;
}
-#endif
-
/*[clinic input]
_curses.raw
@@ -7689,7 +8239,7 @@ _curses_start_color_impl(PyObject *module)
}
#define DICT_ADD_INT_VALUE(NAME, VALUE) \
do { \
- PyObject *value = PyLong_FromLong((long)(VALUE)); \
+ PyObject *value = PyLong_FromUnsignedLongLong((unsigned long long)(VALUE)); \
if (value == NULL) { \
return NULL; \
} \
@@ -7716,9 +8266,13 @@ Return a logical OR of all video attributes supported by the terminal.
static PyObject *
_curses_termattrs_impl(PyObject *module)
/*[clinic end generated code: output=b06f437fce1b6fc4 input=0559882a04f84d1d]*/
-NoArgReturnIntFunctionBody(termattrs)
+{
+ PyCursesStatefulInitialised(module);
-#ifdef HAVE_CURSES_TERM_ATTRS
+ return PyLong_FromUnsignedLong((unsigned long)(chtype)termattrs());
+}
+
+#ifdef _Py_HAVE_CURSES_TERM_ATTRS
/*[clinic input]
_curses.term_attrs
@@ -7734,9 +8288,9 @@ _curses_term_attrs_impl(PyObject *module)
{
PyCursesStatefulInitialised(module);
- return PyLong_FromUnsignedLong(term_attrs());
+ return PyLong_FromUnsignedLongLong(term_attrs());
}
-#endif /* HAVE_CURSES_TERM_ATTRS */
+#endif /* _Py_HAVE_CURSES_TERM_ATTRS */
/*[clinic input]
@permit_long_summary
@@ -7820,35 +8374,155 @@ _curses_tigetstr_impl(PyObject *module, const char *capname)
return PyBytes_FromString( capname );
}
+#ifndef NCURSES_TPARM_ARG
+# define NCURSES_TPARM_ARG long
+#endif
+
+/* Return a bit mask of the parameters of a terminfo string that curses takes
+ as strings: those that %s or %l follows directly after %p, as in ncurses'
+ _nc_tparm_analyze(). The others are numbers. */
+static unsigned int
+curses_tparm_string_params(const char *str)
+{
+ unsigned int mask = 0;
+ int last = 0; /* the parameter pushed last, or 0 */
+
+ while (*str) {
+ if (*str++ != '%') {
+ continue;
+ }
+ /* Skip the flags, width and precision of a conversion. */
+ int allowminus = 0;
+ while (*str) {
+ if (*str == ':') {
+ allowminus = 1;
+ }
+ else if (!(*str == '#' || *str == ' ' || *str == '.'
+ || Py_ISDIGIT(*str) || (*str == '-' && allowminus)))
+ {
+ break;
+ }
+ str++;
+ }
+ switch (*str) {
+ case 'p':
+ if (str[1] >= '1' && str[1] <= '9') {
+ last = str[1] - '0';
+ }
+ str++;
+ break;
+ case 's':
+ case 'l':
+ if (last > 0) {
+ mask |= 1u << (last - 1);
+ }
+ break;
+ case 'd': case 'o': case 'x': case 'X': case 'c':
+ case '+': case '-': case '*': case '/': case 'm':
+ case '&': case '|': case '^': case '=': case '<': case '>':
+ case 'A': case 'O': case '!': case '~':
+ last = 0;
+ break;
+ case '\'':
+ str += 2;
+ last = 0;
+ break;
+ case '\0':
+ return mask;
+ default:
+ /* %P, %g, %{, %i, %?, %t, %e, %; and %% keep it. */
+ break;
+ }
+ str++;
+ }
+ return mask;
+}
+
+/* Convert a tparm() parameter: a string for those that the terminfo string
+ takes as strings (passing a number there would crash curses), otherwise a
+ number. An omitted one is 0, or NULL, which curses takes as "". */
+static int
+curses_tparm_param(PyObject *arg, int argnum, int is_string,
+ NCURSES_TPARM_ARG *result)
+{
+ if (arg == NULL) {
+ *result = 0;
+ return 0;
+ }
+ if (is_string) {
+ if (!PyBytes_Check(arg)) {
+ PyErr_Format(PyExc_TypeError,
+ "tparm() argument %d must be bytes, not %T",
+ argnum, arg);
+ return -1;
+ }
+ const char *value = PyBytes_AS_STRING(arg);
+ if (strlen(value) != (size_t)PyBytes_GET_SIZE(arg)) {
+ PyErr_SetString(PyExc_ValueError, "embedded null byte");
+ return -1;
+ }
+ *result = (NCURSES_TPARM_ARG)(intptr_t)value;
+ return 0;
+ }
+ if (PyBytes_Check(arg)) {
+ PyErr_Format(PyExc_TypeError,
+ "tparm() argument %d must be int, not bytes", argnum);
+ return -1;
+ }
+ int value = PyLong_AsInt(arg);
+ if (value == -1 && PyErr_Occurred()) {
+ return -1;
+ }
+ *result = value;
+ return 0;
+}
+
/*[clinic input]
_curses.tparm
- str: str(accept={robuffer})
+ str as string: object
Parameterized byte string obtained from the terminfo database.
- i1: int = 0
- i2: int = 0
- i3: int = 0
- i4: int = 0
- i5: int = 0
- i6: int = 0
- i7: int = 0
- i8: int = 0
- i9: int = 0
/
+ *params: tuple
+ Up to nine parameters.
Instantiate the specified byte string with the supplied parameters.
+
+The parameters are integers, except in a few cases where they must be
+bytes objects.
[clinic start generated code]*/
static PyObject *
-_curses_tparm_impl(PyObject *module, const char *str, int i1, int i2, int i3,
- int i4, int i5, int i6, int i7, int i8, int i9)
-/*[clinic end generated code: output=599f62b615c667ff input=5e30b15786f032aa]*/
+_curses_tparm_impl(PyObject *module, PyObject *string, PyObject *params)
+/*[clinic end generated code: output=3439bb1b37a13d5b input=4889c0e3a5eab5b5]*/
{
char* result = NULL;
+ NCURSES_TPARM_ARG values[9];
+ Py_ssize_t count = PyTuple_GET_SIZE(params);
+ const char *str;
+
+ if (!PyArg_Parse(string, "y:tparm", &str)) {
+ return NULL;
+ }
+ if (count > 9) {
+ PyErr_Format(PyExc_TypeError,
+ "tparm() takes at most 9 parameters (%zd given)", count);
+ return NULL;
+ }
PyCursesStatefulSetupTermCalled(module);
- result = tparm((char *)str,i1,i2,i3,i4,i5,i6,i7,i8,i9);
+ unsigned int strings = curses_tparm_string_params(str);
+ for (int i = 0; i < 9; i++) {
+ PyObject *arg = i < count ? PyTuple_GET_ITEM(params, i) : NULL;
+ if (curses_tparm_param(arg, i + 2, strings & (1u << i),
+ &values[i]) < 0)
+ {
+ return NULL;
+ }
+ }
+ result = tparm((char *)str, values[0], values[1], values[2], values[3],
+ values[4], values[5], values[6], values[7], values[8]);
if (!result) {
curses_set_null_error(module, "tparm", NULL);
return NULL;
@@ -7886,15 +8560,17 @@ _curses.unctrl
ch: object
/
-Return a string which is a printable representation of the character ch.
+Return a bytes object which is a printable representation of ch.
-Control characters are displayed as a caret followed by the character,
-for example as ^C. Printing characters are left as they are.
+Control characters are displayed as a caret followed by the
+character, for example as ^C. Printing characters are left as they
+are. Any attributes and color pair are ignored. ch must fit in a
+single byte; use wunctrl() for other characters.
[clinic start generated code]*/
static PyObject *
_curses_unctrl(PyObject *module, PyObject *ch)
-/*[clinic end generated code: output=8e07fafc430c9434 input=cd1e35e16cd1ace4]*/
+/*[clinic end generated code: output=8e07fafc430c9434 input=eed6686669f5ca21]*/
{
chtype ch_;
@@ -8254,15 +8930,15 @@ NoArgNoReturnFunctionBody(slk_touch)
/*[clinic input]
_curses.slk_attron
- attr: long
+ attr: attr
/
Add the given chtype attributes to the soft labels.
[clinic start generated code]*/
static PyObject *
-_curses_slk_attron_impl(PyObject *module, long attr)
-/*[clinic end generated code: output=01aa29848a58ab50 input=fa198a604e3eec04]*/
+_curses_slk_attron_impl(PyObject *module, attr_t attr)
+/*[clinic end generated code: output=c2a4bfac8ddbbf20 input=c2cfffeb7ce6a86e]*/
{
PyCursesStatefulInitialised(module);
return curses_check_err(module, slk_attron((chtype)attr),
@@ -8272,15 +8948,15 @@ _curses_slk_attron_impl(PyObject *module, long attr)
/*[clinic input]
_curses.slk_attroff
- attr: long
+ attr: attr
/
Remove the given chtype attributes from the soft labels.
[clinic start generated code]*/
static PyObject *
-_curses_slk_attroff_impl(PyObject *module, long attr)
-/*[clinic end generated code: output=7b172cc37a17811f input=21dab55d43d30b8f]*/
+_curses_slk_attroff_impl(PyObject *module, attr_t attr)
+/*[clinic end generated code: output=321a3b4dc61119bb input=2593027e03cbd302]*/
{
PyCursesStatefulInitialised(module);
return curses_check_err(module, slk_attroff((chtype)attr),
@@ -8290,15 +8966,15 @@ _curses_slk_attroff_impl(PyObject *module, long attr)
/*[clinic input]
_curses.slk_attrset
- attr: long
+ attr: attr
/
Set the chtype attributes of the soft labels.
[clinic start generated code]*/
static PyObject *
-_curses_slk_attrset_impl(PyObject *module, long attr)
-/*[clinic end generated code: output=1139e2b0f757edfd input=d5c798956a5f046a]*/
+_curses_slk_attrset_impl(PyObject *module, attr_t attr)
+/*[clinic end generated code: output=f396b745cb23fc01 input=5faafda445b2b158]*/
{
PyCursesStatefulInitialised(module);
return curses_check_err(module, slk_attrset((chtype)attr),
@@ -8317,10 +8993,11 @@ _curses_slk_attr_impl(PyObject *module)
/*[clinic end generated code: output=6d47752f82bdc29f input=be38805fdec52149]*/
{
PyCursesStatefulInitialised(module);
- return PyLong_FromUnsignedLong((unsigned long)slk_attr());
+ return PyLong_FromUnsignedLongLong((unsigned long long)slk_attr());
}
#endif
+#ifdef _Py_HAVE_CURSES_SLK_ATTR_ON
/*[clinic input]
_curses.slk_attr_on
@@ -8338,7 +9015,9 @@ _curses_slk_attr_on_impl(PyObject *module, attr_t attr)
return curses_check_err(module, slk_attr_on(attr, NULL),
"slk_attr_on", NULL);
}
+#endif /* _Py_HAVE_CURSES_SLK_ATTR_ON */
+#ifdef _Py_HAVE_CURSES_SLK_ATTR_OFF
/*[clinic input]
_curses.slk_attr_off
@@ -8356,7 +9035,9 @@ _curses_slk_attr_off_impl(PyObject *module, attr_t attr)
return curses_check_err(module, slk_attr_off(attr, NULL),
"slk_attr_off", NULL);
}
+#endif /* _Py_HAVE_CURSES_SLK_ATTR_OFF */
+#ifdef _Py_HAVE_CURSES_SLK_ATTR_SET
/*[clinic input]
_curses.slk_attr_set
@@ -8380,7 +9061,9 @@ _curses_slk_attr_set_impl(PyObject *module, attr_t attr, int pair)
#endif
return curses_check_err(module, rtn, "slk_attr_set", NULL);
}
+#endif /* _Py_HAVE_CURSES_SLK_ATTR_SET */
+#ifdef _Py_HAVE_CURSES_SLK_COLOR
/*[clinic input]
_curses.slk_color
@@ -8395,8 +9078,15 @@ _curses_slk_color_impl(PyObject *module, int pair)
/*[clinic end generated code: output=ffe4de805f9c65f5 input=b1e691a9cc6177ee]*/
{
PyCursesStatefulInitialised(module);
- return curses_check_err(module, slk_color((short)pair), "slk_color", NULL);
+ int rtn;
+#if _NCURSES_EXTENDED_COLOR_FUNCS
+ rtn = extended_slk_color(pair);
+#else
+ rtn = slk_color((short)pair);
+#endif
+ return curses_check_err(module, rtn, "slk_color", NULL);
}
+#endif /* _Py_HAVE_CURSES_SLK_COLOR */
#ifdef HAVE_CURSES_USE_ENV
/*[clinic input]
@@ -8608,7 +9298,7 @@ static PyMethodDef cursesmodule_methods[] = {
_CURSES_NEWPAD_METHODDEF
_CURSES_NEWTERM_METHODDEF
_CURSES_NEWWIN_METHODDEF
-#ifdef HAVE_CURSES_NEW_PRESCR
+#ifdef _Py_HAVE_CURSES_NEW_PRESCR
_CURSES_NEW_PRESCR_METHODDEF
#endif
_CURSES_NL_METHODDEF
@@ -8783,6 +9473,7 @@ cursesmodule_traverse(PyObject *mod, visitproc visit, void *arg)
Py_VISIT(state->complexchar_type);
Py_VISIT(state->complexstr_type);
Py_VISIT(state->topscreen);
+ Py_VISIT(state->prescreen);
return 0;
}
@@ -8796,6 +9487,7 @@ cursesmodule_clear(PyObject *mod)
Py_CLEAR(state->complexchar_type);
Py_CLEAR(state->complexstr_type);
Py_CLEAR(state->topscreen);
+ Py_CLEAR(state->prescreen);
return 0;
}
@@ -8889,6 +9581,17 @@ cursesmodule_exec(PyObject *module)
return -1;
}
+ /* Whether a cell holds a character or a single byte of the locale
+ encoding, decided when the module is built. */
+#ifdef HAVE_NCURSESW
+ rc = PyDict_SetItemString(module_dict, "_wide_character_support", Py_True);
+#else
+ rc = PyDict_SetItemString(module_dict, "_wide_character_support", Py_False);
+#endif
+ if (rc < 0) {
+ return -1;
+ }
+
/* Make the version available */
PyObject *curses_version = PyBytes_FromString(PyCursesVersion);
if (curses_version == NULL) {
@@ -8927,7 +9630,22 @@ cursesmodule_exec(PyObject *module)
#define SetDictInt(NAME, VALUE) \
do { \
- PyObject *value = PyLong_FromLong((long)(VALUE)); \
+ PyObject *value = PyLong_FromUnsignedLongLong((unsigned long long)(VALUE)); \
+ if (value == NULL) { \
+ return -1; \
+ } \
+ int rc = PyDict_SetItemString(module_dict, (NAME), value); \
+ Py_DECREF(value); \
+ if (rc < 0) { \
+ return -1; \
+ } \
+ } while (0)
+
+ /* ERR is -1, so it needs a signed conversion, unlike the chtype
+ constants below. */
+#define SetDictSignedInt(NAME, VALUE) \
+ do { \
+ PyObject *value = PyLong_FromLongLong((long long)(VALUE)); \
if (value == NULL) { \
return -1; \
} \
@@ -8938,8 +9656,9 @@ cursesmodule_exec(PyObject *module)
} \
} while (0)
- SetDictInt("ERR", ERR);
- SetDictInt("OK", OK);
+ SetDictSignedInt("ERR", ERR);
+ SetDictSignedInt("OK", OK);
+#undef SetDictSignedInt
/* Here are some attributes you can add to chars to print */
diff --git a/Modules/_datetimemodule.c b/Modules/_datetimemodule.c
index cd02b298b406e6a..a06b867049097ee 100644
--- a/Modules/_datetimemodule.c
+++ b/Modules/_datetimemodule.c
@@ -52,6 +52,9 @@ typedef struct {
/* The interned Unix epoch datetime instance */
PyObject *epoch;
+
+ PyObject *time_struct_time;
+ PyObject *time_strftime;
} datetime_state;
/* The module has a fixed number of static objects, due to being exposed
@@ -460,124 +463,57 @@ days_before_month(int year, int month)
return days;
}
-/* year -> number of days before January 1st of year. Remember that we
- * start with year 1, so days_before_year(1) == 0.
- */
-static int
-days_before_year(int year)
-{
- int y = year - 1;
- /* This is incorrect if year <= 0; we really want the floor
- * here. But so long as MINYEAR is 1, the smallest year this
- * can see is 1.
- */
- assert (year >= 1);
- return y*365 + y/4 - y/100 + y/400;
-}
/* Number of days in 4, 100, and 400 year cycles. That these have
* the correct values is asserted in the module init function.
*/
-#define DI4Y 1461 /* days_before_year(5); days in 4 years */
-#define DI100Y 36524 /* days_before_year(101); days in 100 years */
-#define DI400Y 146097 /* days_before_year(401); days in 400 years */
+#define DI4Y 1461 /* _PyTime_DaysBeforeYear(5); days in 4 years */
+#define DI100Y 36524 /* _PyTime_DaysBeforeYear(101); days in 100 years */
+#define DI400Y 146097 /* _PyTime_DaysBeforeYear(401); days in 400 years */
-/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
+/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1.
+ *
+ * Neri and Schneider's algorithm, https://doi.org/10.1002/spe.3172; see
+ * _ord2ymd() in Lib/_pydatetime.py for an explanation of the steps.
+ *
+ * The intermediate values only fit in 32 bits for small ordinals;
+ * iso_to_ymd() passes the largest, MAXORDINAL + 2 (10000-01-02).
+ */
static void
ord_to_ymd(int ordinal, int *year, int *month, int *day)
{
- int n, n1, n4, n100, n400, leapyear, preceding;
-
- /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
- * leap years repeats exactly every 400 years. The basic strategy is
- * to find the closest 400-year boundary at or before ordinal, then
- * work with the offset from that boundary to ordinal. Life is much
- * clearer if we subtract 1 from ordinal first -- then the values
- * of ordinal at 400-year boundaries are exactly those divisible
- * by DI400Y:
- *
- * D M Y n n-1
- * -- --- ---- ---------- ----------------
- * 31 Dec -400 -DI400Y -DI400Y -1
- * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
- * ...
- * 30 Dec 000 -1 -2
- * 31 Dec 000 0 -1
- * 1 Jan 001 1 0 400-year boundary
- * 2 Jan 001 2 1
- * 3 Jan 001 3 2
- * ...
- * 31 Dec 400 DI400Y DI400Y -1
- * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
- */
- assert(ordinal >= 1);
- --ordinal;
- n400 = ordinal / DI400Y;
- n = ordinal % DI400Y;
- *year = n400 * 400 + 1;
-
- /* Now n is the (non-negative) offset, in days, from January 1 of
- * year, to the desired date. Now compute how many 100-year cycles
- * precede n.
- * Note that it's possible for n100 to equal 4! In that case 4 full
- * 100-year cycles precede the desired day, which implies the
- * desired day is December 31 at the end of a 400-year cycle.
- */
- n100 = n / DI100Y;
- n = n % DI100Y;
-
- /* Now compute how many 4-year cycles precede it. */
- n4 = n / DI4Y;
- n = n % DI4Y;
-
- /* And now how many single years. Again n1 can be 4, and again
- * meaning that the desired day is December 31 at the end of the
- * 4-year cycle.
- */
- n1 = n / 365;
- n = n % 365;
-
- *year += n100 * 100 + n4 * 4 + n1;
- if (n1 == 4 || n100 == 4) {
- assert(n == 0);
- *year -= 1;
- *month = 12;
- *day = 31;
- return;
+ assert(1 <= ordinal && ordinal <= MAXORDINAL + 2);
+ const uint32_t days = (uint32_t)ordinal + 305;
+ const uint32_t century = (4 * days + 3) / DI400Y;
+ const uint32_t day_of_century = (4 * days + 3) % DI400Y / 4;
+ const uint32_t year_of_century = (4 * day_of_century + 3) / DI4Y;
+ const uint32_t day_of_year = (4 * day_of_century + 3) % DI4Y / 4;
+ const uint32_t m = (5 * day_of_year + 461) / 153;
+ const uint32_t d = (5 * day_of_year + 461) % 153 / 5 + 1;
+ const uint32_t y = 100 * century + year_of_century;
+ if (m > 12) { /* January or February */
+ *year = (int)(y + 1);
+ *month = (int)(m - 12);
}
-
- /* Now the year is correct, and n is the offset from January 1. We
- * find the month via an estimate that's either exact or one too
- * large.
- */
- leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
- assert(leapyear == is_leap(*year));
- *month = (n + 50) >> 5;
- preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
- if (preceding > n) {
- /* estimate is too large */
- *month -= 1;
- preceding -= days_in_month(*year, *month);
+ else {
+ *year = (int)y;
+ *month = (int)m;
}
- n -= preceding;
- assert(0 <= n);
- assert(n < days_in_month(*year, *month));
-
- *day = n + 1;
+ *day = (int)d;
}
/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
static int
ymd_to_ord(int year, int month, int day)
{
- return days_before_year(year) + days_before_month(year, month) + day;
+ return _PyTime_DaysBeforeYear(year) + days_before_month(year, month) + day;
}
/* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
static int
weekday(int year, int month, int day)
{
- return (ymd_to_ord(year, month, day) + 6) % 7;
+ return _PyTime_Weekday(year, days_before_month(year, month) + day);
}
/* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
@@ -679,6 +615,18 @@ check_date_args(int year, int month, int day)
return 0;
}
+static int
+year_from_tm(const struct tm *tm, int *year)
+{
+ if (tm->tm_year > INT_MAX - 1900) {
+ PyErr_Format(PyExc_ValueError, "year must be in %d..%d, not %lld",
+ MINYEAR, MAXYEAR, (long long)tm->tm_year + 1900);
+ return -1;
+ }
+ *year = tm->tm_year + 1900;
+ return 0;
+}
+
/* Check that time arguments are in range. Return 0 if they are. If they
* aren't, raise ValueError and return -1.
*/
@@ -988,6 +936,10 @@ parse_isoformat_date(const char *dtstr, const size_t len, int *year, int *month,
iso_day = 1;
}
+ if ((size_t)(p - dtstr) != len) {
+ return -1;
+ }
+
int rv = iso_to_ymd(*year, iso_week, iso_day, year, month, day);
if (rv) {
return -3 + rv;
@@ -1008,6 +960,9 @@ parse_isoformat_date(const char *dtstr, const size_t len, int *year, int *month,
if (p == NULL) {
return -1;
}
+ if ((size_t)(p - dtstr) != len) {
+ return -1;
+ }
return 0;
}
@@ -1043,8 +998,11 @@ parse_hh_mm_ss_ff(const char *tstr, const char *tstr_end, int *hour,
}
break;
}
- else if (p >= p_end) {
- return c != '\0';
+ else if (p > p_end) {
+ return 0; // Stopped at p_end: an offset designator or NUL
+ }
+ else if (p == p_end) {
+ return 1; // Stray character just before p_end
}
else if (has_separator && (c == ':')) {
if (i == 2) {
@@ -1084,8 +1042,8 @@ parse_hh_mm_ss_ff(const char *tstr, const char *tstr_end, int *hour,
++p; // skip truncated digits
}
- // Return 1 if it's not the end of the string
- return *p != '\0';
+ // Return 1 if there is unparsed text before p_end
+ return p != p_end;
}
static int
@@ -1119,15 +1077,11 @@ parse_isoformat_time(const char *dtstr, size_t dtlen, int *hour, int *minute,
if (rv < 0) {
return rv;
}
+ else if (rv == 1) {
+ return -5; // Unparsed text after the time
+ }
else if (tzinfo_pos == p_end) {
- // We know that there's no time zone, so if there's stuff at the
- // end of the string it's an error.
- if (rv == 1) {
- return -5;
- }
- else {
- return 0;
- }
+ return 0;
}
// Special case UTC / Zulu time.
@@ -1780,17 +1734,19 @@ inline static int
normalize_century(void)
{
static int cache = -1;
- if (cache < 0) {
+ int res = FT_ATOMIC_LOAD_INT_RELAXED(cache);
+ if (res < 0) {
char year[5];
struct tm date = {
.tm_year = -1801,
.tm_mon = 0,
.tm_mday = 1
};
- cache = (strftime(year, sizeof(year), "%Y", &date) &&
- strcmp(year, "0099") != 0);
+ res = (strftime(year, sizeof(year), "%Y", &date) &&
+ strcmp(year, "0099") != 0);
+ FT_ATOMIC_STORE_INT_RELAXED(cache, res);
}
- return cache;
+ return res;
}
static PyObject *
@@ -1861,12 +1817,17 @@ static PyObject *
make_freplacement(PyObject *object)
{
char freplacement[64];
- if (PyTime_Check(object))
- sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
- else if (PyDateTime_Check(object))
- sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
- else
- sprintf(freplacement, "%06d", 0);
+ if (PyTime_Check(object)) {
+ PyOS_snprintf(freplacement, sizeof(freplacement),
+ "%06d", TIME_GET_MICROSECOND(object));
+ }
+ else if (PyDateTime_Check(object)) {
+ PyOS_snprintf(freplacement, sizeof(freplacement),
+ "%06d", DATE_GET_MICROSECOND(object));
+ }
+ else {
+ PyOS_snprintf(freplacement, sizeof(freplacement), "%06d", 0);
+ }
return PyUnicode_FromString(freplacement);
}
@@ -1892,10 +1853,12 @@ wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
assert(object && format && timetuple);
assert(PyUnicode_Check(format));
- PyObject *strftime = PyImport_ImportModuleAttrString("time", "strftime");
- if (strftime == NULL) {
+ PyObject *current_mod = NULL;
+ datetime_state *st = GET_CURRENT_STATE(current_mod);
+ if (st == NULL) {
return NULL;
}
+ PyObject *strftime = st->time_strftime;
/* Scan the input format, looking for %z/%Z/%f escapes, building
* a new format. Since computing the replacements for those codes
@@ -1964,6 +1927,29 @@ wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
}
replacement = freplacement;
}
+ else if (ch >= '1' && ch <= '6'
+ && i < flen && PyUnicode_READ_CHAR(format, i) == 'f')
+ {
+ /* %Nf -> first N digits of microseconds */
+ i++;
+ if (freplacement == NULL) {
+ freplacement = make_freplacement(object);
+ if (freplacement == NULL) {
+ goto Error;
+ }
+ }
+ if (PyUnicodeWriter_WriteSubstring(writer, format, start, end) < 0) {
+ goto Error;
+ }
+ start = i;
+ Py_ssize_t precision = ch - '0';
+ if (PyUnicodeWriter_WriteSubstring(writer, freplacement,
+ 0, precision) < 0)
+ {
+ goto Error;
+ }
+ continue;
+ }
else if (normalize_century()
&& (ch == 'Y' || ch == 'G' || ch == 'F' || ch == 'C'))
{
@@ -2055,7 +2041,7 @@ wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
Py_XDECREF(zreplacement);
Py_XDECREF(colonzreplacement);
Py_XDECREF(Zreplacement);
- Py_XDECREF(strftime);
+ RELEASE_CURRENT_STATE(st, current_mod);
return result;
Error:
@@ -2068,41 +2054,26 @@ wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
* from C. Perhaps they should be.
*/
-/* Call time.time() and return its result (a Python float). */
-static PyObject *
-time_time(void)
-{
- PyObject *result = NULL;
- PyObject *time = PyImport_ImportModuleAttrString("time", "time");
-
- if (time != NULL) {
- result = PyObject_CallNoArgs(time);
- Py_DECREF(time);
- }
- return result;
-}
-
/* Build a time.struct_time. The weekday and day number are automatically
* computed from the y,m,d args.
*/
static PyObject *
build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
{
- PyObject *struct_time;
- PyObject *result;
-
- struct_time = PyImport_ImportModuleAttrString("time", "struct_time");
- if (struct_time == NULL) {
+ PyObject *current_mod = NULL;
+ datetime_state *st = GET_CURRENT_STATE(current_mod);
+ if (st == NULL) {
return NULL;
}
- result = PyObject_CallFunction(struct_time, "((iiiiiiiii))",
+ PyObject *result = PyObject_CallFunction(st->time_struct_time,
+ "((iiiiiiiii))",
y, m, d,
hh, mm, ss,
weekday(y, m, d),
days_before_month(y, m) + d,
dstflag);
- Py_DECREF(struct_time);
+ RELEASE_CURRENT_STATE(st, current_mod);
return result;
}
@@ -2130,15 +2101,25 @@ diff_to_bool(int diff, int op)
/* Convert a timedelta to a number of us,
* (24*3600*self.days + self.seconds)*1000000 + self.microseconds
* as a Python int.
- * Doing mixed-radix arithmetic by hand instead is excruciating in C,
- * due to ubiquitous overflow possibilities.
+ * The number of whole seconds always fits in int64_t, and so does the
+ * number of microseconds unless the delta is very large, so compute it
+ * in C when possible and fall back to Python int arithmetic otherwise.
+ * One second is reserved at the limit so that adding the microseconds
+ * field cannot overflow.
*/
static PyObject *
delta_to_microseconds(PyDateTime_Delta *self)
{
+ const int64_t max_seconds = INT64_MAX / 1000000 - 1;
+ int64_t seconds = (int64_t)GET_TD_DAYS(self) * (24 * 3600)
+ + GET_TD_SECONDS(self);
+ if (-max_seconds <= seconds && seconds <= max_seconds) {
+ return PyLong_FromInt64(seconds * 1000000
+ + GET_TD_MICROSECONDS(self));
+ }
+
PyObject *x1 = NULL;
PyObject *x2 = NULL;
- PyObject *x3 = NULL;
PyObject *result = NULL;
PyObject *current_mod;
@@ -2147,42 +2128,23 @@ delta_to_microseconds(PyDateTime_Delta *self)
return NULL;
}
- x1 = PyLong_FromLong(GET_TD_DAYS(self));
+ x1 = PyLong_FromInt64(seconds); /* days and seconds in seconds */
if (x1 == NULL)
goto Done;
- x2 = PyNumber_Multiply(x1, CONST_SEC_PER_DAY(st)); /* days in seconds */
+ x2 = PyNumber_Multiply(x1, CONST_US_PER_SECOND(st)); /* us */
if (x2 == NULL)
goto Done;
- Py_SETREF(x1, NULL);
-
- /* x2 has days in seconds */
- x1 = PyLong_FromLong(GET_TD_SECONDS(self)); /* seconds */
- if (x1 == NULL)
- goto Done;
- x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
- if (x3 == NULL)
- goto Done;
- Py_DECREF(x1);
- Py_DECREF(x2);
- /* x1 = */ x2 = NULL;
- /* x3 has days+seconds in seconds */
- x1 = PyNumber_Multiply(x3, CONST_US_PER_SECOND(st)); /* us */
+ /* x2 has days+seconds in us */
+ Py_SETREF(x1, PyLong_FromLong(GET_TD_MICROSECONDS(self)));
if (x1 == NULL)
goto Done;
- Py_SETREF(x3, NULL);
-
- /* x1 has days+seconds in us */
- x2 = PyLong_FromLong(GET_TD_MICROSECONDS(self));
- if (x2 == NULL)
- goto Done;
- result = PyNumber_Add(x1, x2);
+ result = PyNumber_Add(x2, x1);
assert(result == NULL || PyLong_CheckExact(result));
Done:
Py_XDECREF(x1);
Py_XDECREF(x2);
- Py_XDECREF(x3);
RELEASE_CURRENT_STATE(st, current_mod);
return result;
}
@@ -3290,14 +3252,18 @@ date_fromtimestamp(PyTypeObject *cls, PyObject *obj)
{
struct tm tm;
time_t t;
+ int year;
if (_PyTime_ObjectToTime_t(obj, &t, _PyTime_ROUND_FLOOR) == -1)
return NULL;
if (_PyTime_localtime(t, &tm) != 0)
return NULL;
+ if (year_from_tm(&tm, &year) < 0) {
+ return NULL;
+ }
- return new_date_subclass_ex(tm.tm_year + 1900,
+ return new_date_subclass_ex(year,
tm.tm_mon + 1,
tm.tm_mday,
cls);
@@ -3337,7 +3303,11 @@ datetime_date_today_impl(PyTypeObject *type)
type);
}
- PyObject *time = time_time();
+ PyTime_t ts;
+ if (PyTime_Time(&ts) < 0) {
+ return NULL;
+ }
+ PyObject *time = PyFloat_FromDouble(PyTime_AsSecondsDouble(ts));
if (time == NULL) {
return NULL;
}
@@ -3412,7 +3382,16 @@ datetime_date_fromordinal_impl(PyTypeObject *type, int ordinal)
PyErr_SetString(PyExc_ValueError, "ordinal must be >= 1");
return NULL;
}
- ord_to_ymd(ordinal, &year, &month, &day);
+ if (ordinal <= MAXORDINAL) {
+ ord_to_ymd(ordinal, &year, &month, &day);
+ }
+ else {
+ /* Out of range, but compute the year for the error message.
+ * The calendar repeats every 400 years (DI400Y days). */
+ int cycles = (ordinal - 1) / DI400Y;
+ ord_to_ymd(ordinal - cycles * DI400Y, &year, &month, &day);
+ year += 400 * cycles;
+ }
return new_date_subclass_ex(year, month, day, type);
}
@@ -3520,6 +3499,11 @@ datetime_date_strptime_impl(PyTypeObject *type, PyObject *string,
PyObject *format)
/*[clinic end generated code: output=454d473bee2d5161 input=2db8f0b2b5242deb]*/
{
+ _PyTime_StrptimeFields fields;
+ if (type == DATE_TYPE(NO_STATE) &&
+ _PyTime_Strptime(string, format, &fields)) {
+ return new_date_ex(fields.year, fields.month, fields.day, type);
+ }
PyObject *result;
PyObject *module = PyImport_Import(&_Py_ID(_strptime));
@@ -4549,6 +4533,22 @@ static PyMethodDef timezone_methods[] = {
{NULL, NULL}
};
+static PyObject *
+timezone_name(PyObject *op, void *Py_UNUSED(closure))
+{
+ PyDateTime_TimeZone *self = PyTimeZone_CAST(op);
+ if (self->name == NULL) {
+ Py_RETURN_NONE;
+ }
+ return Py_NewRef(self->name);
+}
+
+static PyGetSetDef timezone_getset[] = {
+ {"name", timezone_name, NULL,
+ PyDoc_STR("Name given when the timezone was created.")},
+ {NULL}
+};
+
static PyTypeObject PyDateTime_TimeZoneType = {
PyVarObject_HEAD_INIT(NULL, 0)
"datetime.timezone", /* tp_name */
@@ -4579,7 +4579,7 @@ static PyTypeObject PyDateTime_TimeZoneType = {
0, /* tp_iternext */
timezone_methods, /* tp_methods */
0, /* tp_members */
- 0, /* tp_getset */
+ timezone_getset, /* tp_getset */
&PyDateTime_TZInfoType, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
@@ -4792,6 +4792,20 @@ datetime_time_strptime_impl(PyTypeObject *type, PyObject *string,
PyObject *format)
/*[clinic end generated code: output=ae05a9bc0241d3bf input=f01d0b9eb5383da5]*/
{
+ _PyTime_StrptimeFields fields;
+ if (type == TIME_TYPE(NO_STATE) &&
+ _PyTime_Strptime(string, format, &fields)) {
+ PyObject *tzinfo = tzinfo_from_isoformat_results(
+ fields.gmtoff != INT_MIN, fields.gmtoff, 0);
+ if (tzinfo == NULL) {
+ return NULL;
+ }
+ PyObject *result = new_time_ex(
+ fields.hour, fields.minute, fields.second, fields.fraction,
+ tzinfo, type);
+ Py_DECREF(tzinfo);
+ return result;
+ }
PyObject *result;
PyObject *module = PyImport_Import(&_Py_ID(_strptime));
@@ -5057,22 +5071,33 @@ time_richcompare(PyObject *self, PyObject *other, int op)
}
/* The hard case: both aware with different UTC offsets */
else if (offset1 != Py_None && offset2 != Py_None) {
- int offsecs1, offsecs2;
+ long long norm_us1, norm_us2;
assert(offset1 != offset2); /* else last "if" handled it */
- offsecs1 = TIME_GET_HOUR(self) * 3600 +
- TIME_GET_MINUTE(self) * 60 +
- TIME_GET_SECOND(self) -
- GET_TD_DAYS(offset1) * 86400 -
- GET_TD_SECONDS(offset1);
- offsecs2 = TIME_GET_HOUR(other) * 3600 +
- TIME_GET_MINUTE(other) * 60 +
- TIME_GET_SECOND(other) -
- GET_TD_DAYS(offset2) * 86400 -
- GET_TD_SECONDS(offset2);
- diff = offsecs1 - offsecs2;
- if (diff == 0)
- diff = TIME_GET_MICROSECOND(self) -
- TIME_GET_MICROSECOND(other);
+ norm_us1 =
+ ((TIME_GET_HOUR(self) * 3600 +
+ TIME_GET_MINUTE(self) * 60 +
+ TIME_GET_SECOND(self)) * 1000000LL +
+ TIME_GET_MICROSECOND(self)) -
+ ((GET_TD_DAYS(offset1) * 86400LL +
+ GET_TD_SECONDS(offset1)) * 1000000LL +
+ GET_TD_MICROSECONDS(offset1));
+ norm_us2 =
+ ((TIME_GET_HOUR(other) * 3600 +
+ TIME_GET_MINUTE(other) * 60 +
+ TIME_GET_SECOND(other)) * 1000000LL +
+ TIME_GET_MICROSECOND(other)) -
+ ((GET_TD_DAYS(offset2) * 86400LL +
+ GET_TD_SECONDS(offset2)) * 1000000LL +
+ GET_TD_MICROSECONDS(offset2));
+ if (norm_us1 < norm_us2) {
+ diff = -1;
+ }
+ else if (norm_us1 > norm_us2) {
+ diff = 1;
+ }
+ else {
+ diff = 0;
+ }
result = diff_to_bool(diff, op);
}
else if (op == Py_EQ) {
@@ -5618,7 +5643,9 @@ datetime_from_timet_and_us(PyTypeObject *cls, TM_FUNC f, time_t timet, int us,
if (f(timet, &tm) != 0)
return NULL;
- year = tm.tm_year + 1900;
+ if (year_from_tm(&tm, &year) < 0) {
+ return NULL;
+ }
month = tm.tm_mon + 1;
day = tm.tm_mday;
hour = tm.tm_hour;
@@ -5861,6 +5888,22 @@ datetime_datetime_strptime_impl(PyTypeObject *type, PyObject *string,
PyObject *format)
/*[clinic end generated code: output=af2c2d024f3203f5 input=ef7807589f1d50e7]*/
{
+ /* Subclasses retain the Python parser's constructor arguments. */
+ _PyTime_StrptimeFields fields;
+ if (type == DATETIME_TYPE(NO_STATE) &&
+ _PyTime_Strptime(string, format, &fields)) {
+ PyObject *tzinfo = tzinfo_from_isoformat_results(
+ fields.gmtoff != INT_MIN, fields.gmtoff, 0);
+ if (tzinfo == NULL) {
+ return NULL;
+ }
+ PyObject *result = new_datetime_ex(
+ fields.year, fields.month, fields.day,
+ fields.hour, fields.minute, fields.second, fields.fraction,
+ tzinfo, type);
+ Py_DECREF(tzinfo);
+ return result;
+ }
PyObject *result;
PyObject *module = PyImport_Import(&_Py_ID(_strptime));
@@ -6767,6 +6810,9 @@ local_timezone_from_timestamp(time_t timestamp)
struct tm local_time_tm;
PyObject *nameo = NULL;
const char *zone = NULL;
+#ifndef HAVE_STRUCT_TM_TM_ZONE
+ char buf[100]; // for zone, which is used after the block below
+#endif
if (_PyTime_localtime(timestamp, &local_time_tm) != 0)
return NULL;
@@ -6777,9 +6823,9 @@ local_timezone_from_timestamp(time_t timestamp)
{
PyObject *local_time, *utc_time;
struct tm utc_time_tm;
- char buf[100];
- strftime(buf, sizeof(buf), "%Z", &local_time_tm);
- zone = buf;
+ if (strftime(buf, sizeof(buf), "%Z", &local_time_tm) != 0) {
+ zone = buf;
+ }
local_time = new_datetime(local_time_tm.tm_year + 1900,
local_time_tm.tm_mon + 1,
local_time_tm.tm_mday,
@@ -6789,8 +6835,10 @@ local_timezone_from_timestamp(time_t timestamp)
if (local_time == NULL) {
return NULL;
}
- if (_PyTime_gmtime(timestamp, &utc_time_tm) != 0)
+ if (_PyTime_gmtime(timestamp, &utc_time_tm) != 0) {
+ Py_DECREF(local_time);
return NULL;
+ }
utc_time = new_datetime(utc_time_tm.tm_year + 1900,
utc_time_tm.tm_mon + 1,
utc_time_tm.tm_mday,
@@ -7449,6 +7497,8 @@ init_state(datetime_state *st, PyObject *module, PyObject *old_module)
.us_per_week = Py_NewRef(st_old->us_per_week),
.seconds_per_day = Py_NewRef(st_old->seconds_per_day),
.epoch = Py_NewRef(st_old->epoch),
+ .time_struct_time = Py_NewRef(st_old->time_struct_time),
+ .time_strftime = Py_NewRef(st_old->time_strftime),
};
return 0;
}
@@ -7493,6 +7543,15 @@ init_state(datetime_state *st, PyObject *module, PyObject *old_module)
return -1;
}
+ st->time_struct_time = PyImport_ImportModuleAttrString("time", "struct_time");
+ if (st->time_struct_time == NULL) {
+ return -1;
+ }
+ st->time_strftime = PyImport_ImportModuleAttrString("time", "strftime");
+ if (st->time_strftime == NULL) {
+ return -1;
+ }
+
return 0;
}
@@ -7502,6 +7561,9 @@ traverse_state(datetime_state *st, visitproc visit, void *arg)
/* heap types */
Py_VISIT(st->isocalendar_date_type);
+ Py_VISIT(st->time_struct_time);
+ Py_VISIT(st->time_strftime);
+
return 0;
}
@@ -7517,6 +7579,8 @@ clear_state(datetime_state *st)
Py_CLEAR(st->us_per_week);
Py_CLEAR(st->seconds_per_day);
Py_CLEAR(st->epoch);
+ Py_CLEAR(st->time_struct_time);
+ Py_CLEAR(st->time_strftime);
return 0;
}
@@ -7661,19 +7725,19 @@ _datetime_exec(PyObject *module)
* pasting together 4 single years.
*/
static_assert(DI4Y == 4 * 365 + 1, "DI4Y");
- assert(DI4Y == days_before_year(4+1));
+ assert(DI4Y == _PyTime_DaysBeforeYear(4+1));
/* Similarly, a 400-year cycle has an extra leap day over what we'd
* get from pasting together 4 100-year cycles.
*/
static_assert(DI400Y == 4 * DI100Y + 1, "DI400Y");
- assert(DI400Y == days_before_year(400+1));
+ assert(DI400Y == _PyTime_DaysBeforeYear(400+1));
/* OTOH, a 100-year cycle has one fewer leap day than we'd get from
* pasting together 25 4-year cycles.
*/
static_assert(DI100Y == 25 * DI4Y - 1, "DI100Y");
- assert(DI100Y == days_before_year(100+1));
+ assert(DI100Y == _PyTime_DaysBeforeYear(100+1));
if (set_current_module(interp, module) < 0) {
goto error;
diff --git a/Modules/_dbmmodule.c b/Modules/_dbmmodule.c
index a9f4f27d9eb742e..fe2d34a53b57113 100644
--- a/Modules/_dbmmodule.c
+++ b/Modules/_dbmmodule.c
@@ -28,7 +28,12 @@
static const char which_dbm[] = "GNU gdbm";
#elif defined(USE_NDBM)
#include
+ #ifdef _GDBM_H_
+ /* ndbm.h is the GDBM compatibility interface. */
static const char which_dbm[] = "GNU gdbm";
+ #else
+ static const char which_dbm[] = "ndbm";
+ #endif
#elif defined(USE_BERKDB)
#ifndef DB_DBM_HSEARCH
#define DB_DBM_HSEARCH 1
@@ -111,10 +116,16 @@ dbm_dealloc(PyObject *self)
Py_DECREF(tp);
}
+/*[clinic input]
+@critical_section
+_dbm.dbm.__len__ as dbm_length
+[clinic start generated code]*/
+
static Py_ssize_t
-dbm_length_lock_held(PyObject *self)
+dbm_length_impl(dbmobject *self)
+/*[clinic end generated code: output=d7ea9510562e5f86 input=f912d65e9b06fef5]*/
{
- dbmobject *dp = dbmobject_CAST(self);
+ dbmobject *dp = self;
_dbm_state *state = PyType_GetModuleState(Py_TYPE(dp));
assert(state != NULL);
if (dp->di_dbm == NULL) {
@@ -134,20 +145,16 @@ dbm_length_lock_held(PyObject *self)
return dp->di_size;
}
-static Py_ssize_t
-dbm_length(PyObject *self)
-{
- Py_ssize_t result;
- Py_BEGIN_CRITICAL_SECTION(self);
- result = dbm_length_lock_held(self);
- Py_END_CRITICAL_SECTION();
- return result;
-}
+/*[clinic input]
+@critical_section
+_dbm.dbm.__bool__ as dbm_bool
+[clinic start generated code]*/
static int
-dbm_bool_lock_held(PyObject *self)
+dbm_bool_impl(dbmobject *self)
+/*[clinic end generated code: output=b550ce1ae52d6ad1 input=212af765b6e60719]*/
{
- dbmobject *dp = dbmobject_CAST(self);
+ dbmobject *dp = self;
_dbm_state *state = PyType_GetModuleState(Py_TYPE(dp));
assert(state != NULL);
@@ -176,22 +183,20 @@ dbm_bool_lock_held(PyObject *self)
return 1;
}
-static int
-dbm_bool(PyObject *self)
-{
- int result;
- Py_BEGIN_CRITICAL_SECTION(self);
- result = dbm_bool_lock_held(self);
- Py_END_CRITICAL_SECTION();
- return result;
-}
+/*[clinic input]
+@critical_section
+_dbm.dbm.__getitem__ as dbm_subscript
+ key: object
+ /
+[clinic start generated code]*/
static PyObject *
-dbm_subscript_lock_held(PyObject *self, PyObject *key)
+dbm_subscript_impl(dbmobject *self, PyObject *key)
+/*[clinic end generated code: output=6278465f3ff37eaa input=e748b684a0870527]*/
{
datum drec, krec;
Py_ssize_t tmp_size;
- dbmobject *dp = dbmobject_CAST(self);
+ dbmobject *dp = self;
_dbm_state *state = PyType_GetModuleState(Py_TYPE(dp));
assert(state != NULL);
if (!PyArg_Parse(key, "s#", &krec.dptr, &tmp_size)) {
@@ -213,22 +218,22 @@ dbm_subscript_lock_held(PyObject *self, PyObject *key)
return PyBytes_FromStringAndSize(drec.dptr, drec.dsize);
}
-static PyObject *
-dbm_subscript(PyObject *self, PyObject *key)
-{
- PyObject *result;
- Py_BEGIN_CRITICAL_SECTION(self);
- result = dbm_subscript_lock_held(self, key);
- Py_END_CRITICAL_SECTION();
- return result;
-}
+/*[clinic input]
+@critical_section
+_dbm.dbm.__setitem__ as dbm_ass_sub
+
+ v: object
+ w: object
+ /
+[clinic start generated code]*/
static int
-dbm_ass_sub_lock_held(PyObject *self, PyObject *v, PyObject *w)
+dbm_ass_sub_impl(dbmobject *self, PyObject *v, PyObject *w)
+/*[clinic end generated code: output=33e861810d1fd44a input=4f10cc93a02142ee]*/
{
datum krec, drec;
Py_ssize_t tmp_size;
- dbmobject *dp = dbmobject_CAST(self);
+ dbmobject *dp = self;
if ( !PyArg_Parse(v, "s#", &krec.dptr, &tmp_size) ) {
PyErr_SetString(PyExc_TypeError,
@@ -278,16 +283,6 @@ dbm_ass_sub_lock_held(PyObject *self, PyObject *v, PyObject *w)
return 0;
}
-static int
-dbm_ass_sub(PyObject *self, PyObject *v, PyObject *w)
-{
- int result;
- Py_BEGIN_CRITICAL_SECTION(self);
- result = dbm_ass_sub_lock_held(self, v, w);
- Py_END_CRITICAL_SECTION();
- return result;
-}
-
/*[clinic input]
@critical_section
_dbm.dbm.close
@@ -347,10 +342,18 @@ _dbm_dbm_keys_impl(dbmobject *self, PyTypeObject *cls)
return v;
}
+/*[clinic input]
+@critical_section
+_dbm.dbm.__contains__ as dbm_contains
+ arg: object
+ /
+[clinic start generated code]*/
+
static int
-dbm_contains_lock_held(PyObject *self, PyObject *arg)
+dbm_contains_impl(dbmobject *self, PyObject *arg)
+/*[clinic end generated code: output=6c42b797ada528bc input=94134e7abf3eeb6e]*/
{
- dbmobject *dp = dbmobject_CAST(self);
+ dbmobject *dp = self;
datum key, val;
Py_ssize_t size;
@@ -381,16 +384,6 @@ dbm_contains_lock_held(PyObject *self, PyObject *arg)
return val.dptr != NULL;
}
-static int
-dbm_contains(PyObject *self, PyObject *arg)
-{
- int result;
- Py_BEGIN_CRITICAL_SECTION(self);
- result = dbm_contains_lock_held(self, arg);
- Py_END_CRITICAL_SECTION();
- return result;
-}
-
/*[clinic input]
@critical_section
_dbm.dbm.get
@@ -513,15 +506,21 @@ dbm__enter__(PyObject *self, PyObject *Py_UNUSED(dummy))
return Py_NewRef(self);
}
+/*[clinic input]
+@critical_section
+_dbm.dbm.__exit__
+
+ *exc_info: array
+
+Close the database.
+[clinic start generated code]*/
+
static PyObject *
-dbm__exit__(PyObject *self, PyObject *Py_UNUSED(args))
+_dbm_dbm___exit___impl(dbmobject *self, PyObject * const *exc_info,
+ Py_ssize_t exc_info_length)
+/*[clinic end generated code: output=f9549bf513b3285d input=340d8190b6fb0f15]*/
{
- PyObject *result;
- dbmobject *dp = dbmobject_CAST(self);
- Py_BEGIN_CRITICAL_SECTION(self);
- result = _dbm_dbm_close_impl(dp);
- Py_END_CRITICAL_SECTION();
- return result;
+ return _dbm_dbm_close_impl(self);
}
static PyMethodDef dbm_methods[] = {
@@ -531,7 +530,7 @@ static PyMethodDef dbm_methods[] = {
_DBM_DBM_SETDEFAULT_METHODDEF
_DBM_DBM_CLEAR_METHODDEF
{"__enter__", dbm__enter__, METH_NOARGS, NULL},
- {"__exit__", dbm__exit__, METH_VARARGS, NULL},
+ _DBM_DBM___EXIT___METHODDEF
{NULL, NULL} /* sentinel */
};
@@ -628,6 +627,136 @@ static PyMethodDef dbmmodule_methods[] = {
{ 0, 0 },
};
+#if defined(GDBM_VERSION_MAJOR) || defined(DB_VERSION_MAJOR)
+static PyStructSequence_Field version_info_fields[] = {
+ {"major", "Major release number"},
+ {"minor", "Minor release number"},
+ {"patch", "Patch release number"},
+ {0}
+};
+
+static PyObject *
+make_version_info(PyTypeObject *type, int major, int minor, int patch)
+{
+ PyObject *version;
+ int pos = 0;
+
+ version = PyStructSequence_New(type);
+ if (version == NULL) {
+ return NULL;
+ }
+
+#define SetItem(VALUE) \
+ PyStructSequence_SET_ITEM(version, pos++, VALUE); \
+ if (PyErr_Occurred()) { \
+ Py_DECREF(version); \
+ return NULL; \
+ }
+
+ SetItem(PyLong_FromLong(major))
+ SetItem(PyLong_FromLong(minor))
+ SetItem(PyLong_FromLong(patch))
+#undef SetItem
+
+ return version;
+}
+#endif
+
+#if defined(GDBM_VERSION_MAJOR)
+PyDoc_STRVAR(gdbm_version_info__doc__,
+"_dbm.gdbm_version_info\n\
+\n\
+GDBM version information as a named tuple.");
+
+static PyStructSequence_Desc gdbm_version_info_desc = {
+ "_dbm.gdbm_version_info", /* name */
+ gdbm_version_info__doc__, /* doc */
+ version_info_fields, /* fields */
+ 3
+};
+
+static int
+add_version_constants(PyObject *module)
+{
+ if (PyModule_AddStringConstant(module, "gdbm_version", gdbm_version) < 0) {
+ return -1;
+ }
+ PyTypeObject *version_type;
+ version_type = PyStructSequence_NewType(&gdbm_version_info_desc);
+ if (version_type == NULL) {
+ return -1;
+ }
+ if (PyModule_Add(module, "GDBM_VERSION_INFO",
+ make_version_info(version_type, GDBM_VERSION_MAJOR,
+ GDBM_VERSION_MINOR, GDBM_VERSION_PATCH)) < 0)
+ {
+ Py_DECREF(version_type);
+ return -1;
+ }
+ if (PyModule_Add(module, "gdbm_version_info",
+ make_version_info(version_type, gdbm_version_number[0],
+ gdbm_version_number[1],
+ gdbm_version_number[2])) < 0)
+ {
+ Py_DECREF(version_type);
+ return -1;
+ }
+ Py_DECREF(version_type);
+ return 0;
+}
+#elif defined(DB_VERSION_MAJOR)
+PyDoc_STRVAR(bdb_version_info__doc__,
+"_dbm.bdb_version_info\n\
+\n\
+Berkeley DB version information as a named tuple.");
+
+static PyStructSequence_Desc bdb_version_info_desc = {
+ "_dbm.bdb_version_info", /* name */
+ bdb_version_info__doc__, /* doc */
+ version_info_fields, /* fields */
+ 3
+};
+
+static int
+add_version_constants(PyObject *module)
+{
+ int major, minor, patch;
+ const char *version = db_version(&major, &minor, &patch);
+ if (PyModule_AddStringConstant(module, "BDB_VERSION", DB_VERSION_STRING) < 0) {
+ return -1;
+ }
+ if (PyModule_AddStringConstant(module, "bdb_version", version) < 0) {
+ return -1;
+ }
+ PyTypeObject *version_type;
+ version_type = PyStructSequence_NewType(&bdb_version_info_desc);
+ if (version_type == NULL) {
+ return -1;
+ }
+ if (PyModule_Add(module, "BDB_VERSION_INFO",
+ make_version_info(version_type, DB_VERSION_MAJOR,
+ DB_VERSION_MINOR, DB_VERSION_PATCH)) < 0)
+ {
+ Py_DECREF(version_type);
+ return -1;
+ }
+ if (PyModule_Add(module, "bdb_version_info",
+ make_version_info(version_type, major, minor, patch)) < 0)
+ {
+ Py_DECREF(version_type);
+ return -1;
+ }
+ Py_DECREF(version_type);
+ return 0;
+}
+#else
+static int
+add_version_constants(PyObject *module)
+{
+ return 0;
+}
+#endif
+
static int
_dbm_exec(PyObject *module)
{
@@ -644,6 +773,9 @@ _dbm_exec(PyObject *module)
if (PyModule_AddStringConstant(module, "library", which_dbm) < 0) {
return -1;
}
+ if (add_version_constants(module) < 0) {
+ return -1;
+ }
if (PyModule_AddType(module, (PyTypeObject *)state->dbm_error) < 0) {
return -1;
}
diff --git a/Modules/_decimal/_decimal.c b/Modules/_decimal/_decimal.c
index dc1b3c06bed9521..3a128a13222f9b5 100644
--- a/Modules/_decimal/_decimal.c
+++ b/Modules/_decimal/_decimal.c
@@ -57,7 +57,6 @@
#define _PY_DEC_ROUND_GUARD (MPD_ROUND_GUARD-1)
#endif
-#include "clinic/_decimal.c.h"
#define MPD_SPEC_VERSION "1.70" // Highest version of the spec this complies with
// See https://speleotrove.com/decimal/decarith.html
@@ -66,8 +65,9 @@
module _decimal
class _decimal.Decimal "PyObject *" "&dec_spec"
class _decimal.Context "PyObject *" "&context_spec"
+class _decimal.ContextManager "PyDecContextManagerObject *" "&ctxmanager_spec"
[clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=a6a6c0bdf4e576ef]*/
+/*[clinic end generated code: output=da39a3ee5e6b4b0d input=52b8c97cabc5bf05]*/
struct PyDecContextObject;
struct DecCondMap;
@@ -234,6 +234,8 @@ typedef struct {
PyObject *global;
} PyDecContextManagerObject;
+#include "clinic/_decimal.c.h"
+
#define _PyDecContextManagerObject_CAST(op) ((PyDecContextManagerObject *)(op))
#undef MPD
@@ -346,30 +348,6 @@ static const char *dec_signal_string[MPD_NUM_FLAGS] = {
"Underflow",
};
-static const char *invalid_rounding_err =
-"valid values for rounding are:\n\
- [ROUND_CEILING, ROUND_FLOOR, ROUND_UP, ROUND_DOWN,\n\
- ROUND_HALF_UP, ROUND_HALF_DOWN, ROUND_HALF_EVEN,\n\
- ROUND_05UP]";
-
-static const char *invalid_signals_err =
-"valid values for signals are:\n\
- [InvalidOperation, FloatOperation, DivisionByZero,\n\
- Overflow, Underflow, Subnormal, Inexact, Rounded,\n\
- Clamped]";
-
-#ifdef EXTRA_FUNCTIONALITY
-static const char *invalid_flags_err =
-"valid values for _flags or _traps are:\n\
- signals:\n\
- [DecIEEEInvalidOperation, DecFloatOperation, DecDivisionByZero,\n\
- DecOverflow, DecUnderflow, DecSubnormal, DecInexact, DecRounded,\n\
- DecClamped]\n\
- conditions which trigger DecIEEEInvalidOperation:\n\
- [DecInvalidOperation, DecConversionSyntax, DecDivisionImpossible,\n\
- DecDivisionUndefined, DecFpuError, DecInvalidContext, DecMallocError]";
-#endif
-
static int
value_error_int(const char *mesg)
{
@@ -440,7 +418,11 @@ exception_as_flag(decimal_state *state, PyObject *ex)
}
}
- PyErr_SetString(PyExc_KeyError, invalid_signals_err);
+ PyErr_SetString(PyExc_KeyError,
+ "valid values for signals are:\n"
+ " [InvalidOperation, FloatOperation, DivisionByZero,\n"
+ " Overflow, Underflow, Subnormal, Inexact, Rounded,\n"
+ " Clamped]");
return DEC_INVALID_SIGNALS;
}
@@ -599,7 +581,15 @@ long_as_flags(PyObject *v)
return DEC_ERR_OCCURRED;
}
if (x < 0 || x > (long)MPD_Max_status) {
- PyErr_SetString(PyExc_TypeError, invalid_flags_err);
+ PyErr_SetString(PyExc_TypeError,
+ "valid values for _flags or _traps are:\n"
+ " signals:\n"
+ " [DecIEEEInvalidOperation, DecFloatOperation, DecDivisionByZero,\n"
+ " DecOverflow, DecUnderflow, DecSubnormal, DecInexact, DecRounded,\n"
+ " DecClamped]\n"
+ " conditions which trigger DecIEEEInvalidOperation:\n"
+ " [DecInvalidOperation, DecConversionSyntax, DecDivisionImpossible,\n"
+ " DecDivisionUndefined, DecFpuError, DecInvalidContext, DecMallocError]");
return DEC_INVALID_SIGNALS;
}
@@ -655,7 +645,11 @@ getround(decimal_state *state, PyObject *v)
}
}
- return type_error_int(invalid_rounding_err);
+ return type_error_int(
+ "valid values for rounding are:\n"
+ " [ROUND_CEILING, ROUND_FLOOR, ROUND_UP, ROUND_DOWN,\n"
+ " ROUND_HALF_UP, ROUND_HALF_DOWN, ROUND_HALF_EVEN,\n"
+ " ROUND_05UP]");
}
@@ -669,7 +663,7 @@ getround(decimal_state *state, PyObject *v)
initialized to new SignalDicts. Once a SignalDict is tied to
a context, it cannot be deleted. */
-static const char *INVALID_SIGNALDICT_ERROR_MSG = "invalid signal dict";
+static const char *const INVALID_SIGNALDICT_ERROR_MSG = "invalid signal dict";
static int
signaldict_init(PyObject *self,
@@ -1168,6 +1162,9 @@ context_settraps_dict(PyObject *self, PyObject *value)
decimal_state *state = get_module_state_from_ctx(self);
if (PyDecSignalDict_Check(state, value)) {
+ if (SdFlagAddr(value) == NULL) {
+ return value_error_int(INVALID_SIGNALDICT_ERROR_MSG);
+ }
flags = SdFlags(value);
}
else {
@@ -1234,6 +1231,9 @@ context_setstatus_dict(PyObject *self, PyObject *value)
decimal_state *state = get_module_state_from_ctx(self);
if (PyDecSignalDict_Check(state, value)) {
+ if (SdFlagAddr(value) == NULL) {
+ return value_error_int(INVALID_SIGNALDICT_ERROR_MSG);
+ }
flags = SdFlags(value);
}
else {
@@ -1333,32 +1333,37 @@ context_setattr(PyObject *self, PyObject *name, PyObject *value)
return PyObject_GenericSetAttr(self, name, value);
}
+/* In the constructor None means "not specified". */
+#define NONE_TO_NULL(x) ((x) == Py_None ? NULL : (x))
+
+/* Set the given attributes. An attribute is left unchanged if the
+ corresponding argument is NULL. */
static int
context_setattrs(PyObject *self, PyObject *prec, PyObject *rounding,
PyObject *emin, PyObject *emax, PyObject *capitals,
PyObject *clamp, PyObject *status, PyObject *traps) {
int ret;
- if (prec != Py_None && context_setprec(self, prec, NULL) < 0) {
+ if (prec != NULL && context_setprec(self, prec, NULL) < 0) {
return -1;
}
- if (rounding != Py_None && context_setround(self, rounding, NULL) < 0) {
+ if (rounding != NULL && context_setround(self, rounding, NULL) < 0) {
return -1;
}
- if (emin != Py_None && context_setemin(self, emin, NULL) < 0) {
+ if (emin != NULL && context_setemin(self, emin, NULL) < 0) {
return -1;
}
- if (emax != Py_None && context_setemax(self, emax, NULL) < 0) {
+ if (emax != NULL && context_setemax(self, emax, NULL) < 0) {
return -1;
}
- if (capitals != Py_None && context_setcapitals(self, capitals, NULL) < 0) {
+ if (capitals != NULL && context_setcapitals(self, capitals, NULL) < 0) {
return -1;
}
- if (clamp != Py_None && context_setclamp(self, clamp, NULL) < 0) {
+ if (clamp != NULL && context_setclamp(self, clamp, NULL) < 0) {
return -1;
}
- if (traps != Py_None) {
+ if (traps != NULL) {
if (PyList_Check(traps)) {
ret = context_settraps_list(self, traps);
}
@@ -1374,7 +1379,7 @@ context_setattrs(PyObject *self, PyObject *prec, PyObject *rounding,
return ret;
}
}
- if (status != Py_None) {
+ if (status != NULL) {
if (PyList_Check(status)) {
ret = context_setstatus_list(self, status);
}
@@ -1499,6 +1504,20 @@ static int
context_clear(PyObject *op)
{
PyDecContextObject *self = _PyDecContextObject_CAST(op);
+ /* Since traps and flags hold a borrowed reference to the
+ flags stored in the context object, these references need
+ to be cleared when the context object is deallocated
+ because traps and flags can survive. See gh-146011. */
+ PyDecSignalDictObject *traps = _PyDecSignalDictObject_CAST(self->traps);
+ PyDecSignalDictObject *flags = _PyDecSignalDictObject_CAST(self->flags);
+
+ if (traps != NULL) {
+ traps->flags = NULL;
+ }
+ if (flags != NULL) {
+ flags->flags = NULL;
+ }
+
Py_CLEAR(self->traps);
Py_CLEAR(self->flags);
return 0;
@@ -1545,10 +1564,11 @@ context_init_impl(PyObject *self, PyObject *prec, PyObject *rounding,
PyObject *clamp, PyObject *status, PyObject *traps)
/*[clinic end generated code: output=8bfdc59fbe862f44 input=45c704b93cd02959]*/
{
+ /* The context has already been initialized with the default values. */
return context_setattrs(
- self, prec, rounding,
- emin, emax, capitals,
- clamp, status, traps
+ self, NONE_TO_NULL(prec), NONE_TO_NULL(rounding),
+ NONE_TO_NULL(emin), NONE_TO_NULL(emax), NONE_TO_NULL(capitals),
+ NONE_TO_NULL(clamp), NONE_TO_NULL(status), NONE_TO_NULL(traps)
);
}
@@ -1676,12 +1696,12 @@ _decimal.Context.copy
cls: defining_class
-Return a duplicate of the context with all flags cleared.
+Return a duplicate of the context.
[clinic start generated code]*/
static PyObject *
_decimal_Context_copy_impl(PyObject *self, PyTypeObject *cls)
-/*[clinic end generated code: output=31c9c8eeb0c0cf77 input=aef1c0bddabdf8f0]*/
+/*[clinic end generated code: output=31c9c8eeb0c0cf77 input=87f8b92b1c7462a5]*/
{
decimal_state *state = PyType_GetModuleState(cls);
@@ -1702,6 +1722,47 @@ _decimal_Context___copy___impl(PyObject *self, PyTypeObject *cls)
return context_copy(state, self);
}
+/*[clinic input]
+@text_signature "($self, /, **changes)"
+_decimal.Context.__replace__
+
+ cls: defining_class
+ *
+ prec: object = NULL
+ rounding: object = NULL
+ Emin as emin: object = NULL
+ Emax as emax: object = NULL
+ capitals: object = NULL
+ clamp: object = NULL
+ flags as status: object = NULL
+ traps: object = NULL
+
+Return a copy of the context with the specified attributes replaced.
+[clinic start generated code]*/
+
+static PyObject *
+_decimal_Context___replace___impl(PyObject *self, PyTypeObject *cls,
+ PyObject *prec, PyObject *rounding,
+ PyObject *emin, PyObject *emax,
+ PyObject *capitals, PyObject *clamp,
+ PyObject *status, PyObject *traps)
+/*[clinic end generated code: output=375ef0392df682ec input=414d9d00b25af6f3]*/
+{
+ decimal_state *state = PyType_GetModuleState(cls);
+
+ PyObject *result = context_copy(state, self);
+ if (result == NULL) {
+ return NULL;
+ }
+ if (context_setattrs(result, prec, rounding, emin, emax, capitals,
+ clamp, status, traps) < 0)
+ {
+ Py_DECREF(result);
+ return NULL;
+ }
+ return result;
+}
+
/*[clinic input]
_decimal.Context.__reduce__ = _decimal.Context.copy
@@ -1942,6 +2003,13 @@ current_context(decimal_state *state)
}
if (tl_context != NULL) {
+ if (!PyDecContext_Check(state, tl_context)) {
+ PyErr_Format(PyExc_TypeError,
+ "current decimal context must be a Context "
+ "instance, got %T", tl_context);
+ Py_DECREF(tl_context);
+ return NULL;
+ }
return tl_context;
}
@@ -2038,14 +2106,14 @@ _decimal.localcontext
ctx as local: object = None
*
- prec: object = None
- rounding: object = None
- Emin: object = None
- Emax: object = None
- capitals: object = None
- clamp: object = None
- flags: object = None
- traps: object = None
+ prec: object = NULL
+ rounding: object = NULL
+ Emin: object = NULL
+ Emax: object = NULL
+ capitals: object = NULL
+ clamp: object = NULL
+ flags: object = NULL
+ traps: object = NULL
Return a context manager for a copy of the supplied context.
@@ -2060,7 +2128,7 @@ _decimal_localcontext_impl(PyObject *module, PyObject *local, PyObject *prec,
PyObject *rounding, PyObject *Emin,
PyObject *Emax, PyObject *capitals,
PyObject *clamp, PyObject *flags, PyObject *traps)
-/*[clinic end generated code: output=9bf4e47742a809b0 input=490307b9689c3856]*/
+/*[clinic end generated code: output=9bf4e47742a809b0 input=616abb6ee1654373]*/
{
PyObject *global;
@@ -2148,11 +2216,21 @@ ctxmanager_set_local(PyObject *op, PyObject *Py_UNUSED(dummy))
return Py_NewRef(self->local);
}
+/*[clinic input]
+_decimal.ContextManager.__exit__
+
+ *exc_info: array
+
+Restore the global context.
+[clinic start generated code]*/
+
static PyObject *
-ctxmanager_restore_global(PyObject *op, PyObject *Py_UNUSED(args))
+_decimal_ContextManager___exit___impl(PyDecContextManagerObject *self,
+ PyObject * const *exc_info,
+ Py_ssize_t exc_info_length)
+/*[clinic end generated code: output=744a645b0145842d input=a86ec9080e28dff3]*/
{
PyObject *ret;
- PyDecContextManagerObject *self = _PyDecContextManagerObject_CAST(op);
ret = PyDec_SetCurrentContext(PyType_GetModule(Py_TYPE(self)), self->global);
if (ret == NULL) {
return NULL;
@@ -2165,7 +2243,7 @@ ctxmanager_restore_global(PyObject *op, PyObject *Py_UNUSED(args))
static PyMethodDef ctxmanager_methods[] = {
{"__enter__", ctxmanager_set_local, METH_NOARGS, NULL},
- {"__exit__", ctxmanager_restore_global, METH_VARARGS, NULL},
+ _DECIMAL_CONTEXTMANAGER___EXIT___METHODDEF
{NULL, NULL}
};
@@ -3248,6 +3326,7 @@ PyDec_FromObject(PyObject *v, PyObject *context)
}
/*[clinic input]
+@vectorcall
@classmethod
_decimal.Decimal.__new__ as dec_new
@@ -3264,7 +3343,7 @@ trap is active.
static PyObject *
dec_new_impl(PyTypeObject *type, PyObject *value, PyObject *context)
-/*[clinic end generated code: output=35f48a40c65625ba input=5f8a0892d3fcef80]*/
+/*[clinic end generated code: output=35f48a40c65625ba input=0e5ca99183562cd9]*/
{
decimal_state *state = get_module_state_by_def(type);
CONTEXT_CHECK_VA(state, context);
@@ -5921,11 +6000,13 @@ static Py_hash_t
dec_hash(PyObject *op)
{
PyDecObject *self = _PyDecObject_CAST(op);
- if (self->hash == -1) {
- self->hash = _dec_hash(self);
- }
+ Py_hash_t hash = FT_ATOMIC_LOAD_SSIZE_RELAXED(self->hash);
- return self->hash;
+ if (hash == -1) {
+ hash = _dec_hash(self);
+ FT_ATOMIC_STORE_SSIZE_RELAXED(self->hash, hash);
+ }
+ return hash;
}
/*[clinic input]
@@ -6123,6 +6204,7 @@ static PyType_Slot dec_slots[] = {
{Py_tp_methods, dec_methods},
{Py_tp_getset, dec_getsets},
{Py_tp_new, dec_new},
+ {Py_tp_vectorcall, dec_vectorcall},
// Number protocol
{Py_nb_add, nm_mpd_qadd},
@@ -6722,7 +6804,7 @@ _decimal.Context.power
Compute a**b.
If 'a' is negative, then 'b' must be integral. The result will be
-inexact unless 'a' is integral and the result is finite and can be
+inexact unless 'b' is integral and the result is finite and can be
expressed exactly in 'precision' digits. In the Python version the
result is always correctly rounded, in the C version the result is
almost always correctly rounded.
@@ -6740,7 +6822,7 @@ restrictions hold:
static PyObject *
_decimal_Context_power_impl(PyObject *context, PyTypeObject *cls,
PyObject *base, PyObject *exp, PyObject *mod)
-/*[clinic end generated code: output=d06d40c37cdd69dc input=178a254468ec189b]*/
+/*[clinic end generated code: output=d06d40c37cdd69dc input=660210a6607ca4b0]*/
{
PyObject *a, *b, *c = NULL;
PyObject *result;
@@ -7000,13 +7082,19 @@ _decimal_Context_apply_impl(PyObject *context, PyTypeObject *cls,
/*[clinic input]
_decimal.Context.canonical = _decimal.Context.is_normal
-Return a new instance of x.
+Returns the same Decimal object.
+
+As we do not have different encodings for the same number, the
+received object already is in its canonical form.
+
+>>> ExtendedContext.canonical(Decimal('2.50'))
+Decimal('2.50')
[clinic start generated code]*/
static PyObject *
_decimal_Context_canonical_impl(PyObject *context, PyTypeObject *cls,
PyObject *x)
-/*[clinic end generated code: output=f213e433e2032e5e input=025ecb106ac15bff]*/
+/*[clinic end generated code: output=f213e433e2032e5e input=d9f19ee3e7ed9433]*/
{
decimal_state *state = PyType_GetModuleState(cls);
if (!PyDec_Check(state, x)) {
@@ -7541,6 +7629,7 @@ static PyMethodDef context_methods [] =
/* Miscellaneous */
_DECIMAL_CONTEXT___COPY___METHODDEF
+ _DECIMAL_CONTEXT___REPLACE___METHODDEF
_DECIMAL_CONTEXT___REDUCE___METHODDEF
_DECIMAL_CONTEXT_COPY_METHODDEF
_DECIMAL_CONTEXT_CREATE_DECIMAL_METHODDEF
@@ -7680,6 +7769,104 @@ cfunc_noargs(PyTypeObject *t, const char *name)
return NULL;
}
+PyDoc_STRVAR(libmpdec_version_info__doc__,
+"decimal.libmpdec_version_info\n\
+\n\
+libmpdec version information as a named tuple.");
+
+static PyStructSequence_Field libmpdec_version_info_fields[] = {
+ {"major", "Major release number"},
+ {"minor", "Minor release number"},
+ {"micro", "Micro release number"},
+ {0}
+};
+
+static PyStructSequence_Desc libmpdec_version_info_desc = {
+ "decimal.libmpdec_version_info", /* name */
+ libmpdec_version_info__doc__, /* doc */
+ libmpdec_version_info_fields, /* fields */
+ 3
+};
+
+static PyObject *
+make_libmpdec_version_info(PyTypeObject *type, int major, int minor, int micro)
+{
+ PyObject *version;
+ int pos = 0;
+
+ version = PyStructSequence_New(type);
+ if (version == NULL) {
+ return NULL;
+ }
+
+#define SetItem(VALUE) \
+ PyStructSequence_SET_ITEM(version, pos++, VALUE); \
+ if (PyErr_Occurred()) { \
+ Py_DECREF(version); \
+ return NULL; \
+ }
+
+ SetItem(PyLong_FromLong(major))
+ SetItem(PyLong_FromLong(minor))
+ SetItem(PyLong_FromLong(micro))
+#undef SetItem
+
+ return version;
+}
+
+static PyObject *
+parse_libmpdec_version_info(PyTypeObject *type, const char *version)
+{
+ int major, minor, micro;
+ if (sscanf(version, "%d.%d.%d", &major, &minor, µ) != 3) {
+ PyErr_Format(PyExc_RuntimeError,
+ "unexpected libmpdec version string %s", version);
+ return NULL;
+ }
+ return make_libmpdec_version_info(type, major, minor, micro);
+}
+
+static int
+add_version_constants(PyObject *m)
+{
+ const char *version = mpd_version();
+ if (PyModule_AddStringConstant(m, "LIBMPDEC_VERSION", MPD_VERSION) < 0) {
+ return -1;
+ }
+ PyObject *obj = PyUnicode_FromString(version);
+ if (obj == NULL) {
+ return -1;
+ }
+ if (PyModule_AddObjectRef(m, "libmpdec_version", obj) < 0 ||
+ PyModule_AddObjectRef(m, "__libmpdec_version__", obj) < 0)
+ {
+ Py_DECREF(obj);
+ return -1;
+ }
+ Py_DECREF(obj);
+ PyTypeObject *version_type;
+ version_type = PyStructSequence_NewType(&libmpdec_version_info_desc);
+ if (version_type == NULL) {
+ return -1;
+ }
+ if (PyModule_Add(m, "LIBMPDEC_VERSION_INFO",
+ make_libmpdec_version_info(version_type, MPD_MAJOR_VERSION,
+ MPD_MINOR_VERSION,
+ MPD_MICRO_VERSION)) < 0)
+ {
+ Py_DECREF(version_type);
+ return -1;
+ }
+ if (PyModule_Add(m, "libmpdec_version_info",
+ parse_libmpdec_version_info(version_type, version)) < 0)
+ {
+ Py_DECREF(version_type);
+ return -1;
+ }
+ Py_DECREF(version_type);
+ return 0;
+}
+
static int minalloc_is_set = 0;
static int
@@ -7928,7 +8115,7 @@ _decimal_exec(PyObject *m)
/* Add specification version number */
CHECK_INT(PyModule_AddStringConstant(m, "SPEC_VERSION", MPD_SPEC_VERSION));
- CHECK_INT(PyModule_AddStringConstant(m, "__libmpdec_version__", mpd_version()));
+ CHECK_INT(add_version_constants(m));
return 0;
diff --git a/Modules/_decimal/clinic/_decimal.c.h b/Modules/_decimal/clinic/_decimal.c.h
index c803006ad443825..8aa362b5258d7df 100644
--- a/Modules/_decimal/clinic/_decimal.c.h
+++ b/Modules/_decimal/clinic/_decimal.c.h
@@ -371,7 +371,7 @@ PyDoc_STRVAR(_decimal_Context_copy__doc__,
"copy($self, /)\n"
"--\n"
"\n"
-"Return a duplicate of the context with all flags cleared.");
+"Return a duplicate of the context.");
#define _DECIMAL_CONTEXT_COPY_METHODDEF \
{"copy", _PyCFunction_CAST(_decimal_Context_copy), METH_METHOD|METH_FASTCALL|METH_KEYWORDS, _decimal_Context_copy__doc__},
@@ -410,6 +410,122 @@ _decimal_Context___copy__(PyObject *self, PyTypeObject *cls, PyObject *const *ar
return _decimal_Context___copy___impl(self, cls);
}
+PyDoc_STRVAR(_decimal_Context___replace____doc__,
+"__replace__($self, /, **changes)\n"
+"--\n"
+"\n"
+"Return a copy of the context with the specified attributes replaced.");
+
+#define _DECIMAL_CONTEXT___REPLACE___METHODDEF \
+ {"__replace__", _PyCFunction_CAST(_decimal_Context___replace__), METH_METHOD|METH_FASTCALL|METH_KEYWORDS, _decimal_Context___replace____doc__},
+
+static PyObject *
+_decimal_Context___replace___impl(PyObject *self, PyTypeObject *cls,
+ PyObject *prec, PyObject *rounding,
+ PyObject *emin, PyObject *emax,
+ PyObject *capitals, PyObject *clamp,
+ PyObject *status, PyObject *traps);
+
+static PyObject *
+_decimal_Context___replace__(PyObject *self, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
+{
+ PyObject *return_value = NULL;
+ #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
+
+ #define NUM_KEYWORDS 8
+ static struct {
+ PyGC_Head _this_is_not_used;
+ PyObject_VAR_HEAD
+ Py_hash_t ob_hash;
+ PyObject *ob_item[NUM_KEYWORDS];
+ } _kwtuple = {
+ .ob_base = PyVarObject_HEAD_INIT(&PyTuple_Type, NUM_KEYWORDS)
+ .ob_hash = -1,
+ .ob_item = { &_Py_ID(prec), &_Py_ID(rounding), &_Py_ID(Emin), &_Py_ID(Emax), &_Py_ID(capitals), &_Py_ID(clamp), &_Py_ID(flags), &_Py_ID(traps), },
+ };
+ #undef NUM_KEYWORDS
+ #define KWTUPLE (&_kwtuple.ob_base.ob_base)
+
+ #else // !Py_BUILD_CORE
+ # define KWTUPLE NULL
+ #endif // !Py_BUILD_CORE
+
+ static const char * const _keywords[] = {"prec", "rounding", "Emin", "Emax", "capitals", "clamp", "flags", "traps", NULL};
+ static _PyArg_Parser _parser = {
+ .keywords = _keywords,
+ .fname = "__replace__",
+ .kwtuple = KWTUPLE,
+ };
+ #undef KWTUPLE
+ PyObject *argsbuf[8];
+ Py_ssize_t noptargs = nargs + (kwnames ? PyTuple_GET_SIZE(kwnames) : 0) - 0;
+ PyObject *prec = NULL;
+ PyObject *rounding = NULL;
+ PyObject *emin = NULL;
+ PyObject *emax = NULL;
+ PyObject *capitals = NULL;
+ PyObject *clamp = NULL;
+ PyObject *status = NULL;
+ PyObject *traps = NULL;
+
+ args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
+ /*minpos*/ 0, /*maxpos*/ 0, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
+ if (!args) {
+ goto exit;
+ }
+ if (!noptargs) {
+ goto skip_optional_kwonly;
+ }
+ if (args[0]) {
+ prec = args[0];
+ if (!--noptargs) {
+ goto skip_optional_kwonly;
+ }
+ }
+ if (args[1]) {
+ rounding = args[1];
+ if (!--noptargs) {
+ goto skip_optional_kwonly;
+ }
+ }
+ if (args[2]) {
+ emin = args[2];
+ if (!--noptargs) {
+ goto skip_optional_kwonly;
+ }
+ }
+ if (args[3]) {
+ emax = args[3];
+ if (!--noptargs) {
+ goto skip_optional_kwonly;
+ }
+ }
+ if (args[4]) {
+ capitals = args[4];
+ if (!--noptargs) {
+ goto skip_optional_kwonly;
+ }
+ }
+ if (args[5]) {
+ clamp = args[5];
+ if (!--noptargs) {
+ goto skip_optional_kwonly;
+ }
+ }
+ if (args[6]) {
+ status = args[6];
+ if (!--noptargs) {
+ goto skip_optional_kwonly;
+ }
+ }
+ traps = args[7];
+skip_optional_kwonly:
+ return_value = _decimal_Context___replace___impl(self, cls, prec, rounding, emin, emax, capitals, clamp, status, traps);
+
+exit:
+ return return_value;
+}
+
PyDoc_STRVAR(_decimal_Context___reduce____doc__,
"__reduce__($self, /)\n"
"--\n"
@@ -512,14 +628,14 @@ _decimal_localcontext(PyObject *module, PyObject *const *args, Py_ssize_t nargs,
PyObject *argsbuf[9];
Py_ssize_t noptargs = nargs + (kwnames ? PyTuple_GET_SIZE(kwnames) : 0) - 0;
PyObject *local = Py_None;
- PyObject *prec = Py_None;
- PyObject *rounding = Py_None;
- PyObject *Emin = Py_None;
- PyObject *Emax = Py_None;
- PyObject *capitals = Py_None;
- PyObject *clamp = Py_None;
- PyObject *flags = Py_None;
- PyObject *traps = Py_None;
+ PyObject *prec = NULL;
+ PyObject *rounding = NULL;
+ PyObject *Emin = NULL;
+ PyObject *Emax = NULL;
+ PyObject *capitals = NULL;
+ PyObject *clamp = NULL;
+ PyObject *flags = NULL;
+ PyObject *traps = NULL;
args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
/*minpos*/ 0, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
@@ -589,6 +705,34 @@ _decimal_localcontext(PyObject *module, PyObject *const *args, Py_ssize_t nargs,
return return_value;
}
+PyDoc_STRVAR(_decimal_ContextManager___exit____doc__,
+"__exit__($self, /, *exc_info)\n"
+"--\n"
+"\n"
+"Restore the global context.");
+
+#define _DECIMAL_CONTEXTMANAGER___EXIT___METHODDEF \
+ {"__exit__", _PyCFunction_CAST(_decimal_ContextManager___exit__), METH_FASTCALL, _decimal_ContextManager___exit____doc__},
+
+static PyObject *
+_decimal_ContextManager___exit___impl(PyDecContextManagerObject *self,
+ PyObject * const *exc_info,
+ Py_ssize_t exc_info_length);
+
+static PyObject *
+_decimal_ContextManager___exit__(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
+{
+ PyObject *return_value = NULL;
+ PyObject * const *exc_info;
+ Py_ssize_t exc_info_length;
+
+ exc_info = args;
+ exc_info_length = nargs;
+ return_value = _decimal_ContextManager___exit___impl((PyDecContextManagerObject *)self, exc_info, exc_info_length);
+
+ return return_value;
+}
+
PyDoc_STRVAR(_decimal_Decimal_from_float__doc__,
"from_float($type, f, /)\n"
"--\n"
@@ -618,25 +762,12 @@ static PyObject *
_decimal_Decimal_from_float(PyObject *type, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "from_float",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *pyfloat;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("from_float", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("from_float", nargs, 1, 1)) {
goto exit;
}
pyfloat = args[0];
@@ -670,25 +801,12 @@ static PyObject *
_decimal_Decimal_from_number(PyObject *type, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "from_number",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *number;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("from_number", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("from_number", nargs, 1, 1)) {
goto exit;
}
number = args[0];
@@ -719,25 +837,12 @@ static PyObject *
_decimal_Context_create_decimal_from_float(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "create_decimal_from_float",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *f;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("create_decimal_from_float", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("create_decimal_from_float", nargs, 1, 1)) {
goto exit;
}
f = args[0];
@@ -762,7 +867,8 @@ static PyObject *
dec_new_impl(PyTypeObject *type, PyObject *value, PyObject *context);
static PyObject *
-dec_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
+dec_new_helper(PyTypeObject *type, PyObject *const *args,
+ Py_ssize_t nargs, Py_ssize_t nkw, PyObject *kwargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
#if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
@@ -794,12 +900,11 @@ dec_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
#undef KWTUPLE
PyObject *argsbuf[2];
PyObject * const *fastargs;
- Py_ssize_t nargs = PyTuple_GET_SIZE(args);
- Py_ssize_t noptargs = nargs + (kwargs ? PyDict_GET_SIZE(kwargs) : 0) - 0;
+ Py_ssize_t noptargs = nargs + nkw - 0;
PyObject *value = NULL;
PyObject *context = Py_None;
- fastargs = _PyArg_UnpackKeywords(_PyTuple_CAST(args)->ob_item, nargs, kwargs, NULL, &_parser,
+ fastargs = _PyArg_UnpackKeywords(args, nargs, kwargs, kwnames, &_parser,
/*minpos*/ 0, /*maxpos*/ 2, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
if (!fastargs) {
goto exit;
@@ -821,6 +926,47 @@ dec_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
return return_value;
}
+static PyObject *
+dec_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
+{
+ return dec_new_helper(type, _PyTuple_CAST(args)->ob_item,
+ PyTuple_GET_SIZE(args),
+ kwargs ? PyDict_GET_SIZE(kwargs) : 0,
+ kwargs, NULL);
+}
+
+static PyObject *
+dec_vectorcall(PyObject *type, PyObject *const *args,
+ size_t nargsf, PyObject *kwnames)
+{
+ PyObject *return_value = NULL;
+ Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
+ PyObject *value = NULL;
+ PyObject *context = Py_None;
+
+ assert(_PyType_CAST(type)->tp_new == dec_new);
+ /* Make sure the type object is immutable: the generated
+ * vectorcall doesn't deal e.g. with users reassigning __init__. */
+ assert(PyType_HasFeature(_PyType_CAST(type), Py_TPFLAGS_IMMUTABLETYPE));
+ if (kwnames != NULL || nargs > 2) {
+ return dec_new_helper(_PyType_CAST(type), args, nargs,
+ kwnames ? PyTuple_GET_SIZE(kwnames) : 0,
+ NULL, kwnames);
+ }
+ if (nargs < 1) {
+ goto skip_optional;
+ }
+ value = args[0];
+ if (nargs < 2) {
+ goto skip_optional;
+ }
+ context = args[1];
+skip_optional:
+ return_value = dec_new_impl(_PyType_CAST(type), value, context);
+
+ return return_value;
+}
+
PyDoc_STRVAR(_decimal_Context_create_decimal__doc__,
"create_decimal($self, num=\'0\', /)\n"
"--\n"
@@ -873,26 +1019,13 @@ static PyObject *
_decimal_Decimal___format__(PyObject *dec, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", "", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "__format__",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[2];
PyObject *fmtarg;
PyObject *override = NULL;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 2, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("__format__", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("__format__", nargs, 1, 2)) {
goto exit;
}
if (!PyUnicode_Check(args[0])) {
@@ -901,10 +1034,10 @@ _decimal_Decimal___format__(PyObject *dec, PyTypeObject *cls, PyObject *const *a
}
fmtarg = args[0];
if (nargs < 2) {
- goto skip_optional_posonly;
+ goto skip_optional;
}
override = args[1];
-skip_optional_posonly:
+skip_optional:
return_value = _decimal_Decimal___format___impl(dec, cls, fmtarg, override);
exit:
@@ -1180,32 +1313,19 @@ static PyObject *
_decimal_Decimal___round__(PyObject *self, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "__round__",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *ndigits = NULL;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 0, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("__round__", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("__round__", nargs, 0, 1)) {
goto exit;
}
if (nargs < 1) {
- goto skip_optional_posonly;
+ goto skip_optional;
}
ndigits = args[0];
-skip_optional_posonly:
+skip_optional:
return_value = _decimal_Decimal___round___impl(self, cls, ndigits);
exit:
@@ -4012,25 +4132,12 @@ static PyObject *
_decimal_Context_abs(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "abs",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("abs", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("abs", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -4056,25 +4163,12 @@ static PyObject *
_decimal_Context_exp(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "exp",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("exp", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("exp", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -4100,25 +4194,12 @@ static PyObject *
_decimal_Context_ln(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "ln",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("ln", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("ln", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -4145,25 +4226,12 @@ static PyObject *
_decimal_Context_log10(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "log10",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("log10", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("log10", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -4192,25 +4260,12 @@ static PyObject *
_decimal_Context_minus(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "minus",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("minus", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("minus", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -4237,25 +4292,12 @@ static PyObject *
_decimal_Context_next_minus(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "next_minus",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("next_minus", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("next_minus", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -4282,25 +4324,12 @@ static PyObject *
_decimal_Context_next_plus(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "next_plus",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("next_plus", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("next_plus", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -4327,25 +4356,12 @@ static PyObject *
_decimal_Context_normalize(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "normalize",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("normalize", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("normalize", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -4373,25 +4389,12 @@ static PyObject *
_decimal_Context_plus(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "plus",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("plus", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("plus", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -4418,25 +4421,12 @@ static PyObject *
_decimal_Context_to_integral_value(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "to_integral_value",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("to_integral_value", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("to_integral_value", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -4463,25 +4453,12 @@ static PyObject *
_decimal_Context_to_integral_exact(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "to_integral_exact",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("to_integral_exact", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("to_integral_exact", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -4508,25 +4485,12 @@ static PyObject *
_decimal_Context_to_integral(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "to_integral",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("to_integral", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("to_integral", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -4552,25 +4516,12 @@ static PyObject *
_decimal_Context_sqrt(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "sqrt",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("sqrt", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("sqrt", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -4597,26 +4548,13 @@ static PyObject *
_decimal_Context_add(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", "", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "add",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[2];
PyObject *x;
PyObject *y;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 2, /*maxpos*/ 2, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("add", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("add", nargs, 2, 2)) {
goto exit;
}
x = args[0];
@@ -4644,26 +4582,13 @@ static PyObject *
_decimal_Context_compare(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", "", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "compare",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[2];
PyObject *x;
PyObject *y;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 2, /*maxpos*/ 2, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("compare", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("compare", nargs, 2, 2)) {
goto exit;
}
x = args[0];
@@ -4691,26 +4616,13 @@ static PyObject *
_decimal_Context_compare_signal(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", "", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "compare_signal",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[2];
PyObject *x;
PyObject *y;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 2, /*maxpos*/ 2, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("compare_signal", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("compare_signal", nargs, 2, 2)) {
goto exit;
}
x = args[0];
@@ -4738,26 +4650,13 @@ static PyObject *
_decimal_Context_divide(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", "", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "divide",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[2];
PyObject *x;
PyObject *y;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 2, /*maxpos*/ 2, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("divide", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("divide", nargs, 2, 2)) {
goto exit;
}
x = args[0];
@@ -4785,26 +4684,13 @@ static PyObject *
_decimal_Context_divide_int(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", "", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "divide_int",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[2];
PyObject *x;
PyObject *y;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 2, /*maxpos*/ 2, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("divide_int", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("divide_int", nargs, 2, 2)) {
goto exit;
}
x = args[0];
@@ -4832,26 +4718,13 @@ static PyObject *
_decimal_Context_max(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", "", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "max",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[2];
PyObject *x;
PyObject *y;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 2, /*maxpos*/ 2, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("max", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("max", nargs, 2, 2)) {
goto exit;
}
x = args[0];
@@ -4879,26 +4752,13 @@ static PyObject *
_decimal_Context_max_mag(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", "", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "max_mag",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[2];
PyObject *x;
PyObject *y;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 2, /*maxpos*/ 2, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("max_mag", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("max_mag", nargs, 2, 2)) {
goto exit;
}
x = args[0];
@@ -4926,26 +4786,13 @@ static PyObject *
_decimal_Context_min(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", "", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "min",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[2];
PyObject *x;
PyObject *y;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 2, /*maxpos*/ 2, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("min", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("min", nargs, 2, 2)) {
goto exit;
}
x = args[0];
@@ -4973,26 +4820,13 @@ static PyObject *
_decimal_Context_min_mag(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", "", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "min_mag",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[2];
PyObject *x;
PyObject *y;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 2, /*maxpos*/ 2, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("min_mag", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("min_mag", nargs, 2, 2)) {
goto exit;
}
x = args[0];
@@ -5020,26 +4854,13 @@ static PyObject *
_decimal_Context_multiply(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", "", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "multiply",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[2];
PyObject *x;
PyObject *y;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 2, /*maxpos*/ 2, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("multiply", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("multiply", nargs, 2, 2)) {
goto exit;
}
x = args[0];
@@ -5067,26 +4888,13 @@ static PyObject *
_decimal_Context_next_toward(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", "", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "next_toward",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[2];
PyObject *x;
PyObject *y;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 2, /*maxpos*/ 2, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("next_toward", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("next_toward", nargs, 2, 2)) {
goto exit;
}
x = args[0];
@@ -5114,26 +4922,13 @@ static PyObject *
_decimal_Context_quantize(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", "", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "quantize",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[2];
PyObject *x;
PyObject *y;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 2, /*maxpos*/ 2, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("quantize", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("quantize", nargs, 2, 2)) {
goto exit;
}
x = args[0];
@@ -5164,26 +4959,13 @@ static PyObject *
_decimal_Context_remainder(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", "", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "remainder",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[2];
PyObject *x;
PyObject *y;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 2, /*maxpos*/ 2, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("remainder", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("remainder", nargs, 2, 2)) {
goto exit;
}
x = args[0];
@@ -5214,26 +4996,13 @@ static PyObject *
_decimal_Context_remainder_near(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", "", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "remainder_near",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[2];
PyObject *x;
PyObject *y;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 2, /*maxpos*/ 2, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("remainder_near", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("remainder_near", nargs, 2, 2)) {
goto exit;
}
x = args[0];
@@ -5261,26 +5030,13 @@ static PyObject *
_decimal_Context_subtract(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", "", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "subtract",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[2];
PyObject *x;
PyObject *y;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 2, /*maxpos*/ 2, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("subtract", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("subtract", nargs, 2, 2)) {
goto exit;
}
x = args[0];
@@ -5328,7 +5084,7 @@ PyDoc_STRVAR(_decimal_Context_power__doc__,
"Compute a**b.\n"
"\n"
"If \'a\' is negative, then \'b\' must be integral. The result will be\n"
-"inexact unless \'a\' is integral and the result is finite and can be\n"
+"inexact unless \'b\' is integral and the result is finite and can be\n"
"expressed exactly in \'precision\' digits. In the Python version the\n"
"result is always correctly rounded, in the C version the result is\n"
"almost always correctly rounded.\n"
@@ -5421,27 +5177,14 @@ static PyObject *
_decimal_Context_fma(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", "", "", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "fma",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[3];
PyObject *x;
PyObject *y;
PyObject *z;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 3, /*maxpos*/ 3, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("fma", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("fma", nargs, 3, 3)) {
goto exit;
}
x = args[0];
@@ -5492,25 +5235,12 @@ static PyObject *
_decimal_Context_is_normal(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "is_normal",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("is_normal", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("is_normal", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -5537,25 +5267,12 @@ static PyObject *
_decimal_Context_is_subnormal(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "is_subnormal",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("is_subnormal", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("is_subnormal", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -5582,25 +5299,12 @@ static PyObject *
_decimal_Context_is_finite(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "is_finite",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("is_finite", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("is_finite", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -5627,25 +5331,12 @@ static PyObject *
_decimal_Context_is_infinite(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "is_infinite",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("is_infinite", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("is_infinite", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -5672,25 +5363,12 @@ static PyObject *
_decimal_Context_is_nan(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "is_nan",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("is_nan", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("is_nan", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -5717,25 +5395,12 @@ static PyObject *
_decimal_Context_is_qnan(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "is_qnan",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("is_qnan", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("is_qnan", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -5762,25 +5427,12 @@ static PyObject *
_decimal_Context_is_snan(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "is_snan",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("is_snan", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("is_snan", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -5807,25 +5459,12 @@ static PyObject *
_decimal_Context_is_signed(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "is_signed",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("is_signed", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("is_signed", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -5852,25 +5491,12 @@ static PyObject *
_decimal_Context_is_zero(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "is_zero",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("is_zero", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("is_zero", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -5897,25 +5523,12 @@ static PyObject *
_decimal_Context_is_canonical(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "is_canonical",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("is_canonical", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("is_canonical", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -5942,25 +5555,12 @@ static PyObject *
_decimal_Context__apply(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "_apply",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("_apply", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("_apply", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -5989,25 +5589,12 @@ static PyObject *
_decimal_Context_apply(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "apply",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("apply", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("apply", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -6023,7 +5610,13 @@ PyDoc_STRVAR(_decimal_Context_canonical__doc__,
"canonical($self, x, /)\n"
"--\n"
"\n"
-"Return a new instance of x.");
+"Returns the same Decimal object.\n"
+"\n"
+"As we do not have different encodings for the same number, the\n"
+"received object already is in its canonical form.\n"
+"\n"
+">>> ExtendedContext.canonical(Decimal(\'2.50\'))\n"
+"Decimal(\'2.50\')");
#define _DECIMAL_CONTEXT_CANONICAL_METHODDEF \
{"canonical", _PyCFunction_CAST(_decimal_Context_canonical), METH_METHOD|METH_FASTCALL|METH_KEYWORDS, _decimal_Context_canonical__doc__},
@@ -6032,29 +5625,16 @@ static PyObject *
_decimal_Context_canonical_impl(PyObject *context, PyTypeObject *cls,
PyObject *x);
-static PyObject *
-_decimal_Context_canonical(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
-{
- PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "canonical",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
+static PyObject *
+_decimal_Context_canonical(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
+{
+ PyObject *return_value = NULL;
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("canonical", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("canonical", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -6081,25 +5661,12 @@ static PyObject *
_decimal_Context_copy_abs(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "copy_abs",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("copy_abs", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("copy_abs", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -6126,25 +5693,12 @@ static PyObject *
_decimal_Context_copy_decimal(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "copy_decimal",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("copy_decimal", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("copy_decimal", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -6171,25 +5725,12 @@ static PyObject *
_decimal_Context_copy_negate(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "copy_negate",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("copy_negate", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("copy_negate", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -6215,25 +5756,12 @@ static PyObject *
_decimal_Context_logb(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "logb",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("logb", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("logb", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -6273,25 +5801,12 @@ static PyObject *
_decimal_Context_logical_invert(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "logical_invert",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("logical_invert", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("logical_invert", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -6318,25 +5833,12 @@ static PyObject *
_decimal_Context_number_class(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "number_class",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("number_class", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("number_class", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -6363,25 +5865,12 @@ static PyObject *
_decimal_Context_to_sci_string(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "to_sci_string",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("to_sci_string", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("to_sci_string", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -6408,25 +5897,12 @@ static PyObject *
_decimal_Context_to_eng_string(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "to_eng_string",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *x;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("to_eng_string", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("to_eng_string", nargs, 1, 1)) {
goto exit;
}
x = args[0];
@@ -6453,26 +5929,13 @@ static PyObject *
_decimal_Context_compare_total(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", "", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "compare_total",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[2];
PyObject *x;
PyObject *y;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 2, /*maxpos*/ 2, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("compare_total", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("compare_total", nargs, 2, 2)) {
goto exit;
}
x = args[0];
@@ -6500,26 +5963,13 @@ static PyObject *
_decimal_Context_compare_total_mag(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", "", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "compare_total_mag",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[2];
PyObject *x;
PyObject *y;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 2, /*maxpos*/ 2, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("compare_total_mag", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("compare_total_mag", nargs, 2, 2)) {
goto exit;
}
x = args[0];
@@ -6547,26 +5997,13 @@ static PyObject *
_decimal_Context_copy_sign(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", "", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "copy_sign",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[2];
PyObject *x;
PyObject *y;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 2, /*maxpos*/ 2, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("copy_sign", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("copy_sign", nargs, 2, 2)) {
goto exit;
}
x = args[0];
@@ -6615,26 +6052,13 @@ static PyObject *
_decimal_Context_logical_and(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", "", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "logical_and",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[2];
PyObject *x;
PyObject *y;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 2, /*maxpos*/ 2, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("logical_and", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("logical_and", nargs, 2, 2)) {
goto exit;
}
x = args[0];
@@ -6683,26 +6107,13 @@ static PyObject *
_decimal_Context_logical_or(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", "", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "logical_or",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[2];
PyObject *x;
PyObject *y;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 2, /*maxpos*/ 2, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("logical_or", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("logical_or", nargs, 2, 2)) {
goto exit;
}
x = args[0];
@@ -6751,26 +6162,13 @@ static PyObject *
_decimal_Context_logical_xor(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", "", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "logical_xor",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[2];
PyObject *x;
PyObject *y;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 2, /*maxpos*/ 2, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("logical_xor", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("logical_xor", nargs, 2, 2)) {
goto exit;
}
x = args[0];
@@ -6798,26 +6196,13 @@ static PyObject *
_decimal_Context_rotate(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", "", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "rotate",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[2];
PyObject *x;
PyObject *y;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 2, /*maxpos*/ 2, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("rotate", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("rotate", nargs, 2, 2)) {
goto exit;
}
x = args[0];
@@ -6845,26 +6230,13 @@ static PyObject *
_decimal_Context_scaleb(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", "", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "scaleb",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[2];
PyObject *x;
PyObject *y;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 2, /*maxpos*/ 2, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("scaleb", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("scaleb", nargs, 2, 2)) {
goto exit;
}
x = args[0];
@@ -6892,26 +6264,13 @@ static PyObject *
_decimal_Context_shift(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", "", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "shift",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[2];
PyObject *x;
PyObject *y;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 2, /*maxpos*/ 2, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("shift", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("shift", nargs, 2, 2)) {
goto exit;
}
x = args[0];
@@ -6939,26 +6298,13 @@ static PyObject *
_decimal_Context_same_quantum(PyObject *context, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", "", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "same_quantum",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[2];
PyObject *x;
PyObject *y;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 2, /*maxpos*/ 2, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("same_quantum", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("same_quantum", nargs, 2, 2)) {
goto exit;
}
x = args[0];
@@ -6984,4 +6330,4 @@ _decimal_Context_same_quantum(PyObject *context, PyTypeObject *cls, PyObject *co
#ifndef _DECIMAL_CONTEXT_APPLY_METHODDEF
#define _DECIMAL_CONTEXT_APPLY_METHODDEF
#endif /* !defined(_DECIMAL_CONTEXT_APPLY_METHODDEF) */
-/*[clinic end generated code: output=0eb835634388294e input=a9049054013a1b77]*/
+/*[clinic end generated code: output=f9ddc00f5a7335c4 input=a9049054013a1b77]*/
diff --git a/Modules/_decimal/tests/README.txt b/Modules/_decimal/tests/README.txt
index 97b6ff68a56fb7a..9ea9ef8c802ac2f 100644
--- a/Modules/_decimal/tests/README.txt
+++ b/Modules/_decimal/tests/README.txt
@@ -1,9 +1,4 @@
-
-
-This directory contains extended tests and a benchmark against decimal.py:
-
- bench.py -> Benchmark for small and large precisions.
- Usage: ../../../python bench.py
+This directory contains extended tests against decimal.py:
formathelper.py ->
randdec.py -> Generate test cases for deccheck.py.
@@ -11,5 +6,3 @@ This directory contains extended tests and a benchmark against decimal.py:
deccheck.py -> Run extended tests.
Usage: ../../../python deccheck.py [--short|--medium|--long|--all]
-
-
diff --git a/Modules/_decimal/tests/bench.py b/Modules/_decimal/tests/bench.py
deleted file mode 100644
index 6605e9a92e2dde4..000000000000000
--- a/Modules/_decimal/tests/bench.py
+++ /dev/null
@@ -1,150 +0,0 @@
-#
-# Copyright (C) 2001 Python Software Foundation. All Rights Reserved.
-# Modified and extended by Stefan Krah.
-#
-
-# Usage: ../../../python bench.py
-
-
-import time
-import sys
-from functools import wraps
-from test.support.import_helper import import_fresh_module
-
-C = import_fresh_module('decimal', fresh=['_decimal'])
-P = import_fresh_module('decimal', blocked=['_decimal'])
-
-#
-# NOTE: This is the pi function from the decimal documentation, modified
-# for benchmarking purposes. Since floats do not have a context, the higher
-# intermediate precision from the original is NOT used, so the modified
-# algorithm only gives an approximation to the correctly rounded result.
-# For serious use, refer to the documentation or the appropriate literature.
-#
-def pi_float():
- """native float"""
- lasts, t, s, n, na, d, da = 0, 3.0, 3, 1, 0, 0, 24
- while s != lasts:
- lasts = s
- n, na = n+na, na+8
- d, da = d+da, da+32
- t = (t * n) / d
- s += t
- return s
-
-def pi_cdecimal():
- """cdecimal"""
- D = C.Decimal
- lasts, t, s, n, na, d, da = D(0), D(3), D(3), D(1), D(0), D(0), D(24)
- while s != lasts:
- lasts = s
- n, na = n+na, na+8
- d, da = d+da, da+32
- t = (t * n) / d
- s += t
- return s
-
-def pi_decimal():
- """decimal"""
- D = P.Decimal
- lasts, t, s, n, na, d, da = D(0), D(3), D(3), D(1), D(0), D(0), D(24)
- while s != lasts:
- lasts = s
- n, na = n+na, na+8
- d, da = d+da, da+32
- t = (t * n) / d
- s += t
- return s
-
-def factorial(n, m):
- if (n > m):
- return factorial(m, n)
- elif m == 0:
- return 1
- elif n == m:
- return n
- else:
- return factorial(n, (n+m)//2) * factorial((n+m)//2 + 1, m)
-
-# Fix failed test cases caused by CVE-2020-10735 patch.
-# See gh-95778 for details.
-def increase_int_max_str_digits(maxdigits):
- def _increase_int_max_str_digits(func, maxdigits=maxdigits):
- @wraps(func)
- def wrapper(*args, **kwargs):
- previous_int_limit = sys.get_int_max_str_digits()
- sys.set_int_max_str_digits(maxdigits)
- ans = func(*args, **kwargs)
- sys.set_int_max_str_digits(previous_int_limit)
- return ans
- return wrapper
- return _increase_int_max_str_digits
-
-def test_calc_pi():
- print("\n# ======================================================================")
- print("# Calculating pi, 10000 iterations")
- print("# ======================================================================\n")
-
- to_benchmark = [pi_float, pi_decimal]
- if C is not None:
- to_benchmark.insert(1, pi_cdecimal)
-
- for prec in [9, 19]:
- print("\nPrecision: %d decimal digits\n" % prec)
- for func in to_benchmark:
- start = time.time()
- if C is not None:
- C.getcontext().prec = prec
- P.getcontext().prec = prec
- for i in range(10000):
- x = func()
- print("%s:" % func.__name__.replace("pi_", ""))
- print("result: %s" % str(x))
- print("time: %fs\n" % (time.time()-start))
-
-@increase_int_max_str_digits(maxdigits=10000000)
-def test_factorial():
- print("\n# ======================================================================")
- print("# Factorial")
- print("# ======================================================================\n")
-
- if C is not None:
- c = C.getcontext()
- c.prec = C.MAX_PREC
- c.Emax = C.MAX_EMAX
- c.Emin = C.MIN_EMIN
-
- for n in [100000, 1000000]:
-
- print("n = %d\n" % n)
-
- if C is not None:
- # C version of decimal
- start_calc = time.time()
- x = factorial(C.Decimal(n), 0)
- end_calc = time.time()
- start_conv = time.time()
- sx = str(x)
- end_conv = time.time()
- print("cdecimal:")
- print("calculation time: %fs" % (end_calc-start_calc))
- print("conversion time: %fs\n" % (end_conv-start_conv))
-
- # Python integers
- start_calc = time.time()
- y = factorial(n, 0)
- end_calc = time.time()
- start_conv = time.time()
- sy = str(y)
- end_conv = time.time()
-
- print("int:")
- print("calculation time: %fs" % (end_calc-start_calc))
- print("conversion time: %fs\n\n" % (end_conv-start_conv))
-
- if C is not None:
- assert(sx == sy)
-
-if __name__ == "__main__":
- test_calc_pi()
- test_factorial()
diff --git a/Modules/_elementtree.c b/Modules/_elementtree.c
index f827274eeffba83..2195010261678f7 100644
--- a/Modules/_elementtree.c
+++ b/Modules/_elementtree.c
@@ -612,33 +612,41 @@ element_get_tail(ElementObject* self)
return Py_NewRef(res);
}
-static PyObject*
-subelement(PyObject *self, PyObject *args, PyObject *kwds)
+/*[clinic input]
+_elementtree.SubElement
+
+ parent: object(subclass_of='get_elementtree_state(module)->Element_Type')
+ tag: object
+ attrib: object(subclass_of='&PyDict_Type', c_default='NULL') = {}
+ /
+ **extra: dict
+
+Create a new subelement of the parent element.
+[clinic start generated code]*/
+
+static PyObject *
+_elementtree_SubElement_impl(PyObject *module, PyObject *parent,
+ PyObject *tag, PyObject *attrib,
+ PyObject *extra)
+/*[clinic end generated code: output=42e8a4ebc5db08aa input=8588fc68283cdaa0]*/
{
PyObject* elem;
- elementtreestate *st = get_elementtree_state(self);
- ElementObject* parent;
- PyObject* tag;
- PyObject* attrib = NULL;
- if (!PyArg_ParseTuple(args, "O!O|O!:SubElement",
- st->Element_Type, &parent, &tag,
- &PyDict_Type, &attrib)) {
- return NULL;
- }
+ elementtreestate *st = get_elementtree_state(module);
+ ElementObject* parent_elem = (ElementObject *)parent;
if (attrib) {
/* attrib passed as positional arg */
attrib = PyDict_Copy(attrib);
if (!attrib)
return NULL;
- if (kwds != NULL && PyDict_Update(attrib, kwds) < 0) {
+ if (extra && PyDict_Update(attrib, extra) < 0) {
Py_DECREF(attrib);
return NULL;
}
- } else if (kwds) {
+ } else if (extra && PyDict_GET_SIZE(extra)) {
/* have keyword args */
- attrib = get_attrib_from_keywords(kwds);
+ attrib = get_attrib_from_keywords(extra);
if (!attrib)
return NULL;
} else {
@@ -650,7 +658,7 @@ subelement(PyObject *self, PyObject *args, PyObject *kwds)
if (elem == NULL)
return NULL;
- if (element_add_subelement(st, parent, elem) < 0) {
+ if (element_add_subelement(st, parent_elem, elem) < 0) {
Py_DECREF(elem);
return NULL;
}
@@ -720,12 +728,17 @@ _elementtree.Element.append
subelement: object(subclass_of='clinic_state()->Element_Type')
/
+Add *subelement* to the end of this element.
+
+The new element will appear in document order after the last
+existing subelement (or directly after the text, if it's the first
+subelement), but before the end tag for this element.
[clinic start generated code]*/
static PyObject *
_elementtree_Element_append_impl(ElementObject *self, PyTypeObject *cls,
PyObject *subelement)
-/*[clinic end generated code: output=d00923711ea317fc input=8baf92679f9717b8]*/
+/*[clinic end generated code: output=d00923711ea317fc input=a59ebce98937a372]*/
{
elementtreestate *st = get_elementtree_state_by_cls(cls);
if (element_add_subelement(st, self, subelement) < 0)
@@ -737,11 +750,15 @@ _elementtree_Element_append_impl(ElementObject *self, PyTypeObject *cls,
/*[clinic input]
_elementtree.Element.clear
+Reset element.
+
+This function removes all subelements, clears all attributes, and
+sets the text and tail attributes to None.
[clinic start generated code]*/
static PyObject *
_elementtree_Element_clear_impl(ElementObject *self)
-/*[clinic end generated code: output=8bcd7a51f94cfff6 input=3c719ff94bf45dd6]*/
+/*[clinic end generated code: output=8bcd7a51f94cfff6 input=135c2ab634d0fdf5]*/
{
clear_extra(self);
@@ -1221,24 +1238,6 @@ checkpath(PyObject* tag)
}
return 0;
}
- if (PyBytes_Check(tag)) {
- const char *p = PyBytes_AS_STRING(tag);
- const Py_ssize_t len = PyBytes_GET_SIZE(tag);
- if (len >= 3 && p[0] == '{' && (
- p[1] == '}' || (p[1] == '*' && p[2] == '}'))) {
- /* wildcard: '{}tag' or '{*}tag' */
- return 1;
- }
- for (i = 0; i < len; i++) {
- if (p[i] == '{')
- check = 0;
- else if (p[i] == '}')
- check = 1;
- else if (check && PATHCHAR(p[i]))
- return 1;
- }
- return 0;
- }
return 1; /* unknown type; might be path expression */
}
@@ -1250,12 +1249,15 @@ _elementtree.Element.extend
elements: object
/
+Append subelements from a sequence.
+
+*elements* is a sequence with zero or more elements.
[clinic start generated code]*/
static PyObject *
_elementtree_Element_extend_impl(ElementObject *self, PyTypeObject *cls,
PyObject *elements)
-/*[clinic end generated code: output=3e86d37fac542216 input=6479b1b5379d09ae]*/
+/*[clinic end generated code: output=3e86d37fac542216 input=401ac1d07e13282b]*/
{
PyObject* seq;
Py_ssize_t i;
@@ -1289,12 +1291,19 @@ _elementtree.Element.find
path: object
namespaces: object = None
+Find first matching element by tag name or path.
+
+*path* is a string having either an element tag or an XPath,
+*namespaces* is an optional mapping from namespace prefix to full
+name.
+
+Return the first matching element, or None if no element was found.
[clinic start generated code]*/
static PyObject *
_elementtree_Element_find_impl(ElementObject *self, PyTypeObject *cls,
PyObject *path, PyObject *namespaces)
-/*[clinic end generated code: output=18f77d393c9fef1b input=94df8a83f956acc6]*/
+/*[clinic end generated code: output=18f77d393c9fef1b input=3aec422879a342e1]*/
{
elementtreestate *st = get_elementtree_state_by_cls(cls);
@@ -1332,13 +1341,23 @@ _elementtree.Element.findtext
default: object = None
namespaces: object = None
+Find text for first matching element by tag name or path.
+
+*path* is a string having either an element tag or an XPath,
+*default* is the value to return if the element was not found,
+*namespaces* is an optional mapping from namespace prefix to full
+name.
+
+Return text content of first matching element, or default value if
+none was found. Note that if an element is found having no text
+content, the empty string is returned.
[clinic start generated code]*/
static PyObject *
_elementtree_Element_findtext_impl(ElementObject *self, PyTypeObject *cls,
PyObject *path, PyObject *default_value,
PyObject *namespaces)
-/*[clinic end generated code: output=6af7a2d96aac32cb input=32f252099f62a3d2]*/
+/*[clinic end generated code: output=6af7a2d96aac32cb input=64610701f762c4f5]*/
{
elementtreestate *st = get_elementtree_state_by_cls(cls);
@@ -1381,12 +1400,19 @@ _elementtree.Element.findall
path: object
namespaces: object = None
+Find all matching subelements by tag name or path.
+
+*path* is a string having either an element tag or an XPath,
+*namespaces* is an optional mapping from namespace prefix to full
+name.
+
+Returns list containing all matching elements in document order.
[clinic start generated code]*/
static PyObject *
_elementtree_Element_findall_impl(ElementObject *self, PyTypeObject *cls,
PyObject *path, PyObject *namespaces)
-/*[clinic end generated code: output=65e39a1208f3b59e input=7aa0db45673fc9a5]*/
+/*[clinic end generated code: output=65e39a1208f3b59e input=2208ddeb5f1cc7c3]*/
{
elementtreestate *st = get_elementtree_state_by_cls(cls);
@@ -1427,12 +1453,19 @@ _elementtree.Element.iterfind
path: object
namespaces: object = None
+Find all matching subelements by tag name or path.
+
+*path* is a string having either an element tag or an XPath,
+*namespaces* is an optional mapping from namespace prefix to full
+name.
+
+Return an iterable yielding all matching elements in document order.
[clinic start generated code]*/
static PyObject *
_elementtree_Element_iterfind_impl(ElementObject *self, PyTypeObject *cls,
PyObject *path, PyObject *namespaces)
-/*[clinic end generated code: output=be5c3f697a14e676 input=88766875a5c9a88b]*/
+/*[clinic end generated code: output=be5c3f697a14e676 input=00bea06334260582]*/
{
PyObject* tag = path;
elementtreestate *st = get_elementtree_state_by_cls(cls);
@@ -1447,20 +1480,30 @@ _elementtree.Element.get
key: object
default: object = None
+Get element attribute.
+
+Equivalent to attrib.get, but some implementations may handle this a
+bit more efficiently. *key* is what attribute to look for, and
+*default* is what to return if the attribute was not found.
+
+Returns a string containing the attribute value, or the default if
+attribute was not found.
[clinic start generated code]*/
static PyObject *
_elementtree_Element_get_impl(ElementObject *self, PyObject *key,
PyObject *default_value)
-/*[clinic end generated code: output=523c614142595d75 input=ee153bbf8cdb246e]*/
+/*[clinic end generated code: output=523c614142595d75 input=332624526ef81a70]*/
{
if (self->extra && self->extra->attrib) {
PyObject *attrib = Py_NewRef(self->extra->attrib);
- PyObject *value = Py_XNewRef(PyDict_GetItemWithError(attrib, key));
- Py_DECREF(attrib);
- if (value != NULL || PyErr_Occurred()) {
+ PyObject *value;
+ if (PyDict_GetItemRef(attrib, key, &value) != 0) {
+ Py_DECREF(attrib);
+ // The key exists or an error occurred
return value;
}
+ Py_DECREF(attrib);
}
return Py_NewRef(default_value);
@@ -1478,21 +1521,29 @@ _elementtree.Element.iter
/
tag: object = None
+Create tree iterator.
+
+The iterator loops over the element and all subelements in document
+order, returning all elements with a matching tag.
+
+If the tree structure is modified during iteration, new or removed
+elements may or may not be included. To get a stable set, use the
+list() function on the iterator, and loop over the resulting list.
+
+*tag* is what tags to look for (default is to return all elements)
+
+Return an iterator containing all the matching elements.
[clinic start generated code]*/
static PyObject *
_elementtree_Element_iter_impl(ElementObject *self, PyTypeObject *cls,
PyObject *tag)
-/*[clinic end generated code: output=bff29dc5d4566c68 input=f6944c48d3f84c58]*/
+/*[clinic end generated code: output=bff29dc5d4566c68 input=e4c542a12e6f9199]*/
{
if (PyUnicode_Check(tag)) {
if (PyUnicode_GET_LENGTH(tag) == 1 && PyUnicode_READ_CHAR(tag, 0) == '*')
tag = Py_None;
}
- else if (PyBytes_Check(tag)) {
- if (PyBytes_GET_SIZE(tag) == 1 && *PyBytes_AS_STRING(tag) == '*')
- tag = Py_None;
- }
elementtreestate *st = get_elementtree_state_by_cls(cls);
return create_elementiter(st, self, tag, 0);
@@ -1505,11 +1556,15 @@ _elementtree.Element.itertext
cls: defining_class
/
+Create text iterator.
+
+The iterator loops over the element and all subelements in document
+order, returning all inner text.
[clinic start generated code]*/
static PyObject *
_elementtree_Element_itertext_impl(ElementObject *self, PyTypeObject *cls)
-/*[clinic end generated code: output=fdeb2a3bca0ae063 input=a1ef1f0fc872a586]*/
+/*[clinic end generated code: output=fdeb2a3bca0ae063 input=eaffe70224da7f02]*/
{
elementtreestate *st = get_elementtree_state_by_cls(cls);
return create_elementiter(st, self, Py_None, 1);
@@ -1556,12 +1611,13 @@ _elementtree.Element.insert
subelement: object(subclass_of='clinic_state()->Element_Type')
/
+Insert *subelement* at position *index*.
[clinic start generated code]*/
static PyObject *
_elementtree_Element_insert_impl(ElementObject *self, Py_ssize_t index,
PyObject *subelement)
-/*[clinic end generated code: output=990adfef4d424c0b input=9530f4905aa401ca]*/
+/*[clinic end generated code: output=990adfef4d424c0b input=2886a2266de15ed7]*/
{
Py_ssize_t i;
@@ -1594,11 +1650,14 @@ _elementtree_Element_insert_impl(ElementObject *self, Py_ssize_t index,
/*[clinic input]
_elementtree.Element.items
+Get element attributes as (name, value) pairs.
+
+Equivalent to attrib.items().
[clinic start generated code]*/
static PyObject *
_elementtree_Element_items_impl(ElementObject *self)
-/*[clinic end generated code: output=6db2c778ce3f5a4d input=adbe09aaea474447]*/
+/*[clinic end generated code: output=6db2c778ce3f5a4d input=7b5adcd8f774d4e0]*/
{
if (!self->extra || !self->extra->attrib)
return PyList_New(0);
@@ -1609,11 +1668,14 @@ _elementtree_Element_items_impl(ElementObject *self)
/*[clinic input]
_elementtree.Element.keys
+Get attribute names.
+
+Equivalent to attrib.keys()
[clinic start generated code]*/
static PyObject *
_elementtree_Element_keys_impl(ElementObject *self)
-/*[clinic end generated code: output=bc5bfabbf20eeb3c input=f02caf5b496b5b0b]*/
+/*[clinic end generated code: output=bc5bfabbf20eeb3c input=6d860fbdb565115d]*/
{
if (!self->extra || !self->extra->attrib)
return PyList_New(0);
@@ -1639,12 +1701,19 @@ _elementtree.Element.makeelement
attrib: object(subclass_of='&PyDict_Type')
/
+Create a new element with the same type.
+
+*tag* is a string containing the element name. *attrib* is a
+dictionary containing the element attributes.
+
+Do not call this method, use the SubElement factory function
+instead.
[clinic start generated code]*/
static PyObject *
_elementtree_Element_makeelement_impl(ElementObject *self, PyTypeObject *cls,
PyObject *tag, PyObject *attrib)
-/*[clinic end generated code: output=d50bb17a47077d47 input=589829dab92f26e8]*/
+/*[clinic end generated code: output=d50bb17a47077d47 input=02b62a503fa25ae7]*/
{
PyObject* elem;
@@ -1666,11 +1735,20 @@ _elementtree.Element.remove
subelement: object(subclass_of='clinic_state()->Element_Type')
/
+Remove matching subelement.
+
+Unlike the find methods, this method compares elements based on
+identity, NOT ON tag value or contents. To remove subelements by
+other means, the easiest way is to use a list comprehension to
+select what elements to keep, and then use slice assignment to
+update the parent element.
+
+ValueError is raised if a matching element could not be found.
[clinic start generated code]*/
static PyObject *
_elementtree_Element_remove_impl(ElementObject *self, PyObject *subelement)
-/*[clinic end generated code: output=38fe6c07d6d87d1f input=6133e1d05597d5ee]*/
+/*[clinic end generated code: output=38fe6c07d6d87d1f input=e035af9d920f785b]*/
{
Py_ssize_t i;
// When iterating over the list of children, we need to check that the
@@ -1748,12 +1826,17 @@ _elementtree.Element.set
value: object
/
+Set element attribute.
+
+Equivalent to attrib[key] = value, but some implementations may
+handle this a bit more efficiently. *key* is what attribute to set,
+and *value* is the attribute value to set it to.
[clinic start generated code]*/
static PyObject *
_elementtree_Element_set_impl(ElementObject *self, PyObject *key,
PyObject *value)
-/*[clinic end generated code: output=fb938806be3c5656 input=1efe90f7d82b3fe9]*/
+/*[clinic end generated code: output=fb938806be3c5656 input=bbaadd68b86636d7]*/
{
PyObject* attrib;
@@ -2308,7 +2391,9 @@ elementiter_next(PyObject *op)
if (it->sought_tag == Py_None)
return (PyObject *)elem;
- rc = PyObject_RichCompareBool(elem->tag, it->sought_tag, Py_EQ);
+ PyObject *tag = Py_NewRef(elem->tag);
+ rc = PyObject_RichCompareBool(tag, it->sought_tag, Py_EQ);
+ Py_DECREF(tag);
if (rc > 0)
return (PyObject *)elem;
@@ -2409,14 +2494,6 @@ typedef struct {
PyObject *pi_factory;
/* element tracing */
- PyObject *events_append; /* the append method of the list of events, or NULL */
- PyObject *start_event_obj; /* event objects (NULL to ignore) */
- PyObject *end_event_obj;
- PyObject *start_ns_event_obj;
- PyObject *end_ns_event_obj;
- PyObject *comment_event_obj;
- PyObject *pi_event_obj;
-
char insert_comments;
char insert_pis;
elementtreestate *state;
@@ -2450,10 +2527,6 @@ treebuilder_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
}
t->index = 0;
- t->events_append = NULL;
- t->start_event_obj = t->end_event_obj = NULL;
- t->start_ns_event_obj = t->end_ns_event_obj = NULL;
- t->comment_event_obj = t->pi_event_obj = NULL;
t->insert_comments = t->insert_pis = 0;
t->state = get_elementtree_state_by_type(type);
}
@@ -2470,6 +2543,24 @@ _elementtree.TreeBuilder.__init__
insert_comments: bool = False
insert_pis: bool = False
+Generic element structure builder.
+
+This builder converts a sequence of start, data, and end method
+calls to a well-formed element structure.
+
+You can use this class to build an element structure using a custom
+XML parser, or a parser for some other XML-like format.
+
+*element_factory* is an optional element factory which is called
+to create new Element instances, as necessary.
+
+*comment_factory* is a factory to create comments to be used instead
+of the standard factory. If *insert_comments* is false (the
+default), comments will not be inserted into the tree.
+
+*pi_factory* is a factory to create processing instructions to be
+used instead of the standard factory. If *insert_pis* is false (the
+default), processing instructions will not be inserted into the tree.
[clinic start generated code]*/
static int
@@ -2478,7 +2569,7 @@ _elementtree_TreeBuilder___init___impl(TreeBuilderObject *self,
PyObject *comment_factory,
PyObject *pi_factory,
int insert_comments, int insert_pis)
-/*[clinic end generated code: output=8571d4dcadfdf952 input=ae98a94df20b5cc3]*/
+/*[clinic end generated code: output=8571d4dcadfdf952 input=24fb5a482d93f8e4]*/
{
if (element_factory != Py_None) {
Py_XSETREF(self->element_factory, Py_NewRef(element_factory));
@@ -2518,13 +2609,6 @@ treebuilder_gc_traverse(PyObject *op, visitproc visit, void *arg)
{
TreeBuilderObject *self = _TreeBuilder_CAST(op);
Py_VISIT(Py_TYPE(self));
- Py_VISIT(self->pi_event_obj);
- Py_VISIT(self->comment_event_obj);
- Py_VISIT(self->end_ns_event_obj);
- Py_VISIT(self->start_ns_event_obj);
- Py_VISIT(self->end_event_obj);
- Py_VISIT(self->start_event_obj);
- Py_VISIT(self->events_append);
Py_VISIT(self->root);
Py_VISIT(self->this);
Py_VISIT(self->last);
@@ -2541,13 +2625,6 @@ static int
treebuilder_gc_clear(PyObject *op)
{
TreeBuilderObject *self = _TreeBuilder_CAST(op);
- Py_CLEAR(self->pi_event_obj);
- Py_CLEAR(self->comment_event_obj);
- Py_CLEAR(self->end_ns_event_obj);
- Py_CLEAR(self->start_ns_event_obj);
- Py_CLEAR(self->end_event_obj);
- Py_CLEAR(self->start_event_obj);
- Py_CLEAR(self->events_append);
Py_CLEAR(self->stack);
Py_CLEAR(self->data);
Py_CLEAR(self->last);
@@ -2717,24 +2794,6 @@ treebuilder_add_subelement(elementtreestate *st, PyObject *element,
}
}
-LOCAL(int)
-treebuilder_append_event(TreeBuilderObject *self, PyObject *action,
- PyObject *node)
-{
- if (action != NULL) {
- PyObject *res;
- PyObject *event = _PyTuple_FromPair(action, node);
- if (event == NULL)
- return -1;
- res = PyObject_CallOneArg(self->events_append, event);
- Py_DECREF(event);
- if (res == NULL)
- return -1;
- Py_DECREF(res);
- }
- return 0;
-}
-
/* -------------------------------------------------------------------- */
/* handlers */
@@ -2800,9 +2859,6 @@ treebuilder_handle_start(TreeBuilderObject* self, PyObject* tag,
Py_SETREF(self->this, Py_NewRef(node));
Py_SETREF(self->last, Py_NewRef(node));
- if (treebuilder_append_event(self, self->start_event_obj, node) < 0)
- goto error;
-
return node;
error:
@@ -2822,17 +2878,7 @@ treebuilder_handle_data(TreeBuilderObject* self, PyObject* data)
self->data = Py_NewRef(data);
} else {
/* more than one item; use a list to collect items */
- if (PyBytes_CheckExact(self->data)
- && _PyObject_IsUniquelyReferenced(self->data)
- && PyBytes_CheckExact(data) && PyBytes_GET_SIZE(data) == 1) {
- /* XXX this code path unused in Python 3? */
- /* expat often generates single character data sections; handle
- the most common case by resizing the existing string... */
- Py_ssize_t size = PyBytes_GET_SIZE(self->data);
- if (_PyBytes_Resize(&self->data, size + 1) < 0)
- return NULL;
- PyBytes_AS_STRING(self->data)[size] = PyBytes_AS_STRING(data)[0];
- } else if (PyList_CheckExact(self->data)) {
+ if (PyList_CheckExact(self->data)) {
if (PyList_Append(self->data, data) < 0)
return NULL;
} else {
@@ -2873,11 +2919,6 @@ treebuilder_handle_end(TreeBuilderObject* self, PyObject* tag)
Py_DECREF(last);
Py_XDECREF(last_for_tail);
- if (treebuilder_append_event(self, self->end_event_obj, self->last) < 0) {
- Py_DECREF(this);
- return NULL;
- }
-
return this;
}
@@ -2907,11 +2948,6 @@ treebuilder_handle_comment(TreeBuilderObject* self, PyObject* text)
comment = Py_NewRef(text);
}
- if (self->events_append && self->comment_event_obj) {
- if (treebuilder_append_event(self, self->comment_event_obj, comment) < 0)
- goto error;
- }
-
return comment;
error:
@@ -2950,11 +2986,6 @@ treebuilder_handle_pi(TreeBuilderObject* self, PyObject* target, PyObject* text)
}
}
- if (self->events_append && self->pi_event_obj) {
- if (treebuilder_append_event(self, self->pi_event_obj, pi) < 0)
- goto error;
- }
-
return pi;
error:
@@ -2962,39 +2993,6 @@ treebuilder_handle_pi(TreeBuilderObject* self, PyObject* target, PyObject* text)
return NULL;
}
-LOCAL(PyObject*)
-treebuilder_handle_start_ns(TreeBuilderObject* self, PyObject* prefix, PyObject* uri)
-{
- PyObject* parcel;
-
- if (self->events_append && self->start_ns_event_obj) {
- parcel = _PyTuple_FromPair(prefix, uri);
- if (!parcel) {
- return NULL;
- }
-
- if (treebuilder_append_event(self, self->start_ns_event_obj, parcel) < 0) {
- Py_DECREF(parcel);
- return NULL;
- }
- Py_DECREF(parcel);
- }
-
- Py_RETURN_NONE;
-}
-
-LOCAL(PyObject*)
-treebuilder_handle_end_ns(TreeBuilderObject* self, PyObject* prefix)
-{
- if (self->events_append && self->end_ns_event_obj) {
- if (treebuilder_append_event(self, self->end_ns_event_obj, prefix) < 0) {
- return NULL;
- }
- }
-
- Py_RETURN_NONE;
-}
-
/* -------------------------------------------------------------------- */
/* methods (in alphabetical order) */
@@ -3004,11 +3002,12 @@ _elementtree.TreeBuilder.data
data: object
/
+Add text to current element.
[clinic start generated code]*/
static PyObject *
_elementtree_TreeBuilder_data_impl(TreeBuilderObject *self, PyObject *data)
-/*[clinic end generated code: output=dfa02b68f732b8c0 input=a0540c532b284d29]*/
+/*[clinic end generated code: output=dfa02b68f732b8c0 input=679b26864cecbde8]*/
{
return treebuilder_handle_data(self, data);
}
@@ -3019,11 +3018,14 @@ _elementtree.TreeBuilder.end
tag: object
/
+Close and return current Element.
+
+*tag* is the element name.
[clinic start generated code]*/
static PyObject *
_elementtree_TreeBuilder_end_impl(TreeBuilderObject *self, PyObject *tag)
-/*[clinic end generated code: output=84cb6ca9008ec740 input=22dc3674236f5745]*/
+/*[clinic end generated code: output=84cb6ca9008ec740 input=9d161338282e5fac]*/
{
return treebuilder_handle_end(self, tag);
}
@@ -3034,12 +3036,15 @@ _elementtree.TreeBuilder.comment
text: object
/
+Create a comment using the comment_factory.
+
+*text* is the text of the comment.
[clinic start generated code]*/
static PyObject *
_elementtree_TreeBuilder_comment_impl(TreeBuilderObject *self,
PyObject *text)
-/*[clinic end generated code: output=a555ef39027c3823 input=47e7ebc48ed01dfa]*/
+/*[clinic end generated code: output=a555ef39027c3823 input=b1579b62bb9277e4]*/
{
return treebuilder_handle_comment(self, text);
}
@@ -3051,12 +3056,16 @@ _elementtree.TreeBuilder.pi
text: object = None
/
+Create a processing instruction using the pi_factory.
+
+*target* is the target name of the processing instruction. *text* is
+the data of the processing instruction, or ''.
[clinic start generated code]*/
static PyObject *
_elementtree_TreeBuilder_pi_impl(TreeBuilderObject *self, PyObject *target,
PyObject *text)
-/*[clinic end generated code: output=21eb95ec9d04d1d9 input=349342bd79c35570]*/
+/*[clinic end generated code: output=21eb95ec9d04d1d9 input=160b939cc17e4121]*/
{
return treebuilder_handle_pi(self, target, text);
}
@@ -3079,11 +3088,12 @@ treebuilder_done(TreeBuilderObject* self)
/*[clinic input]
_elementtree.TreeBuilder.close
+Flush builder buffers and return toplevel document Element.
[clinic start generated code]*/
static PyObject *
_elementtree_TreeBuilder_close_impl(TreeBuilderObject *self)
-/*[clinic end generated code: output=b441fee3202f61ee input=f7c9c65dc718de14]*/
+/*[clinic end generated code: output=b441fee3202f61ee input=461e8391c6b73c5f]*/
{
return treebuilder_done(self);
}
@@ -3095,12 +3105,16 @@ _elementtree.TreeBuilder.start
attrs: object(subclass_of='&PyDict_Type')
/
+Open new element and return it.
+
+*tag* is the element name, *attrs* is a dict containing element
+attributes.
[clinic start generated code]*/
static PyObject *
_elementtree_TreeBuilder_start_impl(TreeBuilderObject *self, PyObject *tag,
PyObject *attrs)
-/*[clinic end generated code: output=e7e9dc2861349411 input=7288e9e38e63b2b6]*/
+/*[clinic end generated code: output=e7e9dc2861349411 input=26cccb49c3b8b12f]*/
{
return treebuilder_handle_start(self, tag, attrs);
}
@@ -3125,6 +3139,15 @@ typedef struct {
PyObject *handle_start_ns;
PyObject *handle_end_ns;
+
+ /* event reporting for the pull API */
+ PyObject *events_append; /* the append method of the list of events */
+ PyObject *start_event_obj; /* event objects (NULL to ignore) */
+ PyObject *end_event_obj;
+ PyObject *start_ns_event_obj;
+ PyObject *end_ns_event_obj;
+ PyObject *comment_event_obj;
+ PyObject *pi_event_obj;
PyObject *handle_start;
PyObject *handle_data;
PyObject *handle_end;
@@ -3158,51 +3181,58 @@ makeuniversal(XMLParserObject* self, const char* string)
if (!key)
return NULL;
- value = Py_XNewRef(PyDict_GetItemWithError(self->names, key));
-
- if (value == NULL && !PyErr_Occurred()) {
- /* new name. convert to universal name, and decode as
- necessary */
+ if (PyDict_GetItemRef(self->names, key, &value) != 0) {
+ // The key exists or an error occurred
+ Py_DECREF(key);
+ return value;
+ }
- PyObject* tag;
- char* p;
- Py_ssize_t i;
+ /* new name. convert to universal name, and decode as
+ necessary */
- /* look for namespace separator */
- for (i = 0; i < size; i++)
- if (string[i] == '}')
- break;
- if (i != size) {
- /* convert to universal name */
- tag = PyBytes_FromStringAndSize(NULL, size+1);
- if (tag == NULL) {
- Py_DECREF(key);
- return NULL;
- }
- p = PyBytes_AS_STRING(tag);
- p[0] = '{';
- memcpy(p+1, string, size);
- size++;
- } else {
- /* plain name; use key as tag */
- tag = Py_NewRef(key);
- }
+ PyObject* tag;
+ Py_ssize_t i;
- /* decode universal name */
- p = PyBytes_AS_STRING(tag);
- value = PyUnicode_DecodeUTF8(p, size, "strict");
- Py_DECREF(tag);
- if (!value) {
+ /* look for namespace separator */
+ for (i = 0; i < size; i++)
+ if (string[i] == '}')
+ break;
+ if (i != size) {
+ /* convert to universal name */
+ PyBytesWriter *writer = PyBytesWriter_Create(1 + size);
+ if (writer == NULL) {
Py_DECREF(key);
return NULL;
}
+ char *p = PyBytesWriter_GetData(writer);
+ p[0] = '{';
+ memcpy(p+1, string, size);
+ size++;
- /* add to names dictionary */
- if (PyDict_SetItem(self->names, key, value) < 0) {
+ tag = PyBytesWriter_Finish(writer);
+ if (tag == NULL) {
Py_DECREF(key);
- Py_DECREF(value);
return NULL;
}
+ } else {
+ /* plain name; use key as tag */
+ tag = Py_NewRef(key);
+ }
+
+ /* decode universal name */
+ const char *p = PyBytes_AS_STRING(tag);
+ value = PyUnicode_DecodeUTF8(p, size, "strict");
+ Py_DECREF(tag);
+ if (!value) {
+ Py_DECREF(key);
+ return NULL;
+ }
+
+ /* add to names dictionary */
+ if (PyDict_SetItem(self->names, key, value) < 0) {
+ Py_DECREF(key);
+ Py_DECREF(value);
+ return NULL;
}
Py_DECREF(key);
@@ -3280,7 +3310,11 @@ expat_default_handler(void *op, const XML_Char *data_in, int data_len)
if (!key)
return;
- value = PyDict_GetItemWithError(self->entity, key);
+ if (PyDict_GetItemRef(self->entity, key, &value) < 0) {
+ Py_DECREF(key);
+ return;
+ }
+ Py_DECREF(key);
elementtreestate *st = self->state;
if (value) {
@@ -3292,8 +3326,10 @@ expat_default_handler(void *op, const XML_Char *data_in, int data_len)
res = PyObject_CallOneArg(self->handle_data, value);
else
res = NULL;
+ Py_DECREF(value);
Py_XDECREF(res);
- } else if (!PyErr_Occurred()) {
+ }
+ else {
/* Report the first error, not the last */
char message[128] = "undefined entity ";
strncat(message, data_in, data_len < 100?data_len:100);
@@ -3305,8 +3341,26 @@ expat_default_handler(void *op, const XML_Char *data_in, int data_len)
message
);
}
+}
- Py_DECREF(key);
+/* Append (action, node) to the list of events of the pull parser. */
+LOCAL(int)
+xmlparser_append_event(XMLParserObject *self, PyObject *action, PyObject *node)
+{
+ if (self->events_append == NULL || action == NULL || node == NULL) {
+ return 0;
+ }
+ PyObject *event = _PyTuple_FromPair(action, node);
+ if (event == NULL) {
+ return -1;
+ }
+ PyObject *res = PyObject_CallOneArg(self->events_append, event);
+ Py_DECREF(event);
+ if (res == NULL) {
+ return -1;
+ }
+ Py_DECREF(res);
+ return 0;
}
static void
@@ -3384,7 +3438,10 @@ expat_start_handler(void *op, const XML_Char *tag_in,
Py_DECREF(tag);
Py_XDECREF(attrib);
- Py_XDECREF(res);
+ if (res != NULL) {
+ (void)xmlparser_append_event(self, self->start_event_obj, res);
+ Py_DECREF(res);
+ }
}
static void
@@ -3441,7 +3498,10 @@ expat_end_handler(void *op, const XML_Char *tag_in)
}
}
- Py_XDECREF(res);
+ if (res != NULL) {
+ (void)xmlparser_append_event(self, self->end_event_obj, res);
+ Py_DECREF(res);
+ }
}
static void
@@ -3461,42 +3521,34 @@ expat_start_ns_handler(void *op, const XML_Char *prefix_in,
if (!prefix_in)
prefix_in = "";
- elementtreestate *st = self->state;
- if (TreeBuilder_CheckExact(st, self->target)) {
- /* shortcut - TreeBuilder does not actually implement .start_ns() */
- TreeBuilderObject *target = (TreeBuilderObject*) self->target;
-
- if (target->events_append && target->start_ns_event_obj) {
- prefix = PyUnicode_DecodeUTF8(prefix_in, strlen(prefix_in), "strict");
- if (!prefix)
- return;
- uri = PyUnicode_DecodeUTF8(uri_in, strlen(uri_in), "strict");
- if (!uri) {
- Py_DECREF(prefix);
- return;
- }
+ if (self->handle_start_ns == NULL && self->start_ns_event_obj == NULL) {
+ return;
+ }
- res = treebuilder_handle_start_ns(target, prefix, uri);
- Py_DECREF(uri);
- Py_DECREF(prefix);
- }
- } else if (self->handle_start_ns) {
- prefix = PyUnicode_DecodeUTF8(prefix_in, strlen(prefix_in), "strict");
- if (!prefix)
- return;
- uri = PyUnicode_DecodeUTF8(uri_in, strlen(uri_in), "strict");
- if (!uri) {
- Py_DECREF(prefix);
- return;
- }
+ prefix = PyUnicode_DecodeUTF8(prefix_in, strlen(prefix_in), "strict");
+ if (!prefix)
+ return;
+ uri = PyUnicode_DecodeUTF8(uri_in, strlen(uri_in), "strict");
+ if (!uri) {
+ Py_DECREF(prefix);
+ return;
+ }
+ if (self->handle_start_ns) {
PyObject *args[2] = {prefix, uri};
res = PyObject_Vectorcall(self->handle_start_ns, args, 2, NULL);
- Py_DECREF(uri);
- Py_DECREF(prefix);
}
+ else {
+ /* the target does not implement .start_ns(), report the pair */
+ res = _PyTuple_FromPair(prefix, uri);
+ }
+ Py_DECREF(uri);
+ Py_DECREF(prefix);
- Py_XDECREF(res);
+ if (res != NULL) {
+ (void)xmlparser_append_event(self, self->start_ns_event_obj, res);
+ Py_DECREF(res);
+ }
}
static void
@@ -3512,15 +3564,7 @@ expat_end_ns_handler(void *op, const XML_Char *prefix_in)
if (!prefix_in)
prefix_in = "";
- elementtreestate *st = self->state;
- if (TreeBuilder_CheckExact(st, self->target)) {
- /* shortcut - TreeBuilder does not actually implement .end_ns() */
- TreeBuilderObject *target = (TreeBuilderObject*) self->target;
-
- if (target->events_append && target->end_ns_event_obj) {
- res = treebuilder_handle_end_ns(target, Py_None);
- }
- } else if (self->handle_end_ns) {
+ if (self->handle_end_ns) {
prefix = PyUnicode_DecodeUTF8(prefix_in, strlen(prefix_in), "strict");
if (!prefix)
return;
@@ -3528,8 +3572,15 @@ expat_end_ns_handler(void *op, const XML_Char *prefix_in)
res = PyObject_CallOneArg(self->handle_end_ns, prefix);
Py_DECREF(prefix);
}
+ else if (self->end_ns_event_obj) {
+ /* the target does not implement .end_ns() */
+ res = Py_NewRef(Py_None);
+ }
- Py_XDECREF(res);
+ if (res != NULL) {
+ (void)xmlparser_append_event(self, self->end_ns_event_obj, res);
+ Py_DECREF(res);
+ }
}
static void
@@ -3552,16 +3603,22 @@ expat_comment_handler(void *op, const XML_Char *comment_in)
return; /* parser will look for errors */
res = treebuilder_handle_comment(target, comment);
- Py_XDECREF(res);
Py_DECREF(comment);
+ if (res != NULL) {
+ (void)xmlparser_append_event(self, self->comment_event_obj, res);
+ Py_DECREF(res);
+ }
} else if (self->handle_comment) {
comment = PyUnicode_DecodeUTF8(comment_in, strlen(comment_in), "strict");
if (!comment)
return;
res = PyObject_CallOneArg(self->handle_comment, comment);
- Py_XDECREF(res);
Py_DECREF(comment);
+ if (res != NULL) {
+ (void)xmlparser_append_event(self, self->comment_event_obj, res);
+ Py_DECREF(res);
+ }
}
}
@@ -3641,7 +3698,7 @@ expat_pi_handler(void *op, const XML_Char *target_in,
/* shortcut */
TreeBuilderObject *target = (TreeBuilderObject*) self->target;
- if ((target->events_append && target->pi_event_obj) || target->insert_pis) {
+ if (self->pi_event_obj || target->insert_pis) {
pi_target = PyUnicode_DecodeUTF8(target_in, strlen(target_in), "strict");
if (!pi_target)
goto error;
@@ -3649,9 +3706,12 @@ expat_pi_handler(void *op, const XML_Char *target_in,
if (!data)
goto error;
res = treebuilder_handle_pi(target, pi_target, data);
- Py_XDECREF(res);
Py_DECREF(data);
Py_DECREF(pi_target);
+ if (res != NULL) {
+ (void)xmlparser_append_event(self, self->pi_event_obj, res);
+ Py_DECREF(res);
+ }
}
} else if (self->handle_pi) {
pi_target = PyUnicode_DecodeUTF8(target_in, strlen(target_in), "strict");
@@ -3663,9 +3723,12 @@ expat_pi_handler(void *op, const XML_Char *target_in,
PyObject *args[2] = {pi_target, data};
res = PyObject_Vectorcall(self->handle_pi, args, 2, NULL);
- Py_XDECREF(res);
Py_DECREF(data);
Py_DECREF(pi_target);
+ if (res != NULL) {
+ (void)xmlparser_append_event(self, self->pi_event_obj, res);
+ Py_DECREF(res);
+ }
}
return;
@@ -3688,6 +3751,10 @@ xmlparser_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
self->handle_start = self->handle_data = self->handle_end = NULL;
self->handle_comment = self->handle_pi = self->handle_close = NULL;
self->handle_doctype = NULL;
+ self->events_append = NULL;
+ self->start_event_obj = self->end_event_obj = NULL;
+ self->start_ns_event_obj = self->end_ns_event_obj = NULL;
+ self->comment_event_obj = self->pi_event_obj = NULL;
self->elementtree_module = PyType_GetModuleByDef(type, &elementtreemodule);
assert(self->elementtree_module != NULL);
Py_INCREF(self->elementtree_module);
@@ -3716,12 +3783,18 @@ _elementtree.XMLParser.__init__
target: object = None
encoding: str(accept={str, NoneType}) = None
+Element structure builder for XML source data based on the expat parser.
+
+*target* is an optional target object which defaults to an instance
+of the standard TreeBuilder class, *encoding* is an optional encoding
+string which if given, overrides the encoding specified in the XML
+file: http://www.iana.org/assignments/character-sets
[clinic start generated code]*/
static int
_elementtree_XMLParser___init___impl(XMLParserObject *self, PyObject *target,
const char *encoding)
-/*[clinic end generated code: output=3ae45ec6cdf344e4 input=7e716dd6e4f3e439]*/
+/*[clinic end generated code: output=3ae45ec6cdf344e4 input=a77eb075d276d487]*/
{
self->entity = PyDict_New();
if (!self->entity)
@@ -3856,6 +3929,13 @@ xmlparser_gc_traverse(PyObject *op, visitproc visit, void *arg)
Py_VISIT(self->handle_start_ns);
Py_VISIT(self->handle_end_ns);
Py_VISIT(self->handle_doctype);
+ Py_VISIT(self->events_append);
+ Py_VISIT(self->start_event_obj);
+ Py_VISIT(self->end_event_obj);
+ Py_VISIT(self->start_ns_event_obj);
+ Py_VISIT(self->end_ns_event_obj);
+ Py_VISIT(self->comment_event_obj);
+ Py_VISIT(self->pi_event_obj);
Py_VISIT(self->target);
Py_VISIT(self->entity);
@@ -3885,6 +3965,13 @@ xmlparser_gc_clear(PyObject *op)
Py_CLEAR(self->handle_start_ns);
Py_CLEAR(self->handle_end_ns);
Py_CLEAR(self->handle_doctype);
+ Py_CLEAR(self->events_append);
+ Py_CLEAR(self->start_event_obj);
+ Py_CLEAR(self->end_event_obj);
+ Py_CLEAR(self->start_ns_event_obj);
+ Py_CLEAR(self->end_ns_event_obj);
+ Py_CLEAR(self->comment_event_obj);
+ Py_CLEAR(self->pi_event_obj);
Py_CLEAR(self->target);
Py_CLEAR(self->entity);
@@ -3940,14 +4027,36 @@ expat_parse(elementtreestate *st, XMLParserObject *self, const char *data,
Py_RETURN_NONE;
}
+/* Expat takes the length as an int, feed larger data in chunks. */
+#define MAX_CHUNK_SIZE (1 << 20)
+
+LOCAL(PyObject*)
+expat_parse_large(elementtreestate *st, XMLParserObject *self,
+ const char *data, Py_ssize_t data_len, int final)
+{
+ static_assert(MAX_CHUNK_SIZE <= INT_MAX,
+ "MAX_CHUNK_SIZE is larger than INT_MAX");
+ while (data_len > MAX_CHUNK_SIZE) {
+ PyObject *res = expat_parse(st, self, data, MAX_CHUNK_SIZE, 0);
+ if (res == NULL) {
+ return NULL;
+ }
+ Py_DECREF(res);
+ data += MAX_CHUNK_SIZE;
+ data_len -= MAX_CHUNK_SIZE;
+ }
+ return expat_parse(st, self, data, (int)data_len, final);
+}
+
/*[clinic input]
_elementtree.XMLParser.close
+Finish feeding data to parser and return element structure.
[clinic start generated code]*/
static PyObject *
_elementtree_XMLParser_close_impl(XMLParserObject *self)
-/*[clinic end generated code: output=d68d375dd23bc7fb input=ca7909ca78c3abfe]*/
+/*[clinic end generated code: output=d68d375dd23bc7fb input=177603f3353e644f]*/
{
/* end feeding data to parser */
@@ -4014,11 +4123,12 @@ _elementtree.XMLParser.feed
data: object
/
+Feed encoded data to parser.
[clinic start generated code]*/
static PyObject *
_elementtree_XMLParser_feed_impl(XMLParserObject *self, PyObject *data)
-/*[clinic end generated code: output=503e6fbf1adf17ab input=fe231b6b8de3ce1f]*/
+/*[clinic end generated code: output=503e6fbf1adf17ab input=9432a189100bc488]*/
{
/* feed data to parser */
@@ -4031,26 +4141,17 @@ _elementtree_XMLParser_feed_impl(XMLParserObject *self, PyObject *data)
const char *data_ptr = PyUnicode_AsUTF8AndSize(data, &data_len);
if (data_ptr == NULL)
return NULL;
- if (data_len > INT_MAX) {
- PyErr_SetString(PyExc_OverflowError, "size does not fit in an int");
- return NULL;
- }
/* Explicitly set UTF-8 encoding. Return code ignored. */
(void)EXPAT(st, SetEncoding)(self->parser, "utf-8");
- return expat_parse(st, self, data_ptr, (int)data_len, 0);
+ return expat_parse_large(st, self, data_ptr, data_len, 0);
}
else {
Py_buffer view;
PyObject *res;
if (PyObject_GetBuffer(data, &view, PyBUF_SIMPLE) < 0)
return NULL;
- if (view.len > INT_MAX) {
- PyBuffer_Release(&view);
- PyErr_SetString(PyExc_OverflowError, "size does not fit in an int");
- return NULL;
- }
- res = expat_parse(st, self, view.buf, (int)view.len, 0);
+ res = expat_parse_large(st, self, view.buf, view.len, 0);
PyBuffer_Release(&view);
return res;
}
@@ -4084,6 +4185,7 @@ _elementtree_XMLParser__parse_whole_impl(XMLParserObject *self,
/* read from open file object */
elementtreestate *st = self->state;
+ int first = 1;
for (;;) {
buffer = PyObject_CallFunction(reader, "i", 64*1024);
@@ -4100,6 +4202,11 @@ _elementtree_XMLParser__parse_whole_impl(XMLParserObject *self,
Py_DECREF(buffer);
break;
}
+ if (first) {
+ /* The text is already decoded, the encoding declared in the
+ document does not apply to it. Return code ignored. */
+ (void)EXPAT(st, SetEncoding)(self->parser, "utf-8");
+ }
temp = PyUnicode_AsEncodedString(buffer, "utf-8", "surrogatepass");
Py_DECREF(buffer);
if (!temp) {
@@ -4114,15 +4221,10 @@ _elementtree_XMLParser__parse_whole_impl(XMLParserObject *self,
break;
}
- if (PyBytes_GET_SIZE(buffer) > INT_MAX) {
- Py_DECREF(buffer);
- Py_DECREF(reader);
- PyErr_SetString(PyExc_OverflowError, "size does not fit in an int");
- return NULL;
- }
- res = expat_parse(
- st, self, PyBytes_AS_STRING(buffer), (int)PyBytes_GET_SIZE(buffer),
+ res = expat_parse_large(
+ st, self, PyBytes_AS_STRING(buffer), PyBytes_GET_SIZE(buffer),
0);
+ first = 0;
Py_DECREF(buffer);
@@ -4163,40 +4265,31 @@ _elementtree_XMLParser__setevents_impl(XMLParserObject *self,
{
/* activate element event reporting */
Py_ssize_t i;
- TreeBuilderObject *target;
PyObject *events_append, *events_seq;
if (!_check_xmlparser(self)) {
return NULL;
}
elementtreestate *st = self->state;
- if (!TreeBuilder_CheckExact(st, self->target)) {
- PyErr_SetString(
- PyExc_TypeError,
- "event handling only supported for ElementTree.TreeBuilder "
- "targets"
- );
- return NULL;
- }
-
- target = (TreeBuilderObject*) self->target;
-
events_append = PyObject_GetAttrString(events_queue, "append");
if (events_append == NULL)
return NULL;
- Py_XSETREF(target->events_append, events_append);
+ Py_XSETREF(self->events_append, events_append);
/* clear out existing events */
- Py_CLEAR(target->start_event_obj);
- Py_CLEAR(target->end_event_obj);
- Py_CLEAR(target->start_ns_event_obj);
- Py_CLEAR(target->end_ns_event_obj);
- Py_CLEAR(target->comment_event_obj);
- Py_CLEAR(target->pi_event_obj);
+ Py_CLEAR(self->start_event_obj);
+ Py_CLEAR(self->end_event_obj);
+ Py_CLEAR(self->start_ns_event_obj);
+ Py_CLEAR(self->end_ns_event_obj);
+ Py_CLEAR(self->comment_event_obj);
+ Py_CLEAR(self->pi_event_obj);
if (events_to_report == Py_None) {
/* default is "end" only */
- target->end_event_obj = PyUnicode_FromString("end");
+ self->end_event_obj = PyUnicode_FromString("end");
+ if (self->end_event_obj == NULL) {
+ return NULL;
+ }
Py_RETURN_NONE;
}
@@ -4207,50 +4300,68 @@ _elementtree_XMLParser__setevents_impl(XMLParserObject *self,
for (i = 0; i < PySequence_Fast_GET_SIZE(events_seq); ++i) {
PyObject *event_name_obj = PySequence_Fast_GET_ITEM(events_seq, i);
- const char *event_name = NULL;
- if (PyUnicode_Check(event_name_obj)) {
- event_name = PyUnicode_AsUTF8(event_name_obj);
- } else if (PyBytes_Check(event_name_obj)) {
- event_name = PyBytes_AS_STRING(event_name_obj);
+ if (!PyUnicode_Check(event_name_obj)) {
+ goto unknown_event;
}
+ const char *event_name = PyUnicode_AsUTF8(event_name_obj);
if (event_name == NULL) {
Py_DECREF(events_seq);
- PyErr_Format(PyExc_ValueError, "invalid events sequence");
return NULL;
}
+ /* the target must implement the method of the event,
+ except for the namespace events */
+ PyObject *handler = Py_None;
if (strcmp(event_name, "start") == 0) {
- Py_XSETREF(target->start_event_obj, Py_NewRef(event_name_obj));
+ handler = self->handle_start;
} else if (strcmp(event_name, "end") == 0) {
- Py_XSETREF(target->end_event_obj, Py_NewRef(event_name_obj));
+ handler = self->handle_end;
+ } else if (strcmp(event_name, "comment") == 0) {
+ handler = self->handle_comment;
+ } else if (strcmp(event_name, "pi") == 0) {
+ handler = self->handle_pi;
+ }
+ if (handler == NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "the target does not support %R events",
+ event_name_obj);
+ Py_DECREF(events_seq);
+ return NULL;
+ }
+
+ if (strcmp(event_name, "start") == 0) {
+ Py_XSETREF(self->start_event_obj, Py_NewRef(event_name_obj));
+ } else if (strcmp(event_name, "end") == 0) {
+ Py_XSETREF(self->end_event_obj, Py_NewRef(event_name_obj));
} else if (strcmp(event_name, "start-ns") == 0) {
- Py_XSETREF(target->start_ns_event_obj, Py_NewRef(event_name_obj));
+ Py_XSETREF(self->start_ns_event_obj, Py_NewRef(event_name_obj));
EXPAT(st, SetNamespaceDeclHandler)(
self->parser,
(XML_StartNamespaceDeclHandler) expat_start_ns_handler,
(XML_EndNamespaceDeclHandler) expat_end_ns_handler
);
} else if (strcmp(event_name, "end-ns") == 0) {
- Py_XSETREF(target->end_ns_event_obj, Py_NewRef(event_name_obj));
+ Py_XSETREF(self->end_ns_event_obj, Py_NewRef(event_name_obj));
EXPAT(st, SetNamespaceDeclHandler)(
self->parser,
(XML_StartNamespaceDeclHandler) expat_start_ns_handler,
(XML_EndNamespaceDeclHandler) expat_end_ns_handler
);
} else if (strcmp(event_name, "comment") == 0) {
- Py_XSETREF(target->comment_event_obj, Py_NewRef(event_name_obj));
+ Py_XSETREF(self->comment_event_obj, Py_NewRef(event_name_obj));
EXPAT(st, SetCommentHandler)(
self->parser,
(XML_CommentHandler) expat_comment_handler
);
} else if (strcmp(event_name, "pi") == 0) {
- Py_XSETREF(target->pi_event_obj, Py_NewRef(event_name_obj));
+ Py_XSETREF(self->pi_event_obj, Py_NewRef(event_name_obj));
EXPAT(st, SetProcessingInstructionHandler)(
self->parser,
(XML_ProcessingInstructionHandler) expat_pi_handler
);
} else {
- PyErr_Format(PyExc_ValueError, "unknown event '%s'", event_name);
+unknown_event:
+ PyErr_Format(PyExc_ValueError, "unknown event %R", event_name_obj);
Py_DECREF(events_seq);
return NULL;
}
@@ -4342,7 +4453,27 @@ static PyGetSetDef element_getsetlist[] = {
{NULL},
};
+PyDoc_STRVAR(element_doc,
+"Element(tag, attrib={}, **extra)\n"
+"--\n"
+"\n"
+"An XML element.\n"
+"\n"
+"This class is the reference implementation of the Element interface.\n"
+"\n"
+"An element's length is its number of subelements. That means if you\n"
+"want to check if an element is truly empty, you should check BOTH\n"
+"its length AND its text attribute.\n"
+"\n"
+"*tag* is the element name. *attrib* is an optional dictionary\n"
+"containing element attributes. *extra* are additional element\n"
+"attributes given as keyword arguments.\n"
+"\n"
+"Example form:\n"
+" text...tail");
+
static PyType_Slot element_slots[] = {
+ {Py_tp_doc, (void *)element_doc},
{Py_tp_dealloc, element_dealloc},
{Py_tp_repr, element_repr},
{Py_tp_getattro, PyObject_GenericGetAttr},
@@ -4383,6 +4514,7 @@ static PyMethodDef treebuilder_methods[] = {
};
static PyType_Slot treebuilder_slots[] = {
+ {Py_tp_doc, (void *)_elementtree_TreeBuilder___init____doc__},
{Py_tp_dealloc, treebuilder_dealloc},
{Py_tp_traverse, treebuilder_gc_traverse},
{Py_tp_clear, treebuilder_gc_clear},
@@ -4410,6 +4542,7 @@ static PyMethodDef xmlparser_methods[] = {
};
static PyType_Slot xmlparser_slots[] = {
+ {Py_tp_doc, (void *)_elementtree_XMLParser___init____doc__},
{Py_tp_dealloc, xmlparser_dealloc},
{Py_tp_traverse, xmlparser_gc_traverse},
{Py_tp_clear, xmlparser_gc_clear},
@@ -4434,7 +4567,7 @@ static PyType_Spec xmlparser_spec = {
/* python module interface */
static PyMethodDef _functions[] = {
- {"SubElement", _PyCFunction_CAST(subelement), METH_VARARGS | METH_KEYWORDS},
+ _ELEMENTTREE_SUBELEMENT_METHODDEF
_ELEMENTTREE__SET_FACTORIES_METHODDEF
{NULL, NULL}
};
diff --git a/Modules/_functoolsmodule.c b/Modules/_functoolsmodule.c
index b4595c55d519b93..75b93d87e90a999 100644
--- a/Modules/_functoolsmodule.c
+++ b/Modules/_functoolsmodule.c
@@ -27,7 +27,6 @@ class _functools._lru_cache_wrapper "PyObject *" "&lru_cache_type_spec"
typedef struct _functools_state {
/* this object is used delimit args and keywords in the cache keys */
PyObject *kwd_mark;
- PyTypeObject *placeholder_type;
PyObject *placeholder; // strong reference (singleton)
PyTypeObject *partial_type;
PyTypeObject *keyobject_type;
@@ -55,77 +54,6 @@ typedef struct {
static inline _functools_state *
get_functools_state_by_type(PyTypeObject *type);
-PyDoc_STRVAR(placeholder_doc,
-"The type of the Placeholder singleton.\n\n"
-"Used as a placeholder for partial arguments.");
-
-static PyObject *
-placeholder_repr(PyObject *op)
-{
- return PyUnicode_FromString("Placeholder");
-}
-
-static PyObject *
-placeholder_reduce(PyObject *op, PyObject *Py_UNUSED(ignored))
-{
- return PyUnicode_FromString("Placeholder");
-}
-
-static PyMethodDef placeholder_methods[] = {
- {"__reduce__", placeholder_reduce, METH_NOARGS, NULL},
- {NULL, NULL}
-};
-
-static void
-placeholder_dealloc(PyObject* self)
-{
- PyObject_GC_UnTrack(self);
- PyTypeObject *tp = Py_TYPE(self);
- tp->tp_free((PyObject*)self);
- Py_DECREF(tp);
-}
-
-static PyObject *
-placeholder_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
-{
- if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
- PyErr_SetString(PyExc_TypeError, "PlaceholderType takes no arguments");
- return NULL;
- }
- _functools_state *state = get_functools_state_by_type(type);
- if (state->placeholder != NULL) {
- return Py_NewRef(state->placeholder);
- }
-
- PyObject *placeholder = PyType_GenericNew(type, NULL, NULL);
- if (placeholder == NULL) {
- return NULL;
- }
-
- if (state->placeholder == NULL) {
- state->placeholder = Py_NewRef(placeholder);
- }
- return placeholder;
-}
-
-static PyType_Slot placeholder_type_slots[] = {
- {Py_tp_dealloc, placeholder_dealloc},
- {Py_tp_repr, placeholder_repr},
- {Py_tp_doc, (void *)placeholder_doc},
- {Py_tp_methods, placeholder_methods},
- {Py_tp_new, placeholder_new},
- {Py_tp_traverse, _PyObject_VisitType},
- {0, 0}
-};
-
-static PyType_Spec placeholder_type_spec = {
- .name = "functools._PlaceholderType",
- .basicsize = sizeof(placeholderobject),
- .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_HAVE_GC,
- .slots = placeholder_type_slots
-};
-
-
typedef struct {
PyObject_HEAD
PyObject *fn;
@@ -382,9 +310,14 @@ partial_vectorcall(PyObject *self, PyObject *const *args,
return NULL;
}
- PyObject **pto_args = _PyTuple_ITEMS(pto->args);
- Py_ssize_t pto_nargs = PyTuple_GET_SIZE(pto->args);
- Py_ssize_t pto_nkwds = PyDict_GET_SIZE(pto->kw);
+ PyObject *result = NULL;
+ PyObject *partial_function = Py_NewRef(pto->fn);
+ PyObject *partial_args = Py_NewRef(pto->args);
+ PyObject *partial_keywords = Py_NewRef(pto->kw);
+
+ PyObject **pto_args = _PyTuple_ITEMS(partial_args);
+ Py_ssize_t pto_nargs = PyTuple_GET_SIZE(partial_args);
+ Py_ssize_t pto_nkwds = PyDict_GET_SIZE(partial_keywords);
Py_ssize_t nkwds = kwnames == NULL ? 0 : PyTuple_GET_SIZE(kwnames);
Py_ssize_t nargskw = nargs + nkwds;
@@ -392,8 +325,9 @@ partial_vectorcall(PyObject *self, PyObject *const *args,
if (!pto_nkwds) {
/* Fast path if we're called without arguments */
if (nargskw == 0) {
- return _PyObject_VectorcallTstate(tstate, pto->fn, pto_args,
- pto_nargs, NULL);
+ result = _PyObject_VectorcallTstate(tstate, partial_function, pto_args,
+ pto_nargs, NULL);
+ goto done;
}
/* Use PY_VECTORCALL_ARGUMENTS_OFFSET to prepend a single
@@ -402,10 +336,10 @@ partial_vectorcall(PyObject *self, PyObject *const *args,
PyObject **newargs = (PyObject **)args - 1;
PyObject *tmp = newargs[0];
newargs[0] = pto_args[0];
- PyObject *ret = _PyObject_VectorcallTstate(tstate, pto->fn, newargs,
- nargs + 1, kwnames);
+ result = _PyObject_VectorcallTstate(tstate, partial_function, newargs,
+ nargs + 1, kwnames);
newargs[0] = tmp;
- return ret;
+ goto done;
}
}
@@ -435,7 +369,8 @@ partial_vectorcall(PyObject *self, PyObject *const *args,
else {
stack = PyMem_Malloc(init_stack_size * sizeof(PyObject *));
if (stack == NULL) {
- return PyErr_NoMemory();
+ PyErr_NoMemory();
+ goto done;
}
}
@@ -457,20 +392,20 @@ partial_vectorcall(PyObject *self, PyObject *const *args,
for (Py_ssize_t i = 0; i < nkwds; ++i) {
key = PyTuple_GET_ITEM(kwnames, i);
val = args[nargs + i];
- int contains = PyDict_Contains(pto->kw, key);
+ int contains = PyDict_Contains(partial_keywords, key);
if (contains < 0) {
- goto error;
+ goto clean_stack;
}
else if (contains == 1) {
if (pto_kw_merged == NULL) {
- pto_kw_merged = PyDict_Copy(pto->kw);
+ pto_kw_merged = PyDict_Copy(partial_keywords);
if (pto_kw_merged == NULL) {
- goto error;
+ goto clean_stack;
}
}
if (PyDict_SetItem(pto_kw_merged, key, val) < 0) {
Py_DECREF(pto_kw_merged);
- goto error;
+ goto clean_stack;
}
}
else {
@@ -486,7 +421,7 @@ partial_vectorcall(PyObject *self, PyObject *const *args,
tot_kwnames = PyTuple_New(tot_nkwds - n_merges);
if (tot_kwnames == NULL) {
Py_XDECREF(pto_kw_merged);
- goto error;
+ goto clean_stack;
}
for (Py_ssize_t i = 0; i < n_tail; ++i) {
key = Py_NewRef(stack[tot_nargskw + i]);
@@ -496,7 +431,7 @@ partial_vectorcall(PyObject *self, PyObject *const *args,
/* Copy pto_keywords with overlapping call keywords merged
* Note, tail is already coppied. */
Py_ssize_t pos = 0, i = 0;
- PyObject *keyword_dict = n_merges ? pto_kw_merged : pto->kw;
+ PyObject *keyword_dict = n_merges ? pto_kw_merged : partial_keywords;
Py_BEGIN_CRITICAL_SECTION(keyword_dict);
while (PyDict_Next(keyword_dict, &pos, &key, &val)) {
assert(i < pto_nkwds);
@@ -515,10 +450,8 @@ partial_vectorcall(PyObject *self, PyObject *const *args,
tmp_stack = PyMem_Realloc(stack, (tot_nargskw - n_merges) * sizeof(PyObject *));
if (tmp_stack == NULL) {
Py_DECREF(tot_kwnames);
- if (stack != small_stack) {
- PyMem_Free(stack);
- }
- return PyErr_NoMemory();
+ PyErr_NoMemory();
+ goto clean_stack;
}
stack = tmp_stack;
}
@@ -547,21 +480,22 @@ partial_vectorcall(PyObject *self, PyObject *const *args,
memcpy(stack + pto_nargs, args, nargs * sizeof(PyObject*));
}
- PyObject *ret = _PyObject_VectorcallTstate(tstate, pto->fn, stack,
- tot_nargs, tot_kwnames);
- if (stack != small_stack) {
- PyMem_Free(stack);
- }
+ result = _PyObject_VectorcallTstate(tstate, partial_function, stack,
+ tot_nargs, tot_kwnames);
if (pto_nkwds) {
Py_DECREF(tot_kwnames);
}
- return ret;
- error:
+ clean_stack:
if (stack != small_stack) {
PyMem_Free(stack);
}
- return NULL;
+
+ done:
+ Py_DECREF(partial_function);
+ Py_DECREF(partial_args);
+ Py_DECREF(partial_keywords);
+ return result;
}
/* Set pto->vectorcall depending on the parameters of the partial object */
@@ -1811,14 +1745,31 @@ lru_cache_reduce(PyObject *self, PyObject *Py_UNUSED(dummy))
return PyObject_GetAttrString(self, "__qualname__");
}
+/*[clinic input]
+_functools._lru_cache_wrapper.__copy__
+
+Return a copy of the wrapper, which is the wrapper itself.
+[clinic start generated code]*/
+
static PyObject *
-lru_cache_copy(PyObject *self, PyObject *Py_UNUSED(args))
+_functools__lru_cache_wrapper___copy___impl(PyObject *self)
+/*[clinic end generated code: output=d681851615d57391 input=41d000bde05efb2b]*/
{
return Py_NewRef(self);
}
+/*[clinic input]
+_functools._lru_cache_wrapper.__deepcopy__
+
+ memo: object
+ /
+
+Return a deep copy of the wrapper, which is the wrapper itself.
+[clinic start generated code]*/
+
static PyObject *
-lru_cache_deepcopy(PyObject *self, PyObject *Py_UNUSED(args))
+_functools__lru_cache_wrapper___deepcopy__(PyObject *self, PyObject *memo)
+/*[clinic end generated code: output=3445cd9d96273c9e input=84f706565f55ce46]*/
{
return Py_NewRef(self);
}
@@ -1866,8 +1817,8 @@ static PyMethodDef lru_cache_methods[] = {
_FUNCTOOLS__LRU_CACHE_WRAPPER_CACHE_INFO_METHODDEF
_FUNCTOOLS__LRU_CACHE_WRAPPER_CACHE_CLEAR_METHODDEF
{"__reduce__", lru_cache_reduce, METH_NOARGS},
- {"__copy__", lru_cache_copy, METH_VARARGS},
- {"__deepcopy__", lru_cache_deepcopy, METH_VARARGS},
+ _FUNCTOOLS__LRU_CACHE_WRAPPER___COPY___METHODDEF
+ _FUNCTOOLS__LRU_CACHE_WRAPPER___DEEPCOPY___METHODDEF
{NULL}
};
@@ -1927,16 +1878,7 @@ _functools_exec(PyObject *module)
return -1;
}
- state->placeholder_type = (PyTypeObject *)PyType_FromModuleAndSpec(module,
- &placeholder_type_spec, NULL);
- if (state->placeholder_type == NULL) {
- return -1;
- }
- if (PyModule_AddType(module, state->placeholder_type) < 0) {
- return -1;
- }
-
- PyObject *placeholder = PyObject_CallNoArgs((PyObject *)state->placeholder_type);
+ PyObject *placeholder = PySentinel_New("Placeholder", "functools", NULL);
if (placeholder == NULL) {
return -1;
}
@@ -1944,7 +1886,7 @@ _functools_exec(PyObject *module)
Py_DECREF(placeholder);
return -1;
}
- Py_DECREF(placeholder);
+ state->placeholder = placeholder;
state->partial_type = (PyTypeObject *)PyType_FromModuleAndSpec(module,
&partial_type_spec, NULL);
@@ -1990,7 +1932,6 @@ _functools_traverse(PyObject *module, visitproc visit, void *arg)
{
_functools_state *state = get_functools_state(module);
Py_VISIT(state->kwd_mark);
- Py_VISIT(state->placeholder_type);
Py_VISIT(state->placeholder);
Py_VISIT(state->partial_type);
Py_VISIT(state->keyobject_type);
@@ -2003,7 +1944,6 @@ _functools_clear(PyObject *module)
{
_functools_state *state = get_functools_state(module);
Py_CLEAR(state->kwd_mark);
- Py_CLEAR(state->placeholder_type);
Py_CLEAR(state->placeholder);
Py_CLEAR(state->partial_type);
Py_CLEAR(state->keyobject_type);
diff --git a/Modules/_gdbmmodule.c b/Modules/_gdbmmodule.c
index 20d482021656a50..2cec6e0a0bafbbc 100644
--- a/Modules/_gdbmmodule.c
+++ b/Modules/_gdbmmodule.c
@@ -136,10 +136,16 @@ gdbm_dealloc(PyObject *op)
Py_DECREF(tp);
}
+/*[clinic input]
+@critical_section
+_gdbm.gdbm.__len__ as gdbm_length
+[clinic start generated code]*/
+
static Py_ssize_t
-gdbm_length_lock_held(PyObject *op)
+gdbm_length_impl(gdbmobject *self)
+/*[clinic end generated code: output=3ccb956974ed73b5 input=57878f60d264ed98]*/
{
- gdbmobject *dp = _gdbmobject_CAST(op);
+ gdbmobject *dp = self;
_gdbm_state *state = PyType_GetModuleState(Py_TYPE(dp));
if (dp->di_dbm == NULL) {
PyErr_SetString(state->gdbm_error, "GDBM object has already been closed");
@@ -183,20 +189,16 @@ gdbm_length_lock_held(PyObject *op)
return dp->di_size;
}
-static Py_ssize_t
-gdbm_length(PyObject *op)
-{
- Py_ssize_t result;
- Py_BEGIN_CRITICAL_SECTION(op);
- result = gdbm_length_lock_held(op);
- Py_END_CRITICAL_SECTION();
- return result;
-}
+/*[clinic input]
+@critical_section
+_gdbm.gdbm.__bool__ as gdbm_bool
+[clinic start generated code]*/
static int
-gdbm_bool_lock_held(PyObject *op)
+gdbm_bool_impl(gdbmobject *self)
+/*[clinic end generated code: output=91316ca18acb945c input=bf2878ff5e311848]*/
{
- gdbmobject *dp = _gdbmobject_CAST(op);
+ gdbmobject *dp = self;
_gdbm_state *state = PyType_GetModuleState(Py_TYPE(dp));
if (dp->di_dbm == NULL) {
PyErr_SetString(state->gdbm_error, "GDBM object has already been closed");
@@ -223,16 +225,6 @@ gdbm_bool_lock_held(PyObject *op)
return 1;
}
-static int
-gdbm_bool(PyObject *op)
-{
- int result;
- Py_BEGIN_CRITICAL_SECTION(op);
- result = gdbm_bool_lock_held(op);
- Py_END_CRITICAL_SECTION();
- return result;
-}
-
// Wrapper function for PyArg_Parse(o, "s#", &d.dptr, &d.size).
// This function is needed to support PY_SSIZE_T_CLEAN.
// Return 1 on success, same to PyArg_Parse().
@@ -254,12 +246,20 @@ parse_datum(PyObject *o, datum *d, const char *failmsg)
return 1;
}
+/*[clinic input]
+@critical_section
+_gdbm.gdbm.__getitem__ as gdbm_subscript
+ key: object
+ /
+[clinic start generated code]*/
+
static PyObject *
-gdbm_subscript_lock_held(PyObject *op, PyObject *key)
+gdbm_subscript_impl(gdbmobject *self, PyObject *key)
+/*[clinic end generated code: output=e96388d53678e967 input=8324d90d97ae98f0]*/
{
PyObject *v;
datum drec, krec;
- gdbmobject *dp = _gdbmobject_CAST(op);
+ gdbmobject *dp = self;
_gdbm_state *state = PyType_GetModuleState(Py_TYPE(dp));
if (!parse_datum(key, &krec, NULL)) {
@@ -280,16 +280,6 @@ gdbm_subscript_lock_held(PyObject *op, PyObject *key)
return v;
}
-static PyObject *
-gdbm_subscript(PyObject *op, PyObject *key)
-{
- PyObject *result;
- Py_BEGIN_CRITICAL_SECTION(op);
- result = gdbm_subscript_lock_held(op, key);
- Py_END_CRITICAL_SECTION();
- return result;
-}
-
/*[clinic input]
_gdbm.gdbm.get
@@ -314,12 +304,22 @@ _gdbm_gdbm_get_impl(gdbmobject *self, PyObject *key, PyObject *default_value)
return res;
}
+/*[clinic input]
+@critical_section
+_gdbm.gdbm.__setitem__ as gdbm_ass_sub
+
+ v: object
+ w: object
+ /
+[clinic start generated code]*/
+
static int
-gdbm_ass_sub_lock_held(PyObject *op, PyObject *v, PyObject *w)
+gdbm_ass_sub_impl(gdbmobject *self, PyObject *v, PyObject *w)
+/*[clinic end generated code: output=b46cce6ffa309dab input=fbd980f3b49e2f91]*/
{
datum krec, drec;
const char *failmsg = "gdbm mappings have bytes or string indices only";
- gdbmobject *dp = _gdbmobject_CAST(op);
+ gdbmobject *dp = self;
_gdbm_state *state = PyType_GetModuleState(Py_TYPE(dp));
if (!parse_datum(v, &krec, failmsg)) {
@@ -360,16 +360,6 @@ gdbm_ass_sub_lock_held(PyObject *op, PyObject *v, PyObject *w)
return 0;
}
-static int
-gdbm_ass_sub(PyObject *op, PyObject *v, PyObject *w)
-{
- int result;
- Py_BEGIN_CRITICAL_SECTION(op);
- result = gdbm_ass_sub_lock_held(op, v, w);
- Py_END_CRITICAL_SECTION();
- return result;
-}
-
/*[clinic input]
@permit_long_summary
@critical_section
@@ -470,10 +460,18 @@ _gdbm_gdbm_keys_impl(gdbmobject *self, PyTypeObject *cls)
return v;
}
+/*[clinic input]
+@critical_section
+_gdbm.gdbm.__contains__ as gdbm_contains
+ arg: object
+ /
+[clinic start generated code]*/
+
static int
-gdbm_contains_lock_held(PyObject *self, PyObject *arg)
+gdbm_contains_impl(gdbmobject *self, PyObject *arg)
+/*[clinic end generated code: output=ad951f5a9f4194df input=411dc2039fdd7277]*/
{
- gdbmobject *dp = (gdbmobject *)self;
+ gdbmobject *dp = self;
datum key;
Py_ssize_t size;
_gdbm_state *state = PyType_GetModuleState(Py_TYPE(dp));
@@ -502,16 +500,6 @@ gdbm_contains_lock_held(PyObject *self, PyObject *arg)
return gdbm_exists(dp->di_dbm, key);
}
-static int
-gdbm_contains(PyObject *self, PyObject *arg)
-{
- int result;
- Py_BEGIN_CRITICAL_SECTION(self);
- result = gdbm_contains_lock_held(self, arg);
- Py_END_CRITICAL_SECTION();
- return result;
-}
-
/*[clinic input]
@critical_section
_gdbm.gdbm.firstkey
@@ -687,14 +675,21 @@ gdbm__enter__(PyObject *self, PyObject *args)
return Py_NewRef(self);
}
+/*[clinic input]
+@critical_section
+_gdbm.gdbm.__exit__
+
+ *exc_info: array
+
+Close the database.
+[clinic start generated code]*/
+
static PyObject *
-gdbm__exit__(PyObject *self, PyObject *args)
+_gdbm_gdbm___exit___impl(gdbmobject *self, PyObject * const *exc_info,
+ Py_ssize_t exc_info_length)
+/*[clinic end generated code: output=4bb425e091228932 input=b22b90a00b22cf18]*/
{
- PyObject *result;
- Py_BEGIN_CRITICAL_SECTION(self);
- result = _gdbm_gdbm_close_impl((gdbmobject *)self);
- Py_END_CRITICAL_SECTION();
- return result;
+ return _gdbm_gdbm_close_impl(self);
}
static PyMethodDef gdbm_methods[] = {
@@ -708,7 +703,7 @@ static PyMethodDef gdbm_methods[] = {
_GDBM_GDBM_SETDEFAULT_METHODDEF
_GDBM_GDBM_CLEAR_METHODDEF
{"__enter__", gdbm__enter__, METH_NOARGS, NULL},
- {"__exit__", gdbm__exit__, METH_VARARGS, NULL},
+ _GDBM_GDBM___EXIT___METHODDEF
{NULL, NULL} /* sentinel */
};
@@ -855,6 +850,85 @@ static PyMethodDef _gdbm_module_methods[] = {
{ 0, 0 },
};
+PyDoc_STRVAR(gdbm_version_info__doc__,
+"_gdbm.gdbm_version_info\n\
+\n\
+GDBM version information as a named tuple.");
+
+static PyStructSequence_Field gdbm_version_info_fields[] = {
+ {"major", "Major release number"},
+ {"minor", "Minor release number"},
+ {"patch", "Patch release number"},
+ {0}
+};
+
+static PyStructSequence_Desc gdbm_version_info_desc = {
+ "_gdbm.gdbm_version_info", /* name */
+ gdbm_version_info__doc__, /* doc */
+ gdbm_version_info_fields, /* fields */
+ 3
+};
+
+static PyObject *
+make_gdbm_version_info(PyTypeObject *type, int major, int minor, int patch)
+{
+ PyObject *version;
+ int pos = 0;
+
+ version = PyStructSequence_New(type);
+ if (version == NULL) {
+ return NULL;
+ }
+
+#define SetItem(VALUE) \
+ PyStructSequence_SET_ITEM(version, pos++, VALUE); \
+ if (PyErr_Occurred()) { \
+ Py_DECREF(version); \
+ return NULL; \
+ }
+
+ SetItem(PyLong_FromLong(major))
+ SetItem(PyLong_FromLong(minor))
+ SetItem(PyLong_FromLong(patch))
+#undef SetItem
+
+ return version;
+}
+
+static int
+add_version_constants(PyObject *module)
+{
+ if (PyModule_AddStringConstant(module, "gdbm_version", gdbm_version) < 0) {
+ return -1;
+ }
+#if defined(GDBM_VERSION_MAJOR) && defined(GDBM_VERSION_MINOR) && \
+ defined(GDBM_VERSION_PATCH)
+ PyTypeObject *version_type;
+ version_type = PyStructSequence_NewType(&gdbm_version_info_desc);
+ if (version_type == NULL) {
+ return -1;
+ }
+ if (PyModule_Add(module, "GDBM_VERSION_INFO",
+ make_gdbm_version_info(version_type, GDBM_VERSION_MAJOR,
+ GDBM_VERSION_MINOR,
+ GDBM_VERSION_PATCH)) < 0)
+ {
+ Py_DECREF(version_type);
+ return -1;
+ }
+ if (PyModule_Add(module, "gdbm_version_info",
+ make_gdbm_version_info(version_type, gdbm_version_number[0],
+ gdbm_version_number[1],
+ gdbm_version_number[2])) < 0)
+ {
+ Py_DECREF(version_type);
+ return -1;
+ }
+ Py_DECREF(version_type);
+#endif
+ return 0;
+}
+
static int
_gdbm_exec(PyObject *module)
{
@@ -876,14 +950,9 @@ _gdbm_exec(PyObject *module)
return -1;
}
-#if defined(GDBM_VERSION_MAJOR) && defined(GDBM_VERSION_MINOR) && \
- defined(GDBM_VERSION_PATCH)
- PyObject *obj = Py_BuildValue("iii", GDBM_VERSION_MAJOR,
- GDBM_VERSION_MINOR, GDBM_VERSION_PATCH);
- if (PyModule_Add(module, "_GDBM_VERSION", obj) < 0) {
+ if (add_version_constants(module) < 0) {
return -1;
}
-#endif
return 0;
}
diff --git a/Modules/_hashopenssl.c b/Modules/_hashopenssl.c
index f895c9037485c43..9d7602b39d7b938 100644
--- a/Modules/_hashopenssl.c
+++ b/Modules/_hashopenssl.c
@@ -27,6 +27,7 @@
#include "pycore_strhex.h" // _Py_strhex()
#include "pycore_pyatomic_ft_wrappers.h" // FT_ATOMIC_LOAD_PTR_RELAXED
#include "hashlib.h"
+#include "_openssl_mem.h"
/* EVP is the preferred interface to hashing in OpenSSL */
#include
@@ -692,43 +693,46 @@ static PY_EVP_MD *
get_openssl_evp_md_by_utf8name(_hashlibstate *state, const char *name,
Py_hash_type py_ht)
{
- PY_EVP_MD *digest = NULL, *other_digest = NULL;
+ PY_EVP_MD *digest = NULL, *fresh = NULL;
py_hashentry_t *entry = _Py_hashtable_get(state->hashtable, name);
+ int fips = !disable_fips_property(py_ht);
if (entry != NULL) {
- if (!disable_fips_property(py_ht)) {
- digest = FT_ATOMIC_LOAD_PTR_RELAXED(entry->evp);
- if (digest == NULL) {
- digest = PY_EVP_MD_fetch(entry->ossl_name, NULL);
-#ifdef Py_GIL_DISABLED
- // exchange just in case another thread did same thing at same time
- other_digest = _Py_atomic_exchange_ptr(&entry->evp, (void *)digest);
-#else
- entry->evp = digest;
-#endif
- }
- }
- else {
- digest = FT_ATOMIC_LOAD_PTR_RELAXED(entry->evp_nosecurity);
- if (digest == NULL) {
- digest = PY_EVP_MD_fetch(entry->ossl_name, "-fips");
-#ifdef Py_GIL_DISABLED
- // exchange just in case another thread did same thing at same time
- other_digest = _Py_atomic_exchange_ptr(&entry->evp_nosecurity, (void *)digest);
-#else
- entry->evp_nosecurity = digest;
-#endif
+ PY_EVP_MD **cached = fips ? &entry->evp : &entry->evp_nosecurity;
+ digest = FT_ATOMIC_LOAD_PTR_RELAXED(*cached);
+ if (digest == NULL) {
+ fresh = PY_EVP_MD_fetch(entry->ossl_name, fips ? NULL : "-fips");
+ if (fresh != NULL) {
+ /*
+ * Publish a freshly fetched digest into the cache exactly once.
+ *
+ * On the first publication, 'cached' adopts the 'fresh' ref.
+ * If another thread wins the race, 'fresh' is released and
+ * the cached digest is used instead.
+ *
+ * See https://github.com/python/cpython/issues/128657
+ * and https://github.com/python/cpython/issues/149816.
+ */
+ PY_EVP_MD *expected = NULL;
+ if (_Py_atomic_compare_exchange_ptr(cached, &expected, (void *)fresh)) {
+ digest = fresh; // we won: 'cached' now owns the fresh digest
+ }
+ else {
+ PY_EVP_MD_free(fresh); // we lost: discard the fresh digest
+ digest = expected; // reuse the winner's digest
+ }
}
}
- // if another thread same thing at same time make sure we got same ptr
- assert(other_digest == NULL || other_digest == digest);
- if (digest != NULL && other_digest == NULL) {
+ /* Hand the caller its own reference; the cache keeps its own. Valid
+ * whether `digest` was already cached, freshly published by this
+ * thread, or published by a thread that won the race. */
+ if (digest != NULL) {
PY_EVP_MD_up_ref(digest);
}
}
else {
// Fall back for looking up an unindexed OpenSSL specific name.
- const char *props = disable_fips_property(py_ht) ? "-fips" : NULL;
+ const char *props = fips ? NULL : "-fips";
(void)props; // will only be used in OpenSSL 3.0 and later
digest = PY_EVP_MD_fetch(name, props);
}
@@ -846,6 +850,12 @@ new_hash_object(PyTypeObject *type)
return retval;
}
+/*
+ * Update the digest context of 'self' with 'len' bytes from 'vp'.
+ *
+ * Return 0 on success and -1 if EVP_DigestUpdate() failed. No exception
+ * is set, so that this can be called without an attached thread state.
+ */
static int
_hashlib_HASH_hash(HASHobject *self, const void *vp, Py_ssize_t len)
{
@@ -857,7 +867,6 @@ _hashlib_HASH_hash(HASHobject *self, const void *vp, Py_ssize_t len)
else
process = Py_SAFE_DOWNCAST(len, Py_ssize_t, unsigned int);
if (!EVP_DigestUpdate(self->ctx, (const void*)cp, process)) {
- notify_ssl_error_occurred_in(Py_STRINGIFY(EVP_DigestUpdate));
return -1;
}
len -= process;
@@ -990,7 +999,11 @@ _hashlib_HASH_update_impl(HASHobject *self, PyObject *obj)
result = _hashlib_HASH_hash(self, view.buf, view.len)
);
PyBuffer_Release(&view);
- return result < 0 ? NULL : Py_None;
+ if (result < 0) {
+ notify_ssl_error_occurred_in(Py_STRINGIFY(EVP_DigestUpdate));
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
static PyMethodDef HASH_methods[] = {
@@ -1304,7 +1317,7 @@ _hashlib_HASH(_hashlibstate *state, const char *digestname, PyObject *data_obj,
result = _hashlib_HASH_hash(self, view.buf, view.len)
);
if (result == -1) {
- assert(PyErr_Occurred());
+ notify_ssl_error_occurred_in(Py_STRINGIFY(EVP_DigestUpdate));
Py_CLEAR(self);
goto exit;
}
@@ -1975,16 +1988,6 @@ hashlib_HMAC_get_hashlib_digest_name(HMACobject *self)
#endif
}
-static int
-hashlib_openssl_HMAC_update_once(PY_HMAC_CTX_TYPE *ctx, const Py_buffer *v)
-{
- if (!PY_HMAC_update(ctx, (const unsigned char *)v->buf, (size_t)v->len)) {
- notify_smart_ssl_error_occurred_in(Py_STRINGIFY(PY_HMAC_update));
- return -1;
- }
- return 0;
-}
-
/* Thin wrapper around PY_HMAC_CTX_free that allows to pass a NULL 'ctx'. */
static inline void
hashlib_openssl_HMAC_CTX_free(PY_HMAC_CTX_TYPE *ctx)
@@ -2239,10 +2242,15 @@ _hmac_update(HMACobject *self, PyObject *obj)
GET_BUFFER_VIEW_OR_ERROR(obj, &view, return -1);
HASHLIB_EXTERNAL_INSTRUCTIONS_LOCKED(
self, view.len,
- r = hashlib_openssl_HMAC_update_once(self->ctx, &view)
+ r = PY_HMAC_update(self->ctx, (const unsigned char *)view.buf,
+ (size_t)view.len)
);
PyBuffer_Release(&view);
- return r;
+ if (r == 0) {
+ notify_smart_ssl_error_occurred_in(Py_STRINGIFY(PY_HMAC_update));
+ return -1;
+ }
+ return 0;
}
/*[clinic input]
@@ -2933,5 +2941,6 @@ static struct PyModuleDef _hashlibmodule = {
PyMODINIT_FUNC
PyInit__hashlib(void)
{
+ _PyOpenSSL_SetupMemFunctions();
return PyModuleDef_Init(&_hashlibmodule);
}
diff --git a/Modules/_interpchannelsmodule.c b/Modules/_interpchannelsmodule.c
index 7b31b1f0c85d264..930d7276a3ed45e 100644
--- a/Modules/_interpchannelsmodule.c
+++ b/Modules/_interpchannelsmodule.c
@@ -2634,6 +2634,17 @@ _channelid_from_xid(_PyXIData_t *data)
static int
_channelid_shared(PyThreadState *tstate, PyObject *obj, _PyXIData_t *data)
{
+ module_state *st = _get_current_module_state();
+ if (st == NULL) {
+ return -1;
+ }
+ if (!PyObject_TypeCheck(obj, st->ChannelIDType)) {
+ PyErr_Format(PyExc_TypeError,
+ "'_id' attribute must be an %N object, not %T",
+ st->ChannelIDType, obj);
+ return -1;
+ }
+
if (_PyXIData_InitWithSize(
data, tstate->interp, sizeof(struct _channelid_xid), obj,
_channelid_from_xid
diff --git a/Modules/_interpretersmodule.c b/Modules/_interpretersmodule.c
index 15bfd35a80806ce..454db063d18b6a0 100644
--- a/Modules/_interpretersmodule.c
+++ b/Modules/_interpretersmodule.c
@@ -802,17 +802,27 @@ get_summary(PyInterpreterState *interp)
}
-// Not converted to Argument Clinic because the function uses ``**kwargs``.
+/*[clinic input]
+_interpreters.new_config
+
+ name: str(c_default="NULL") = 'isolated'
+ /
+ **overrides: dict
+
+Return a representation of a new PyInterpreterConfig.
+
+The name determines the initial values of the config. Supported named
+configs are: default, isolated, legacy, and empty.
+
+Any keyword arguments are set on the corresponding config fields,
+overriding the initial values.
+[clinic start generated code]*/
+
static PyObject *
-interp_new_config(PyObject *self, PyObject *args, PyObject *kwds)
+_interpreters_new_config_impl(PyObject *module, const char *name,
+ PyObject *overrides)
+/*[clinic end generated code: output=90ca53e5c8f66e31 input=67a5a2832894a72b]*/
{
- const char *name = NULL;
- if (!PyArg_ParseTuple(args, "|s:" MODULE_NAME_STR ".new_config", &name))
- {
- return NULL;
- }
- PyObject *overrides = kwds;
-
PyInterpreterConfig config;
if (init_named_config(&config, name) < 0) {
return NULL;
@@ -834,18 +844,6 @@ interp_new_config(PyObject *self, PyObject *args, PyObject *kwds)
return configobj;
}
-PyDoc_STRVAR(new_config_doc,
-"new_config($module, name='isolated', /, **overrides)\n\
---\n\
-\n\
-Return a representation of a new PyInterpreterConfig.\n\
-\n\
-The name determines the initial values of the config. Supported named\n\
-configs are: default, isolated, legacy, and empty.\n\
-\n\
-Any keyword arguments are set on the corresponding config fields,\n\
-overriding the initial values.");
-
/*[clinic input]
_interpreters.create
@@ -1558,8 +1556,7 @@ _interpreters_capture_exception_impl(PyObject *module, PyObject *exc_arg)
static PyMethodDef module_functions[] = {
- {"new_config", _PyCFunction_CAST(interp_new_config),
- METH_VARARGS | METH_KEYWORDS, new_config_doc},
+ _INTERPRETERS_NEW_CONFIG_METHODDEF
_INTERPRETERS_CREATE_METHODDEF
_INTERPRETERS_DESTROY_METHODDEF
diff --git a/Modules/_io/_iomodule.c b/Modules/_io/_iomodule.c
index 03e6fbe08889d47..0d28fe24fa0b3a7 100644
--- a/Modules/_io/_iomodule.c
+++ b/Modules/_io/_iomodule.c
@@ -94,10 +94,7 @@ mode. Other common values are 'w' for writing (truncating the file if
it already exists), 'x' for creating and writing to a new file, and
'a' for appending (which on some Unix systems, means that all writes
append to the end of the file regardless of the current seek position).
-In text mode, if encoding is not specified the encoding used is platform
-dependent: locale.getencoding() is called to get the current locale
-encoding. (For reading and writing raw bytes use binary mode and leave
-encoding unspecified.) The available modes are:
+The available modes are:
========= ==========================================================
Character Meaning
@@ -122,8 +119,7 @@ even when the underlying operating system doesn't. Files opened in
binary mode (appending 'b' to the mode argument) return contents as
bytes objects without any decoding. In text mode (the default, or when
't' is appended to the mode argument), the contents of the file are
-returned as strings, the bytes having been first decoded using a
-platform-dependent encoding or using the specified encoding if given.
+decoded using the encoding described below and returned as strings.
buffering is an optional integer used to set the buffering policy.
Pass 0 to switch buffering off (only allowed in binary mode), 1 to
@@ -140,10 +136,11 @@ argument is given, the default buffering policy works as follows:
use line buffering. Other text files use the policy described above
for binary files.
-encoding is the name of the encoding used to decode or encode the
-file. This should only be used in text mode. The default encoding is
-platform dependent, but any encoding supported by Python can be
-passed. See the codecs module for the list of supported encodings.
+encoding is the name of the encoding used to decode or encode the file.
+This should only be used in text mode. The default encoding is UTF-8;
+if UTF-8 Mode is disabled, the encoding returned by
+locale.getencoding() is used instead. See the codecs module for the
+list of supported encodings.
errors is an optional string that specifies how encoding errors are to
be handled---this argument should not be used in binary mode. Pass
@@ -200,7 +197,7 @@ static PyObject *
_io_open_impl(PyObject *module, PyObject *file, const char *mode,
int buffering, const char *encoding, const char *errors,
const char *newline, int closefd, PyObject *opener)
-/*[clinic end generated code: output=aefafc4ce2b46dc0 input=b3cefa70bef404b3]*/
+/*[clinic end generated code: output=aefafc4ce2b46dc0 input=5a005681afa02242]*/
{
size_t i;
diff --git a/Modules/_io/_iomodule.h b/Modules/_io/_iomodule.h
index 4ae487c8e2adf72..c9bbbf24bd466d7 100644
--- a/Modules/_io/_iomodule.h
+++ b/Modules/_io/_iomodule.h
@@ -4,6 +4,7 @@
#include "exports.h"
+#include "pycore_fileutils.h" // Py_off_t
#include "pycore_moduleobject.h" // _PyModule_GetState()
#include "pycore_typeobject.h" // _PyType_GetModuleState()
#include "structmember.h"
@@ -94,8 +95,6 @@ extern int _PyIO_trap_eintr(void);
#ifdef MS_WINDOWS
-/* Windows uses long long for offsets */
-typedef long long Py_off_t;
# define PyLong_AsOff_t PyLong_AsLongLong
# define PyLong_FromOff_t PyLong_FromLongLong
# define PY_OFF_T_MAX LLONG_MAX
@@ -106,7 +105,6 @@ typedef long long Py_off_t;
#else
/* Other platforms use off_t */
-typedef off_t Py_off_t;
#if (SIZEOF_OFF_T == SIZEOF_SIZE_T)
# define PyLong_AsOff_t PyLong_AsSsize_t
# define PyLong_FromOff_t PyLong_FromSsize_t
diff --git a/Modules/_io/bufferedio.c b/Modules/_io/bufferedio.c
index 5537947f6a51c11..9e5a7216ee013b6 100644
--- a/Modules/_io/bufferedio.c
+++ b/Modules/_io/bufferedio.c
@@ -9,11 +9,11 @@
#include "Python.h"
#include "pycore_call.h" // _PyObject_CallNoArgs()
+#include "pycore_critical_section.h" // _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED()
#include "pycore_fileutils.h" // _PyFile_Flush
#include "pycore_object.h" // _PyObject_GC_UNTRACK()
#include "pycore_pyerrors.h" // _Py_FatalErrorFormat()
#include "pycore_pylifecycle.h" // _Py_IsInterpreterFinalizing()
-#include "pycore_weakref.h" // FT_CLEAR_WEAKREFS()
#include "_iomodule.h"
@@ -60,6 +60,11 @@ _bufferediobase_readinto_generic(PyObject *self, Py_buffer *buffer, char readint
if (data == NULL)
return NULL;
+ /* Non-blocking stream with no data available */
+ if (data == Py_None) {
+ return data;
+ }
+
if (!PyBytes_Check(data)) {
Py_DECREF(data);
PyErr_SetString(PyExc_TypeError, "read() should return bytes");
@@ -260,8 +265,6 @@ typedef struct {
Py_ssize_t buffer_size;
Py_ssize_t buffer_mask;
- PyObject *dict;
- PyObject *weakreflist;
} buffered;
#define buffered_CAST(op) ((buffered *)(op))
@@ -417,7 +420,7 @@ buffered_clear(PyObject *op)
buffered *self = buffered_CAST(op);
self->ok = 0;
Py_CLEAR(self->raw);
- Py_CLEAR(self->dict);
+ PyObject_ClearManagedDict(op);
return 0;
}
@@ -431,7 +434,7 @@ buffered_dealloc(PyObject *op)
return;
_PyObject_GC_UNTRACK(self);
self->ok = 0;
- FT_CLEAR_WEAKREFS(op, self->weakreflist);
+ PyObject_ClearWeakRefs(op);
if (self->buffer) {
PyMem_Free(self->buffer);
self->buffer = NULL;
@@ -467,8 +470,7 @@ buffered_traverse(PyObject *op, visitproc visit, void *arg)
buffered *self = buffered_CAST(op);
Py_VISIT(Py_TYPE(self));
Py_VISIT(self->raw);
- Py_VISIT(self->dict);
- return 0;
+ return PyObject_VisitManagedDict(op, visit, arg);
}
/* Because this can call arbitrary code, it shouldn't be called when
@@ -1205,109 +1207,113 @@ _io__Buffered_readinto1_impl(buffered *self, Py_buffer *buffer)
static PyObject *
_buffered_readline(buffered *self, Py_ssize_t limit)
{
- PyObject *res = NULL;
- PyObject *chunks = NULL;
- Py_ssize_t n;
- const char *start, *s, *end;
+ _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
CHECK_CLOSED(self, "readline of closed file")
/* First, try to find a line in the buffer. This can run unlocked because
the calls to the C API are simple enough that they can't trigger
any thread switch. */
- n = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t);
- if (limit >= 0 && n > limit)
+ Py_ssize_t n = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t);
+ if (limit >= 0 && n > limit) {
n = limit;
- start = self->buffer + self->pos;
- s = memchr(start, '\n', n);
+ }
+ const char *start = self->buffer + self->pos;
+ const char *s = memchr(start, '\n', n);
if (s != NULL) {
- res = PyBytes_FromStringAndSize(start, s - start + 1);
- if (res != NULL)
- self->pos += s - start + 1;
- goto end_unlocked;
+ n = s - start + 1;
+ PyObject *res = PyBytes_FromStringAndSize(start, n);
+ if (res == NULL) {
+ return NULL;
+ }
+ self->pos += n;
+ return res;
}
+
if (n == limit) {
- res = PyBytes_FromStringAndSize(start, n);
- if (res != NULL)
- self->pos += n;
- goto end_unlocked;
+ PyObject *res = PyBytes_FromStringAndSize(start, n);
+ if (res == NULL) {
+ return NULL;
+ }
+ self->pos += n;
+ return res;
}
- if (!ENTER_BUFFERED(self))
- goto end_unlocked;
+ PyBytesWriter *writer = NULL;
+ int locked = 0;
+ if (!ENTER_BUFFERED(self)) {
+ goto error;
+ }
+ locked = 1;
/* Now we try to get some more from the raw stream */
- chunks = PyList_New(0);
- if (chunks == NULL)
- goto end;
+ writer = PyBytesWriter_Create(0);
+ if (writer == NULL) {
+ goto error;
+ }
+
if (n > 0) {
- res = PyBytes_FromStringAndSize(start, n);
- if (res == NULL)
- goto end;
- if (PyList_Append(chunks, res) < 0) {
- Py_CLEAR(res);
- goto end;
+ if (PyBytesWriter_WriteBytes(writer, start, n) < 0) {
+ goto error;
}
- Py_CLEAR(res);
self->pos += n;
- if (limit >= 0)
+ if (limit >= 0) {
limit -= n;
+ }
}
if (self->writable) {
- PyObject *r = buffered_flush_and_rewind_unlocked(self);
- if (r == NULL)
- goto end;
- Py_DECREF(r);
+ PyObject *res = buffered_flush_and_rewind_unlocked(self);
+ if (res == NULL) {
+ goto error;
+ }
+ Py_DECREF(res);
}
for (;;) {
_bufferedreader_reset_buf(self);
n = _bufferedreader_fill_buffer(self);
- if (n == -1)
- goto end;
- if (n <= 0)
+ if (n == -1) {
+ goto error;
+ }
+ if (n <= 0) {
break;
- if (limit >= 0 && n > limit)
+ }
+ if (limit >= 0 && n > limit) {
n = limit;
+ }
start = self->buffer;
- end = start + n;
- s = start;
- while (s < end) {
- if (*s++ == '\n') {
- res = PyBytes_FromStringAndSize(start, s - start);
- if (res == NULL)
- goto end;
- self->pos = s - start;
- goto found;
+ const char *newline = memchr(start, '\n', n);
+ if (newline != NULL) {
+ n = newline - start + 1;
+ if (PyBytesWriter_WriteBytes(writer, start, n) < 0) {
+ goto error;
}
+ self->pos = n;
+ goto found;
+ }
+
+ if (PyBytesWriter_WriteBytes(writer, start, n) < 0) {
+ goto error;
}
- res = PyBytes_FromStringAndSize(start, n);
- if (res == NULL)
- goto end;
if (n == limit) {
self->pos = n;
break;
}
- if (PyList_Append(chunks, res) < 0) {
- Py_CLEAR(res);
- goto end;
- }
- Py_CLEAR(res);
- if (limit >= 0)
+ if (limit >= 0) {
limit -= n;
+ }
}
-found:
- if (res != NULL && PyList_Append(chunks, res) < 0) {
- Py_CLEAR(res);
- goto end;
- }
- Py_XSETREF(res, PyBytes_Join((PyObject *)&_Py_SINGLETON(bytes_empty), chunks));
-end:
+found:
LEAVE_BUFFERED(self)
-end_unlocked:
- Py_XDECREF(chunks);
- return res;
+ return PyBytesWriter_Finish(writer);
+
+error:
+ PyBytesWriter_Discard(writer);
+ if (locked) {
+ LEAVE_BUFFERED(self)
+ }
+ return NULL;
}
/*[clinic input]
@@ -2246,8 +2252,6 @@ typedef struct {
PyObject_HEAD
buffered *reader;
buffered *writer;
- PyObject *dict;
- PyObject *weakreflist;
} rwpair;
#define rwpair_CAST(op) ((rwpair *)(op))
@@ -2283,20 +2287,25 @@ _io_BufferedRWPair___init___impl(rwpair *self, PyObject *reader,
return -1;
}
- self->reader = (buffered *) PyObject_CallFunction(
+ buffered *new_reader = (buffered *) PyObject_CallFunction(
(PyObject *)state->PyBufferedReader_Type,
"On", reader, buffer_size);
- if (self->reader == NULL)
+ if (new_reader == NULL) {
return -1;
+ }
- self->writer = (buffered *) PyObject_CallFunction(
+ buffered *new_writer = (buffered *) PyObject_CallFunction(
(PyObject *)state->PyBufferedWriter_Type,
"On", writer, buffer_size);
- if (self->writer == NULL) {
- Py_CLEAR(self->reader);
+ if (new_writer == NULL) {
+ Py_DECREF(new_reader);
return -1;
}
+ /* Release a previous writer before a previous reader, see
+ bufferedrwpair_clear(). */
+ Py_XSETREF(self->writer, new_writer);
+ Py_XSETREF(self->reader, new_reader);
return 0;
}
@@ -2305,19 +2314,19 @@ bufferedrwpair_traverse(PyObject *op, visitproc visit, void *arg)
{
rwpair *self = rwpair_CAST(op);
Py_VISIT(Py_TYPE(self));
- Py_VISIT(self->dict);
Py_VISIT(self->reader);
Py_VISIT(self->writer);
- return 0;
+ return PyObject_VisitManagedDict(op, visit, arg);
}
static int
bufferedrwpair_clear(PyObject *op)
{
rwpair *self = rwpair_CAST(op);
- Py_CLEAR(self->reader);
+ /* Let the writer flush before the reader closes a shared raw stream. */
Py_CLEAR(self->writer);
- Py_CLEAR(self->dict);
+ Py_CLEAR(self->reader);
+ PyObject_ClearManagedDict(op);
return 0;
}
@@ -2327,100 +2336,168 @@ bufferedrwpair_dealloc(PyObject *op)
rwpair *self = rwpair_CAST(op);
PyTypeObject *tp = Py_TYPE(self);
_PyObject_GC_UNTRACK(self);
- FT_CLEAR_WEAKREFS(op, self->weakreflist);
+ PyObject_ClearWeakRefs(op);
(void)bufferedrwpair_clear(op);
tp->tp_free(self);
Py_DECREF(tp);
}
+/* Call the method of the underlying reader or writer. The argument is
+ only passed if it is not NULL, so that the default of that method is
+ used otherwise. */
static PyObject *
-_forward_call(buffered *self, PyObject *name, PyObject *args)
+_forward_call(buffered *self, PyObject *name, PyObject *arg)
{
- PyObject *func, *ret;
if (self == NULL) {
PyErr_SetString(PyExc_ValueError,
"I/O operation on uninitialized object");
return NULL;
}
- func = PyObject_GetAttr((PyObject *)self, name);
- if (func == NULL) {
- PyErr_SetObject(PyExc_AttributeError, name);
- return NULL;
+ if (arg == NULL) {
+ return PyObject_CallMethodNoArgs((PyObject *)self, name);
}
+ return PyObject_CallMethodOneArg((PyObject *)self, name, arg);
+}
- ret = PyObject_CallObject(func, args);
- Py_DECREF(func);
- return ret;
+/*[clinic input]
+_io.BufferedRWPair.read
+ size: object(c_default="NULL") = -1
+ /
+[clinic start generated code]*/
+
+static PyObject *
+_io_BufferedRWPair_read_impl(rwpair *self, PyObject *size)
+/*[clinic end generated code: output=0668e3c5dbd3e93d input=eddb5e52aba9ebe5]*/
+{
+ return _forward_call(self->reader, &_Py_ID(read), size);
}
+/*[clinic input]
+_io.BufferedRWPair.peek
+ size: object(c_default="NULL") = 0
+ /
+[clinic start generated code]*/
+
static PyObject *
-bufferedrwpair_read(PyObject *op, PyObject *args)
+_io_BufferedRWPair_peek_impl(rwpair *self, PyObject *size)
+/*[clinic end generated code: output=190a267bd694efa0 input=36af95964bebe355]*/
{
- rwpair *self = rwpair_CAST(op);
- return _forward_call(self->reader, &_Py_ID(read), args);
+ return _forward_call(self->reader, &_Py_ID(peek), size);
}
+/*[clinic input]
+_io.BufferedRWPair.read1
+ size: object(c_default="NULL") = -1
+ /
+[clinic start generated code]*/
+
static PyObject *
-bufferedrwpair_peek(PyObject *op, PyObject *args)
+_io_BufferedRWPair_read1_impl(rwpair *self, PyObject *size)
+/*[clinic end generated code: output=17ec19608f2bb825 input=9e94db423e490b58]*/
{
- rwpair *self = rwpair_CAST(op);
- return _forward_call(self->reader, &_Py_ID(peek), args);
+ return _forward_call(self->reader, &_Py_ID(read1), size);
}
+/*[clinic input]
+_io.BufferedRWPair.readline
+ size: object(c_default="NULL") = -1
+ /
+
+Read and return a line from the stream.
+
+If size is specified, at most size bytes will be read.
+
+The line terminator is always b'\n'.
+[clinic start generated code]*/
+
static PyObject *
-bufferedrwpair_read1(PyObject *op, PyObject *args)
+_io_BufferedRWPair_readline_impl(rwpair *self, PyObject *size)
+/*[clinic end generated code: output=ee5bb2364231e6e1 input=1c552272a69db1ad]*/
{
- rwpair *self = rwpair_CAST(op);
- return _forward_call(self->reader, &_Py_ID(read1), args);
+ return _forward_call(self->reader, &_Py_ID(readline), size);
}
+/*[clinic input]
+_io.BufferedRWPair.readinto
+ buffer: object
+ /
+[clinic start generated code]*/
+
static PyObject *
-bufferedrwpair_readinto(PyObject *op, PyObject *args)
+_io_BufferedRWPair_readinto_impl(rwpair *self, PyObject *buffer)
+/*[clinic end generated code: output=16c86b071015f7a4 input=ccd86ce2666261f7]*/
{
- rwpair *self = rwpair_CAST(op);
- return _forward_call(self->reader, &_Py_ID(readinto), args);
+ return _forward_call(self->reader, &_Py_ID(readinto), buffer);
}
+/*[clinic input]
+_io.BufferedRWPair.readinto1
+ buffer: object
+ /
+[clinic start generated code]*/
+
static PyObject *
-bufferedrwpair_readinto1(PyObject *op, PyObject *args)
+_io_BufferedRWPair_readinto1_impl(rwpair *self, PyObject *buffer)
+/*[clinic end generated code: output=f1577b6f54c2b02a input=613d9bf127f88a4a]*/
{
- rwpair *self = rwpair_CAST(op);
- return _forward_call(self->reader, &_Py_ID(readinto1), args);
+ return _forward_call(self->reader, &_Py_ID(readinto1), buffer);
}
+/*[clinic input]
+_io.BufferedRWPair.write
+ buffer: object
+ /
+[clinic start generated code]*/
+
static PyObject *
-bufferedrwpair_write(PyObject *op, PyObject *args)
+_io_BufferedRWPair_write_impl(rwpair *self, PyObject *buffer)
+/*[clinic end generated code: output=6f7509a747410c68 input=66c602422e3ec36f]*/
{
- rwpair *self = rwpair_CAST(op);
- return _forward_call(self->writer, &_Py_ID(write), args);
+ return _forward_call(self->writer, &_Py_ID(write), buffer);
}
+/*[clinic input]
+_io.BufferedRWPair.flush
+[clinic start generated code]*/
+
static PyObject *
-bufferedrwpair_flush(PyObject *op, PyObject *Py_UNUSED(dummy))
+_io_BufferedRWPair_flush_impl(rwpair *self)
+/*[clinic end generated code: output=0b2dcbe828718d6b input=e853da796ee61df1]*/
{
- rwpair *self = rwpair_CAST(op);
return _forward_call(self->writer, &_Py_ID(flush), NULL);
}
+/*[clinic input]
+_io.BufferedRWPair.readable
+[clinic start generated code]*/
+
static PyObject *
-bufferedrwpair_readable(PyObject *op, PyObject *Py_UNUSED(dummy))
+_io_BufferedRWPair_readable_impl(rwpair *self)
+/*[clinic end generated code: output=615967d4aa58f122 input=0475ed73d0a3167f]*/
{
- rwpair *self = rwpair_CAST(op);
return _forward_call(self->reader, &_Py_ID(readable), NULL);
}
+/*[clinic input]
+_io.BufferedRWPair.writable
+[clinic start generated code]*/
+
static PyObject *
-bufferedrwpair_writable(PyObject *op, PyObject *Py_UNUSED(dummy))
+_io_BufferedRWPair_writable_impl(rwpair *self)
+/*[clinic end generated code: output=c5a43c84e0195c11 input=3cfd44fb4757082f]*/
{
- rwpair *self = rwpair_CAST(op);
return _forward_call(self->writer, &_Py_ID(writable), NULL);
}
+/*[clinic input]
+_io.BufferedRWPair.close
+[clinic start generated code]*/
+
static PyObject *
-bufferedrwpair_close(PyObject *op, PyObject *Py_UNUSED(dummy))
+_io_BufferedRWPair_close_impl(rwpair *self)
+/*[clinic end generated code: output=5924ba5ecc78752a input=4087d69f2d8fc368]*/
{
- rwpair *self = rwpair_CAST(op);
PyObject *exc = NULL;
PyObject *ret = _forward_call(self->writer, &_Py_ID(close), NULL);
if (ret == NULL) {
@@ -2437,10 +2514,14 @@ bufferedrwpair_close(PyObject *op, PyObject *Py_UNUSED(dummy))
return ret;
}
+/*[clinic input]
+_io.BufferedRWPair.isatty
+[clinic start generated code]*/
+
static PyObject *
-bufferedrwpair_isatty(PyObject *op, PyObject *Py_UNUSED(dummy))
+_io_BufferedRWPair_isatty_impl(rwpair *self)
+/*[clinic end generated code: output=d017c621ed879cb7 input=92833e3d60586e14]*/
{
- rwpair *self = rwpair_CAST(op);
PyObject *ret = _forward_call(self->writer, &_Py_ID(isatty), NULL);
if (ret != Py_False) {
@@ -2452,10 +2533,15 @@ bufferedrwpair_isatty(PyObject *op, PyObject *Py_UNUSED(dummy))
return _forward_call(self->reader, &_Py_ID(isatty), NULL);
}
+/*[clinic input]
+@getter
+_io.BufferedRWPair.closed
+[clinic start generated code]*/
+
static PyObject *
-bufferedrwpair_closed_get(PyObject *op, void *Py_UNUSED(dummy))
+_io_BufferedRWPair_closed_get_impl(rwpair *self)
+/*[clinic end generated code: output=4117400c74766f21 input=8248430ac54e5b25]*/
{
- rwpair *self = rwpair_CAST(op);
if (self->writer == NULL) {
PyErr_SetString(PyExc_RuntimeError,
"the BufferedRWPair object is being garbage-collected");
@@ -2576,8 +2662,6 @@ static PyMethodDef bufferedreader_methods[] = {
static PyMemberDef bufferedreader_members[] = {
{"raw", _Py_T_OBJECT, offsetof(buffered, raw), Py_READONLY},
{"_finalizing", Py_T_BOOL, offsetof(buffered, finalizing), 0},
- {"__weaklistoffset__", Py_T_PYSSIZET, offsetof(buffered, weakreflist), Py_READONLY},
- {"__dictoffset__", Py_T_PYSSIZET, offsetof(buffered, dict), Py_READONLY},
{NULL}
};
@@ -2635,8 +2719,6 @@ static PyMethodDef bufferedwriter_methods[] = {
static PyMemberDef bufferedwriter_members[] = {
{"raw", _Py_T_OBJECT, offsetof(buffered, raw), Py_READONLY},
{"_finalizing", Py_T_BOOL, offsetof(buffered, finalizing), 0},
- {"__weaklistoffset__", Py_T_PYSSIZET, offsetof(buffered, weakreflist), Py_READONLY},
- {"__dictoffset__", Py_T_PYSSIZET, offsetof(buffered, dict), Py_READONLY},
{NULL}
};
@@ -2670,32 +2752,27 @@ PyType_Spec _Py_bufferedwriter_spec = {
};
static PyMethodDef bufferedrwpair_methods[] = {
- {"read", bufferedrwpair_read, METH_VARARGS},
- {"peek", bufferedrwpair_peek, METH_VARARGS},
- {"read1", bufferedrwpair_read1, METH_VARARGS},
- {"readinto", bufferedrwpair_readinto, METH_VARARGS},
- {"readinto1", bufferedrwpair_readinto1, METH_VARARGS},
+ _IO_BUFFEREDRWPAIR_READ_METHODDEF
+ _IO_BUFFEREDRWPAIR_PEEK_METHODDEF
+ _IO_BUFFEREDRWPAIR_READ1_METHODDEF
+ _IO_BUFFEREDRWPAIR_READLINE_METHODDEF
+ _IO_BUFFEREDRWPAIR_READINTO_METHODDEF
+ _IO_BUFFEREDRWPAIR_READINTO1_METHODDEF
- {"write", bufferedrwpair_write, METH_VARARGS},
- {"flush", bufferedrwpair_flush, METH_NOARGS},
+ _IO_BUFFEREDRWPAIR_WRITE_METHODDEF
+ _IO_BUFFEREDRWPAIR_FLUSH_METHODDEF
- {"readable", bufferedrwpair_readable, METH_NOARGS},
- {"writable", bufferedrwpair_writable, METH_NOARGS},
+ _IO_BUFFEREDRWPAIR_READABLE_METHODDEF
+ _IO_BUFFEREDRWPAIR_WRITABLE_METHODDEF
- {"close", bufferedrwpair_close, METH_NOARGS},
- {"isatty", bufferedrwpair_isatty, METH_NOARGS},
+ _IO_BUFFEREDRWPAIR_CLOSE_METHODDEF
+ _IO_BUFFEREDRWPAIR_ISATTY_METHODDEF
{NULL, NULL}
};
-static PyMemberDef bufferedrwpair_members[] = {
- {"__weaklistoffset__", Py_T_PYSSIZET, offsetof(rwpair, weakreflist), Py_READONLY},
- {"__dictoffset__", Py_T_PYSSIZET, offsetof(rwpair, dict), Py_READONLY},
- {NULL}
-};
-
static PyGetSetDef bufferedrwpair_getset[] = {
- {"closed", bufferedrwpair_closed_get, NULL, NULL},
+ _IO_BUFFEREDRWPAIR_CLOSED_GETSETDEF
{NULL}
};
@@ -2705,7 +2782,6 @@ static PyType_Slot bufferedrwpair_slots[] = {
{Py_tp_traverse, bufferedrwpair_traverse},
{Py_tp_clear, bufferedrwpair_clear},
{Py_tp_methods, bufferedrwpair_methods},
- {Py_tp_members, bufferedrwpair_members},
{Py_tp_getset, bufferedrwpair_getset},
{Py_tp_init, _io_BufferedRWPair___init__},
{0, NULL},
@@ -2752,8 +2828,6 @@ static PyMethodDef bufferedrandom_methods[] = {
static PyMemberDef bufferedrandom_members[] = {
{"raw", _Py_T_OBJECT, offsetof(buffered, raw), Py_READONLY},
{"_finalizing", Py_T_BOOL, offsetof(buffered, finalizing), 0},
- {"__weaklistoffset__", Py_T_PYSSIZET, offsetof(buffered, weakreflist), Py_READONLY},
- {"__dictoffset__", Py_T_PYSSIZET, offsetof(buffered, dict), Py_READONLY},
{NULL}
};
diff --git a/Modules/_io/bytesio.c b/Modules/_io/bytesio.c
index 3d14ec3f8f94a92..fa828f218928990 100644
--- a/Modules/_io/bytesio.c
+++ b/Modules/_io/bytesio.c
@@ -1,9 +1,10 @@
#include "Python.h"
+#include "pycore_bytesobject.h" // _PyBytes_ResizeKeepOnError()
#include "pycore_critical_section.h" // Py_BEGIN_CRITICAL_SECTION()
+#include "pycore_list.h" // _PyList_AppendTakeRef()
#include "pycore_object.h"
#include "pycore_pyatomic_ft_wrappers.h"
#include "pycore_sysmodule.h" // _PySys_GetSizeOf()
-#include "pycore_weakref.h" // FT_CLEAR_WEAKREFS()
#include // offsetof()
#include "_iomodule.h"
@@ -19,8 +20,6 @@ typedef struct {
PyObject *buf;
Py_ssize_t pos;
Py_ssize_t string_size;
- PyObject *dict;
- PyObject *weakreflist;
Py_ssize_t exports;
#ifdef Py_GIL_DISABLED
int buf_shared;
@@ -37,10 +36,11 @@ typedef struct {
#define bytesiobuf_CAST(op) ((bytesiobuf *)(op))
/* The bytesio object can be in three states:
- * Py_REFCNT(buf) == 1, exports == 0.
- * Py_REFCNT(buf) > 1. exports == 0,
+ * Py_REFCNT(buf) == 1, the hash of buf is not cached, exports == 0.
+ * Py_REFCNT(buf) > 1 or the hash of buf is cached. exports == 0,
first modification or export causes the internal buffer copying.
- * exports > 0. Py_REFCNT(buf) == 1, any modifications are forbidden.
+ * exports > 0. Any modifications are forbidden. Every exported buffer
+ keeps a reference to buf, so it outlives closing of the bytesio object.
*/
static int
@@ -74,10 +74,19 @@ check_exports(bytesio *self)
return NULL; \
}
+/* If the hash value is cached, the internal bytes object was already used in
+ Python somehow (ex: as a dictionary key). Modifying it in place would leave
+ the hash of the old contents, even if nothing else references it anymore. */
+#define HASHED_BUF(self) \
+ (_PyBytes_GET_CACHED_HASH((PyBytesObject *)(self)->buf) != -1)
+
#ifdef Py_GIL_DISABLED
-#define SHARED_BUF(self) ((self)->buf_shared || !_PyObject_IsUniquelyReferenced((self)->buf))
+#define SHARED_BUF(self) \
+ ((self)->buf_shared || !_PyObject_IsUniquelyReferenced((self)->buf) \
+ || HASHED_BUF(self))
#else
-#define SHARED_BUF(self) (!_PyObject_IsUniquelyReferenced((self)->buf))
+#define SHARED_BUF(self) \
+ (!_PyObject_IsUniquelyReferenced((self)->buf) || HASHED_BUF(self))
#endif
static inline void
@@ -107,7 +116,7 @@ resize_unshared_buffer_lock_held(bytesio *self, Py_ssize_t size)
Callers must detach first. */
assert(!self->buf_shared);
#endif
- int ret = _PyBytes_Resize(&self->buf, size);
+ int ret = _PyBytes_ResizeKeepOnError(&self->buf, size);
if (ret == 0) {
clear_shared_buf(self);
}
@@ -209,6 +218,9 @@ resize_buffer_lock_held(bytesio *self, size_t size)
/* Major upsize; resize up to exact size */
alloc = size + 1;
}
+ if (alloc > PY_SSIZE_T_MAX) {
+ goto overflow;
+ }
if (SHARED_BUF(self)) {
if (unshare_buffer_lock_held(self, alloc) < 0)
@@ -266,6 +278,7 @@ write_bytes_lock_held(bytesio *self, PyObject *b)
goto done;
}
}
+ assert(_PyBytes_IsMutable(self->buf));
if (self->pos > self->string_size) {
/* In case of overseek, pad with null bytes the buffer region between
@@ -295,20 +308,19 @@ write_bytes_lock_held(bytesio *self, PyObject *b)
return len;
}
-static PyObject *
-bytesio_get_closed(PyObject *op, void *Py_UNUSED(closure))
+/*[clinic input]
+@critical_section
+@getter
+_io.BytesIO.closed -> bool
+
+True if the file is closed.
+[clinic start generated code]*/
+
+static int
+_io_BytesIO_closed_get_impl(bytesio *self)
+/*[clinic end generated code: output=7cdc647cc7a71683 input=0687f923344225ee]*/
{
- PyObject *ret;
- bytesio *self = bytesio_CAST(op);
- Py_BEGIN_CRITICAL_SECTION(self);
- if (self->buf == NULL) {
- ret = Py_True;
- }
- else {
- ret = Py_False;
- }
- Py_END_CRITICAL_SECTION();
- return ret;
+ return self->buf == NULL;
}
/*[clinic input]
@@ -484,7 +496,7 @@ peek_bytes_lock_held(bytesio *self, Py_ssize_t size)
is beyond the size of self->buf. Assert above validates size is always in
bounds. When self->pos is out of bounds calling code sets size to 0. */
if (size == 0) {
- return PyBytes_FromStringAndSize(NULL, 0);
+ return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
}
output = PyBytes_AS_STRING(self->buf) + self->pos;
@@ -663,11 +675,9 @@ _io_BytesIO_readlines_impl(bytesio *self, PyObject *arg)
line = PyBytes_FromStringAndSize(output, n);
if (!line)
goto on_error;
- if (PyList_Append(result, line) == -1) {
- Py_DECREF(line);
+ if (_PyList_AppendTakeRef((PyListObject *)result, line) < 0) {
goto on_error;
}
- Py_DECREF(line);
size += n;
if (maxsize > 0 && size >= maxsize)
break;
@@ -714,7 +724,7 @@ _io_BytesIO_readinto_impl(bytesio *self, Py_buffer *buffer)
assert(self->pos + len <= PY_SSIZE_T_MAX);
assert(len >= 0);
- memcpy(buffer->buf, PyBytes_AS_STRING(self->buf) + self->pos, len);
+ memmove(buffer->buf, PyBytes_AS_STRING(self->buf) + self->pos, len);
self->pos += len;
return PyLong_FromSsize_t(len);
@@ -745,7 +755,7 @@ _io_BytesIO_truncate_impl(bytesio *self, PyObject *size)
new_size = self->pos;
}
else {
- new_size = PyLong_AsLong(size);
+ new_size = PyNumber_AsSsize_t(size, PyExc_OverflowError);
if (new_size == -1 && PyErr_Occurred()) {
return NULL;
}
@@ -754,24 +764,34 @@ _io_BytesIO_truncate_impl(bytesio *self, PyObject *size)
"negative size value %zd", new_size);
return NULL;
}
+ CHECK_CLOSED(self);
+ CHECK_EXPORTS(self);
}
if (new_size < self->string_size) {
+ Py_ssize_t old_string_size = self->string_size;
self->string_size = new_size;
- if (resize_buffer_lock_held(self, new_size) < 0)
+ if (resize_buffer_lock_held(self, new_size) < 0) {
+ self->string_size = old_string_size;
return NULL;
+ }
}
return PyLong_FromSsize_t(new_size);
}
+/*[clinic input]
+@critical_section
+_io.BytesIO.__next__ as bytesio_iternext
+[clinic start generated code]*/
+
static PyObject *
-bytesio_iternext_lock_held(PyObject *op)
+bytesio_iternext_impl(bytesio *self)
+/*[clinic end generated code: output=f530bdee3a720d48 input=7fb3a763efe11a21]*/
{
- _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op);
+ _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
Py_ssize_t n;
- bytesio *self = bytesio_CAST(op);
CHECK_CLOSED(self);
@@ -783,16 +803,6 @@ bytesio_iternext_lock_held(PyObject *op)
return read_bytes_lock_held(self, n);
}
-static PyObject *
-bytesio_iternext(PyObject *op)
-{
- PyObject *ret;
- Py_BEGIN_CRITICAL_SECTION(op);
- ret = bytesio_iternext_lock_held(op);
- Py_END_CRITICAL_SECTION();
- return ret;
-}
-
/*[clinic input]
@critical_section
_io.BytesIO.seek
@@ -925,7 +935,7 @@ static PyObject *
_io_BytesIO_close_impl(bytesio *self)
/*[clinic end generated code: output=1471bb9411af84a0 input=34ce76d8bd17a23b]*/
{
- CHECK_EXPORTS(self);
+ /* The exported buffers keep the internal buffer alive. */
Py_CLEAR(self->buf);
Py_RETURN_NONE;
}
@@ -945,54 +955,60 @@ _io_BytesIO_close_impl(bytesio *self)
function to use the efficient instance representation of PEP 307.
*/
- static PyObject *
- bytesio_getstate_lock_held(PyObject *op)
- {
- _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op);
-
- bytesio *self = bytesio_CAST(op);
- PyObject *initvalue = _io_BytesIO_getvalue_impl(self);
- PyObject *dict;
- PyObject *state;
-
- if (initvalue == NULL)
- return NULL;
- if (self->dict == NULL) {
- dict = Py_NewRef(Py_None);
- }
- else {
- dict = PyDict_Copy(self->dict);
- if (dict == NULL) {
- Py_DECREF(initvalue);
- return NULL;
- }
- }
-
- state = Py_BuildValue("(OnN)", initvalue, self->pos, dict);
- Py_DECREF(initvalue);
- return state;
-}
+
+/*[clinic input]
+@critical_section
+_io.BytesIO.__getstate__
+[clinic start generated code]*/
static PyObject *
-bytesio_getstate(PyObject *op, PyObject *Py_UNUSED(dummy))
+_io_BytesIO___getstate___impl(bytesio *self)
+/*[clinic end generated code: output=4a776270c8443b85 input=f41e5bc9731475c4]*/
{
- PyObject *ret;
- Py_BEGIN_CRITICAL_SECTION(op);
- ret = bytesio_getstate_lock_held(op);
- Py_END_CRITICAL_SECTION();
- return ret;
+ PyObject *initvalue = _io_BytesIO_getvalue_impl(self);
+ PyObject *dict;
+ PyObject *state;
+
+ if (initvalue == NULL)
+ return NULL;
+ if (_PyObject_IsInstanceDictEmpty((PyObject *)self)) {
+ dict = Py_NewRef(Py_None);
+ }
+ else {
+ dict = PyObject_GenericGetDict((PyObject *)self, NULL);
+ if (dict == NULL) {
+ Py_DECREF(initvalue);
+ return NULL;
+ }
+ Py_SETREF(dict, PyDict_Copy(dict));
+ if (dict == NULL) {
+ Py_DECREF(initvalue);
+ return NULL;
+ }
+ }
+
+ state = Py_BuildValue("(OnN)", initvalue, self->pos, dict);
+ Py_DECREF(initvalue);
+ return state;
}
+
+/*[clinic input]
+@critical_section
+_io.BytesIO.__setstate__
+
+ state: object
+ /
+[clinic start generated code]*/
+
static PyObject *
-bytesio_setstate_lock_held(PyObject *op, PyObject *state)
+_io_BytesIO___setstate___impl(bytesio *self, PyObject *state)
+/*[clinic end generated code: output=3605abdec171bb98 input=82a189599ba75083]*/
{
- _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op);
-
PyObject *result;
PyObject *position_obj;
PyObject *dict;
Py_ssize_t pos;
- bytesio *self = bytesio_CAST(op);
assert(state != NULL);
@@ -1047,30 +1063,22 @@ bytesio_setstate_lock_held(PyObject *op, PyObject *state)
Py_TYPE(dict)->tp_name);
return NULL;
}
- if (self->dict) {
- /* Alternatively, we could replace the internal dictionary
- completely. However, it seems more practical to just update it. */
- if (PyDict_Update(self->dict, dict) < 0)
- return NULL;
+ /* Alternatively, we could replace the internal dictionary
+ completely. However, it seems more practical to just update it. */
+ PyObject *self_dict = PyObject_GenericGetDict((PyObject *)self, NULL);
+ if (self_dict == NULL) {
+ return NULL;
}
- else {
- self->dict = Py_NewRef(dict);
+ int rc = PyDict_Update(self_dict, dict);
+ Py_DECREF(self_dict);
+ if (rc < 0) {
+ return NULL;
}
}
Py_RETURN_NONE;
}
-static PyObject *
-bytesio_setstate(PyObject *op, PyObject *state)
-{
- PyObject *ret;
- Py_BEGIN_CRITICAL_SECTION(op);
- ret = bytesio_setstate_lock_held(op, state);
- Py_END_CRITICAL_SECTION();
- return ret;
-}
-
static void
bytesio_dealloc(PyObject *op)
{
@@ -1083,8 +1091,8 @@ bytesio_dealloc(PyObject *op)
PyErr_Print();
}
Py_CLEAR(self->buf);
- Py_CLEAR(self->dict);
- FT_CLEAR_WEAKREFS(op, self->weakreflist);
+ PyObject_ClearManagedDict(op);
+ PyObject_ClearWeakRefs(op);
tp->tp_free(self);
Py_DECREF(tp);
}
@@ -1102,7 +1110,7 @@ bytesio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
/* tp_alloc initializes all the fields to zero. So we don't have to
initialize them here. */
- self->buf = PyBytes_FromStringAndSize(NULL, 0);
+ self->buf = Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
if (self->buf == NULL) {
Py_DECREF(self);
return PyErr_NoMemory();
@@ -1112,6 +1120,7 @@ bytesio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
}
/*[clinic input]
+@vectorcall
@critical_section
_io.BytesIO.__init__
initial_bytes as initvalue: object(c_default="NULL") = b''
@@ -1121,17 +1130,18 @@ Buffered I/O implementation using an in-memory bytes buffer.
static int
_io_BytesIO___init___impl(bytesio *self, PyObject *initvalue)
-/*[clinic end generated code: output=65c0c51e24c5b621 input=3da5a74ee4c4f1ac]*/
+/*[clinic end generated code: output=65c0c51e24c5b621 input=a6dc38082204df28]*/
{
- /* In case, __init__ is called multiple times. */
- self->string_size = 0;
- self->pos = 0;
-
if (FT_ATOMIC_LOAD_SSIZE_RELAXED(self->exports) > 0) {
PyErr_SetString(PyExc_BufferError,
"Existing exports of data: object cannot be re-sized");
return -1;
}
+
+ /* In case, __init__ is called multiple times. */
+ self->string_size = 0;
+ self->pos = 0;
+
if (initvalue && initvalue != Py_None) {
if (PyBytes_CheckExact(initvalue)) {
Py_XSETREF(self->buf, Py_NewRef(initvalue));
@@ -1151,12 +1161,18 @@ _io_BytesIO___init___impl(bytesio *self, PyObject *initvalue)
return 0;
}
+
+/*[clinic input]
+@critical_section
+_io.BytesIO.__sizeof__
+
+Size of object in memory, in bytes.
+[clinic start generated code]*/
+
static PyObject *
-bytesio_sizeof_lock_held(PyObject *op)
+_io_BytesIO___sizeof___impl(bytesio *self)
+/*[clinic end generated code: output=f61b601bd055c4de input=6f01c36e6ff64c17]*/
{
- _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op);
-
- bytesio *self = bytesio_CAST(op);
size_t res = _PyObject_SIZE(Py_TYPE(self));
if (self->buf && !SHARED_BUF(self)) {
size_t s = _PySys_GetSizeOf(self->buf);
@@ -1168,31 +1184,20 @@ bytesio_sizeof_lock_held(PyObject *op)
return PyLong_FromSize_t(res);
}
-static PyObject *
-bytesio_sizeof(PyObject *op, PyObject *Py_UNUSED(dummy))
-{
- PyObject *ret;
- Py_BEGIN_CRITICAL_SECTION(op);
- ret = bytesio_sizeof_lock_held(op);
- Py_END_CRITICAL_SECTION();
- return ret;
-}
-
static int
bytesio_traverse(PyObject *op, visitproc visit, void *arg)
{
bytesio *self = bytesio_CAST(op);
Py_VISIT(Py_TYPE(self));
- Py_VISIT(self->dict);
Py_VISIT(self->buf);
- return 0;
+ return PyObject_VisitManagedDict(op, visit, arg);
}
static int
bytesio_clear(PyObject *op)
{
bytesio *self = bytesio_CAST(op);
- Py_CLEAR(self->dict);
+ PyObject_ClearManagedDict(op);
if (FT_ATOMIC_LOAD_SSIZE_RELAXED(self->exports) == 0) {
Py_CLEAR(self->buf);
}
@@ -1205,8 +1210,7 @@ bytesio_clear(PyObject *op)
#undef clinic_state
static PyGetSetDef bytesio_getsetlist[] = {
- {"closed", bytesio_get_closed, NULL,
- "True if the file is closed."},
+ _IO_BYTESIO_CLOSED_GETSETDEF
{NULL}, /* sentinel */
};
@@ -1230,18 +1234,12 @@ static struct PyMethodDef bytesio_methods[] = {
_IO_BYTESIO_GETVALUE_METHODDEF
_IO_BYTESIO_SEEK_METHODDEF
_IO_BYTESIO_TRUNCATE_METHODDEF
- {"__getstate__", bytesio_getstate, METH_NOARGS, NULL},
- {"__setstate__", bytesio_setstate, METH_O, NULL},
- {"__sizeof__", bytesio_sizeof, METH_NOARGS, NULL},
+ _IO_BYTESIO___GETSTATE___METHODDEF
+ _IO_BYTESIO___SETSTATE___METHODDEF
+ _IO_BYTESIO___SIZEOF___METHODDEF
{NULL, NULL} /* sentinel */
};
-static PyMemberDef bytesio_members[] = {
- {"__weaklistoffset__", Py_T_PYSSIZET, offsetof(bytesio, weakreflist), Py_READONLY},
- {"__dictoffset__", Py_T_PYSSIZET, offsetof(bytesio, dict), Py_READONLY},
- {NULL}
-};
-
static PyType_Slot bytesio_slots[] = {
{Py_tp_dealloc, bytesio_dealloc},
{Py_tp_doc, (void *)_io_BytesIO___init____doc__},
@@ -1250,10 +1248,10 @@ static PyType_Slot bytesio_slots[] = {
{Py_tp_iter, PyObject_SelfIter},
{Py_tp_iternext, bytesio_iternext},
{Py_tp_methods, bytesio_methods},
- {Py_tp_members, bytesio_members},
{Py_tp_getset, bytesio_getsetlist},
{Py_tp_init, _io_BytesIO___init__},
{Py_tp_new, bytesio_new},
+ {Py_tp_vectorcall, _io_BytesIO_vectorcall},
{0, NULL},
};
@@ -1279,6 +1277,9 @@ bytesiobuf_getbuffer_lock_held(PyObject *op, Py_buffer *view, int flags)
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(b);
+ if (check_closed(b)) {
+ return -1;
+ }
if (FT_ATOMIC_LOAD_SSIZE_RELAXED(b->exports) == 0 && SHARED_BUF(b)) {
if (unshare_buffer_lock_held(b, b->string_size) < 0)
return -1;
@@ -1288,6 +1289,9 @@ bytesiobuf_getbuffer_lock_held(PyObject *op, Py_buffer *view, int flags)
(void)PyBuffer_FillInfo(view, op,
PyBytes_AS_STRING(b->buf), b->string_size,
0, flags);
+ /* Keep the internal buffer alive: the bytesio object can be closed
+ while the buffer is exported. */
+ view->internal = Py_NewRef(b->buf);
FT_ATOMIC_ADD_SSIZE(b->exports, 1);
return 0;
}
@@ -1309,11 +1313,12 @@ bytesiobuf_getbuffer(PyObject *op, Py_buffer *view, int flags)
}
static void
-bytesiobuf_releasebuffer(PyObject *op, Py_buffer *Py_UNUSED(view))
+bytesiobuf_releasebuffer(PyObject *op, Py_buffer *view)
{
bytesiobuf *obj = bytesiobuf_CAST(op);
bytesio *b = bytesio_CAST(obj->source);
FT_ATOMIC_ADD_SSIZE(b->exports, -1);
+ Py_CLEAR(view->internal);
}
static int
diff --git a/Modules/_io/clinic/_iomodule.c.h b/Modules/_io/clinic/_iomodule.c.h
index f03638064385e28..462597078b77d9c 100644
--- a/Modules/_io/clinic/_iomodule.c.h
+++ b/Modules/_io/clinic/_iomodule.c.h
@@ -7,6 +7,7 @@ preserve
# include "pycore_runtime.h" // _Py_ID()
#endif
#include "pycore_modsupport.h" // _PyArg_UnpackKeywords()
+#include "pycore_unicodeobject.h" // _PyUnicode_AsUTF8NoNUL()
PyDoc_STRVAR(_io_open__doc__,
"open($module, /, file, mode=\'r\', buffering=-1, encoding=None,\n"
@@ -27,10 +28,7 @@ PyDoc_STRVAR(_io_open__doc__,
"it already exists), \'x\' for creating and writing to a new file, and\n"
"\'a\' for appending (which on some Unix systems, means that all writes\n"
"append to the end of the file regardless of the current seek position).\n"
-"In text mode, if encoding is not specified the encoding used is platform\n"
-"dependent: locale.getencoding() is called to get the current locale\n"
-"encoding. (For reading and writing raw bytes use binary mode and leave\n"
-"encoding unspecified.) The available modes are:\n"
+"The available modes are:\n"
"\n"
"========= ==========================================================\n"
"Character Meaning\n"
@@ -55,8 +53,7 @@ PyDoc_STRVAR(_io_open__doc__,
"binary mode (appending \'b\' to the mode argument) return contents as\n"
"bytes objects without any decoding. In text mode (the default, or when\n"
"\'t\' is appended to the mode argument), the contents of the file are\n"
-"returned as strings, the bytes having been first decoded using a\n"
-"platform-dependent encoding or using the specified encoding if given.\n"
+"decoded using the encoding described below and returned as strings.\n"
"\n"
"buffering is an optional integer used to set the buffering policy.\n"
"Pass 0 to switch buffering off (only allowed in binary mode), 1 to\n"
@@ -73,10 +70,11 @@ PyDoc_STRVAR(_io_open__doc__,
" use line buffering. Other text files use the policy described above\n"
" for binary files.\n"
"\n"
-"encoding is the name of the encoding used to decode or encode the\n"
-"file. This should only be used in text mode. The default encoding is\n"
-"platform dependent, but any encoding supported by Python can be\n"
-"passed. See the codecs module for the list of supported encodings.\n"
+"encoding is the name of the encoding used to decode or encode the file.\n"
+"This should only be used in text mode. The default encoding is UTF-8;\n"
+"if UTF-8 Mode is disabled, the encoding returned by\n"
+"locale.getencoding() is used instead. See the codecs module for the\n"
+"list of supported encodings.\n"
"\n"
"errors is an optional string that specifies how encoding errors are to\n"
"be handled---this argument should not be used in binary mode. Pass\n"
@@ -192,15 +190,10 @@ _io_open(PyObject *module, PyObject *const *args, Py_ssize_t nargs, PyObject *kw
_PyArg_BadArgument("open", "argument 'mode'", "str", args[1]);
goto exit;
}
- Py_ssize_t mode_length;
- mode = PyUnicode_AsUTF8AndSize(args[1], &mode_length);
+ mode = _PyUnicode_AsUTF8NoNUL(args[1]);
if (mode == NULL) {
goto exit;
}
- if (strlen(mode) != (size_t)mode_length) {
- PyErr_SetString(PyExc_ValueError, "embedded null character");
- goto exit;
- }
if (!--noptargs) {
goto skip_optional_pos;
}
@@ -219,15 +212,10 @@ _io_open(PyObject *module, PyObject *const *args, Py_ssize_t nargs, PyObject *kw
encoding = NULL;
}
else if (PyUnicode_Check(args[3])) {
- Py_ssize_t encoding_length;
- encoding = PyUnicode_AsUTF8AndSize(args[3], &encoding_length);
+ encoding = _PyUnicode_AsUTF8NoNUL(args[3]);
if (encoding == NULL) {
goto exit;
}
- if (strlen(encoding) != (size_t)encoding_length) {
- PyErr_SetString(PyExc_ValueError, "embedded null character");
- goto exit;
- }
}
else {
_PyArg_BadArgument("open", "argument 'encoding'", "str or None", args[3]);
@@ -242,15 +230,10 @@ _io_open(PyObject *module, PyObject *const *args, Py_ssize_t nargs, PyObject *kw
errors = NULL;
}
else if (PyUnicode_Check(args[4])) {
- Py_ssize_t errors_length;
- errors = PyUnicode_AsUTF8AndSize(args[4], &errors_length);
+ errors = _PyUnicode_AsUTF8NoNUL(args[4]);
if (errors == NULL) {
goto exit;
}
- if (strlen(errors) != (size_t)errors_length) {
- PyErr_SetString(PyExc_ValueError, "embedded null character");
- goto exit;
- }
}
else {
_PyArg_BadArgument("open", "argument 'errors'", "str or None", args[4]);
@@ -265,15 +248,10 @@ _io_open(PyObject *module, PyObject *const *args, Py_ssize_t nargs, PyObject *kw
newline = NULL;
}
else if (PyUnicode_Check(args[5])) {
- Py_ssize_t newline_length;
- newline = PyUnicode_AsUTF8AndSize(args[5], &newline_length);
+ newline = _PyUnicode_AsUTF8NoNUL(args[5]);
if (newline == NULL) {
goto exit;
}
- if (strlen(newline) != (size_t)newline_length) {
- PyErr_SetString(PyExc_ValueError, "embedded null character");
- goto exit;
- }
}
else {
_PyArg_BadArgument("open", "argument 'newline'", "str or None", args[5]);
@@ -411,4 +389,4 @@ _io_open_code(PyObject *module, PyObject *const *args, Py_ssize_t nargs, PyObjec
exit:
return return_value;
}
-/*[clinic end generated code: output=5190d11f0803bfe8 input=a9049054013a1b77]*/
+/*[clinic end generated code: output=517d977e17d38fce input=a9049054013a1b77]*/
diff --git a/Modules/_io/clinic/bufferedio.c.h b/Modules/_io/clinic/bufferedio.c.h
index b7c0ca2c4b919b6..0cedf4a9948e9da 100644
--- a/Modules/_io/clinic/bufferedio.c.h
+++ b/Modules/_io/clinic/bufferedio.c.h
@@ -4,7 +4,7 @@ preserve
#if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
# include "pycore_gc.h" // PyGC_Head
-# include "pycore_runtime.h" // _Py_SINGLETON()
+# include "pycore_runtime.h" // _Py_ID()
#endif
#include "pycore_abstract.h" // _PyNumber_Index()
#include "pycore_critical_section.h"// Py_BEGIN_CRITICAL_SECTION()
@@ -135,35 +135,22 @@ static PyObject *
_io__BufferedIOBase_read(PyObject *self, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "read",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
int size = -1;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 0, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("read", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("read", nargs, 0, 1)) {
goto exit;
}
if (nargs < 1) {
- goto skip_optional_posonly;
+ goto skip_optional;
}
size = PyLong_AsInt(args[0]);
if (size == -1 && PyErr_Occurred()) {
goto exit;
}
-skip_optional_posonly:
+skip_optional:
return_value = _io__BufferedIOBase_read_impl(self, cls, size);
exit:
@@ -190,35 +177,22 @@ static PyObject *
_io__BufferedIOBase_read1(PyObject *self, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "read1",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
int size = -1;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 0, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("read1", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("read1", nargs, 0, 1)) {
goto exit;
}
if (nargs < 1) {
- goto skip_optional_posonly;
+ goto skip_optional;
}
size = PyLong_AsInt(args[0]);
if (size == -1 && PyErr_Occurred()) {
goto exit;
}
-skip_optional_posonly:
+skip_optional:
return_value = _io__BufferedIOBase_read1_impl(self, cls, size);
exit:
@@ -248,25 +222,12 @@ static PyObject *
_io__BufferedIOBase_write(PyObject *self, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "write",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *b;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("write", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("write", nargs, 1, 1)) {
goto exit;
}
b = args[0];
@@ -343,16 +304,6 @@ _io__Buffered_simple_flush(PyObject *self, PyObject *Py_UNUSED(ignored))
return return_value;
}
-#if !defined(_io__Buffered_closed_DOCSTR)
-# define _io__Buffered_closed_DOCSTR NULL
-#endif
-#if defined(_IO__BUFFERED_CLOSED_GETSETDEF)
-# undef _IO__BUFFERED_CLOSED_GETSETDEF
-# define _IO__BUFFERED_CLOSED_GETSETDEF {"closed", (getter)_io__Buffered_closed_get, (setter)_io__Buffered_closed_set, _io__Buffered_closed_DOCSTR},
-#else
-# define _IO__BUFFERED_CLOSED_GETSETDEF {"closed", (getter)_io__Buffered_closed_get, NULL, _io__Buffered_closed_DOCSTR},
-#endif
-
static PyObject *
_io__Buffered_closed_get_impl(buffered *self);
@@ -483,16 +434,6 @@ _io__Buffered_writable(PyObject *self, PyObject *Py_UNUSED(ignored))
return return_value;
}
-#if !defined(_io__Buffered_name_DOCSTR)
-# define _io__Buffered_name_DOCSTR NULL
-#endif
-#if defined(_IO__BUFFERED_NAME_GETSETDEF)
-# undef _IO__BUFFERED_NAME_GETSETDEF
-# define _IO__BUFFERED_NAME_GETSETDEF {"name", (getter)_io__Buffered_name_get, (setter)_io__Buffered_name_set, _io__Buffered_name_DOCSTR},
-#else
-# define _IO__BUFFERED_NAME_GETSETDEF {"name", (getter)_io__Buffered_name_get, NULL, _io__Buffered_name_DOCSTR},
-#endif
-
static PyObject *
_io__Buffered_name_get_impl(buffered *self);
@@ -508,16 +449,6 @@ _io__Buffered_name_get(PyObject *self, void *Py_UNUSED(context))
return return_value;
}
-#if !defined(_io__Buffered_mode_DOCSTR)
-# define _io__Buffered_mode_DOCSTR NULL
-#endif
-#if defined(_IO__BUFFERED_MODE_GETSETDEF)
-# undef _IO__BUFFERED_MODE_GETSETDEF
-# define _IO__BUFFERED_MODE_GETSETDEF {"mode", (getter)_io__Buffered_mode_get, (setter)_io__Buffered_mode_set, _io__Buffered_mode_DOCSTR},
-#else
-# define _IO__BUFFERED_MODE_GETSETDEF {"mode", (getter)_io__Buffered_mode_get, NULL, _io__Buffered_mode_DOCSTR},
-#endif
-
static PyObject *
_io__Buffered_mode_get_impl(buffered *self);
@@ -904,32 +835,19 @@ static PyObject *
_io__Buffered_truncate(PyObject *self, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "truncate",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *pos = Py_None;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 0, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("truncate", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("truncate", nargs, 0, 1)) {
goto exit;
}
if (nargs < 1) {
- goto skip_optional_posonly;
+ goto skip_optional;
}
pos = args[0];
-skip_optional_posonly:
+skip_optional:
Py_BEGIN_CRITICAL_SECTION(self);
return_value = _io__Buffered_truncate_impl((buffered *)self, cls, pos);
Py_END_CRITICAL_SECTION();
@@ -1186,6 +1104,292 @@ _io_BufferedRWPair___init__(PyObject *self, PyObject *args, PyObject *kwargs)
return return_value;
}
+PyDoc_STRVAR(_io_BufferedRWPair_read__doc__,
+"read($self, size=-1, /)\n"
+"--\n"
+"\n");
+
+#define _IO_BUFFEREDRWPAIR_READ_METHODDEF \
+ {"read", _PyCFunction_CAST(_io_BufferedRWPair_read), METH_FASTCALL, _io_BufferedRWPair_read__doc__},
+
+static PyObject *
+_io_BufferedRWPair_read_impl(rwpair *self, PyObject *size);
+
+static PyObject *
+_io_BufferedRWPair_read(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
+{
+ PyObject *return_value = NULL;
+ PyObject *size = NULL;
+
+ if (!_PyArg_CheckPositional("read", nargs, 0, 1)) {
+ goto exit;
+ }
+ if (nargs < 1) {
+ goto skip_optional;
+ }
+ size = args[0];
+skip_optional:
+ return_value = _io_BufferedRWPair_read_impl((rwpair *)self, size);
+
+exit:
+ return return_value;
+}
+
+PyDoc_STRVAR(_io_BufferedRWPair_peek__doc__,
+"peek($self, size=0, /)\n"
+"--\n"
+"\n");
+
+#define _IO_BUFFEREDRWPAIR_PEEK_METHODDEF \
+ {"peek", _PyCFunction_CAST(_io_BufferedRWPair_peek), METH_FASTCALL, _io_BufferedRWPair_peek__doc__},
+
+static PyObject *
+_io_BufferedRWPair_peek_impl(rwpair *self, PyObject *size);
+
+static PyObject *
+_io_BufferedRWPair_peek(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
+{
+ PyObject *return_value = NULL;
+ PyObject *size = NULL;
+
+ if (!_PyArg_CheckPositional("peek", nargs, 0, 1)) {
+ goto exit;
+ }
+ if (nargs < 1) {
+ goto skip_optional;
+ }
+ size = args[0];
+skip_optional:
+ return_value = _io_BufferedRWPair_peek_impl((rwpair *)self, size);
+
+exit:
+ return return_value;
+}
+
+PyDoc_STRVAR(_io_BufferedRWPair_read1__doc__,
+"read1($self, size=-1, /)\n"
+"--\n"
+"\n");
+
+#define _IO_BUFFEREDRWPAIR_READ1_METHODDEF \
+ {"read1", _PyCFunction_CAST(_io_BufferedRWPair_read1), METH_FASTCALL, _io_BufferedRWPair_read1__doc__},
+
+static PyObject *
+_io_BufferedRWPair_read1_impl(rwpair *self, PyObject *size);
+
+static PyObject *
+_io_BufferedRWPair_read1(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
+{
+ PyObject *return_value = NULL;
+ PyObject *size = NULL;
+
+ if (!_PyArg_CheckPositional("read1", nargs, 0, 1)) {
+ goto exit;
+ }
+ if (nargs < 1) {
+ goto skip_optional;
+ }
+ size = args[0];
+skip_optional:
+ return_value = _io_BufferedRWPair_read1_impl((rwpair *)self, size);
+
+exit:
+ return return_value;
+}
+
+PyDoc_STRVAR(_io_BufferedRWPair_readline__doc__,
+"readline($self, size=-1, /)\n"
+"--\n"
+"\n"
+"Read and return a line from the stream.\n"
+"\n"
+"If size is specified, at most size bytes will be read.\n"
+"\n"
+"The line terminator is always b\'\\n\'.");
+
+#define _IO_BUFFEREDRWPAIR_READLINE_METHODDEF \
+ {"readline", _PyCFunction_CAST(_io_BufferedRWPair_readline), METH_FASTCALL, _io_BufferedRWPair_readline__doc__},
+
+static PyObject *
+_io_BufferedRWPair_readline_impl(rwpair *self, PyObject *size);
+
+static PyObject *
+_io_BufferedRWPair_readline(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
+{
+ PyObject *return_value = NULL;
+ PyObject *size = NULL;
+
+ if (!_PyArg_CheckPositional("readline", nargs, 0, 1)) {
+ goto exit;
+ }
+ if (nargs < 1) {
+ goto skip_optional;
+ }
+ size = args[0];
+skip_optional:
+ return_value = _io_BufferedRWPair_readline_impl((rwpair *)self, size);
+
+exit:
+ return return_value;
+}
+
+PyDoc_STRVAR(_io_BufferedRWPair_readinto__doc__,
+"readinto($self, buffer, /)\n"
+"--\n"
+"\n");
+
+#define _IO_BUFFEREDRWPAIR_READINTO_METHODDEF \
+ {"readinto", (PyCFunction)_io_BufferedRWPair_readinto, METH_O, _io_BufferedRWPair_readinto__doc__},
+
+static PyObject *
+_io_BufferedRWPair_readinto_impl(rwpair *self, PyObject *buffer);
+
+static PyObject *
+_io_BufferedRWPair_readinto(PyObject *self, PyObject *buffer)
+{
+ PyObject *return_value = NULL;
+
+ return_value = _io_BufferedRWPair_readinto_impl((rwpair *)self, buffer);
+
+ return return_value;
+}
+
+PyDoc_STRVAR(_io_BufferedRWPair_readinto1__doc__,
+"readinto1($self, buffer, /)\n"
+"--\n"
+"\n");
+
+#define _IO_BUFFEREDRWPAIR_READINTO1_METHODDEF \
+ {"readinto1", (PyCFunction)_io_BufferedRWPair_readinto1, METH_O, _io_BufferedRWPair_readinto1__doc__},
+
+static PyObject *
+_io_BufferedRWPair_readinto1_impl(rwpair *self, PyObject *buffer);
+
+static PyObject *
+_io_BufferedRWPair_readinto1(PyObject *self, PyObject *buffer)
+{
+ PyObject *return_value = NULL;
+
+ return_value = _io_BufferedRWPair_readinto1_impl((rwpair *)self, buffer);
+
+ return return_value;
+}
+
+PyDoc_STRVAR(_io_BufferedRWPair_write__doc__,
+"write($self, buffer, /)\n"
+"--\n"
+"\n");
+
+#define _IO_BUFFEREDRWPAIR_WRITE_METHODDEF \
+ {"write", (PyCFunction)_io_BufferedRWPair_write, METH_O, _io_BufferedRWPair_write__doc__},
+
+static PyObject *
+_io_BufferedRWPair_write_impl(rwpair *self, PyObject *buffer);
+
+static PyObject *
+_io_BufferedRWPair_write(PyObject *self, PyObject *buffer)
+{
+ PyObject *return_value = NULL;
+
+ return_value = _io_BufferedRWPair_write_impl((rwpair *)self, buffer);
+
+ return return_value;
+}
+
+PyDoc_STRVAR(_io_BufferedRWPair_flush__doc__,
+"flush($self, /)\n"
+"--\n"
+"\n");
+
+#define _IO_BUFFEREDRWPAIR_FLUSH_METHODDEF \
+ {"flush", (PyCFunction)_io_BufferedRWPair_flush, METH_NOARGS, _io_BufferedRWPair_flush__doc__},
+
+static PyObject *
+_io_BufferedRWPair_flush_impl(rwpair *self);
+
+static PyObject *
+_io_BufferedRWPair_flush(PyObject *self, PyObject *Py_UNUSED(ignored))
+{
+ return _io_BufferedRWPair_flush_impl((rwpair *)self);
+}
+
+PyDoc_STRVAR(_io_BufferedRWPair_readable__doc__,
+"readable($self, /)\n"
+"--\n"
+"\n");
+
+#define _IO_BUFFEREDRWPAIR_READABLE_METHODDEF \
+ {"readable", (PyCFunction)_io_BufferedRWPair_readable, METH_NOARGS, _io_BufferedRWPair_readable__doc__},
+
+static PyObject *
+_io_BufferedRWPair_readable_impl(rwpair *self);
+
+static PyObject *
+_io_BufferedRWPair_readable(PyObject *self, PyObject *Py_UNUSED(ignored))
+{
+ return _io_BufferedRWPair_readable_impl((rwpair *)self);
+}
+
+PyDoc_STRVAR(_io_BufferedRWPair_writable__doc__,
+"writable($self, /)\n"
+"--\n"
+"\n");
+
+#define _IO_BUFFEREDRWPAIR_WRITABLE_METHODDEF \
+ {"writable", (PyCFunction)_io_BufferedRWPair_writable, METH_NOARGS, _io_BufferedRWPair_writable__doc__},
+
+static PyObject *
+_io_BufferedRWPair_writable_impl(rwpair *self);
+
+static PyObject *
+_io_BufferedRWPair_writable(PyObject *self, PyObject *Py_UNUSED(ignored))
+{
+ return _io_BufferedRWPair_writable_impl((rwpair *)self);
+}
+
+PyDoc_STRVAR(_io_BufferedRWPair_close__doc__,
+"close($self, /)\n"
+"--\n"
+"\n");
+
+#define _IO_BUFFEREDRWPAIR_CLOSE_METHODDEF \
+ {"close", (PyCFunction)_io_BufferedRWPair_close, METH_NOARGS, _io_BufferedRWPair_close__doc__},
+
+static PyObject *
+_io_BufferedRWPair_close_impl(rwpair *self);
+
+static PyObject *
+_io_BufferedRWPair_close(PyObject *self, PyObject *Py_UNUSED(ignored))
+{
+ return _io_BufferedRWPair_close_impl((rwpair *)self);
+}
+
+PyDoc_STRVAR(_io_BufferedRWPair_isatty__doc__,
+"isatty($self, /)\n"
+"--\n"
+"\n");
+
+#define _IO_BUFFEREDRWPAIR_ISATTY_METHODDEF \
+ {"isatty", (PyCFunction)_io_BufferedRWPair_isatty, METH_NOARGS, _io_BufferedRWPair_isatty__doc__},
+
+static PyObject *
+_io_BufferedRWPair_isatty_impl(rwpair *self);
+
+static PyObject *
+_io_BufferedRWPair_isatty(PyObject *self, PyObject *Py_UNUSED(ignored))
+{
+ return _io_BufferedRWPair_isatty_impl((rwpair *)self);
+}
+
+static PyObject *
+_io_BufferedRWPair_closed_get_impl(rwpair *self);
+
+static PyObject *
+_io_BufferedRWPair_closed_get(PyObject *self, void *Py_UNUSED(context))
+{
+ return _io_BufferedRWPair_closed_get_impl((rwpair *)self);
+}
+
PyDoc_STRVAR(_io_BufferedRandom___init____doc__,
"BufferedRandom(raw, buffer_size=DEFAULT_BUFFER_SIZE)\n"
"--\n"
@@ -1265,4 +1469,12 @@ _io_BufferedRandom___init__(PyObject *self, PyObject *args, PyObject *kwargs)
exit:
return return_value;
}
-/*[clinic end generated code: output=3ee17211d2010462 input=a9049054013a1b77]*/
+#define _IO__BUFFERED_CLOSED_GETSETDEF {"closed", (getter)_io__Buffered_closed_get, (setter)NULL, NULL},
+
+#define _IO__BUFFERED_NAME_GETSETDEF {"name", (getter)_io__Buffered_name_get, (setter)NULL, NULL},
+
+#define _IO__BUFFERED_MODE_GETSETDEF {"mode", (getter)_io__Buffered_mode_get, (setter)NULL, NULL},
+
+#define _IO_BUFFEREDRWPAIR_CLOSED_GETSETDEF {"closed", (getter)_io_BufferedRWPair_closed_get, (setter)NULL, NULL},
+
+/*[clinic end generated code: output=1596bb353f00a1ea input=a9049054013a1b77]*/
diff --git a/Modules/_io/clinic/bytesio.c.h b/Modules/_io/clinic/bytesio.c.h
index a0159c063b58591..e48d71397367daf 100644
--- a/Modules/_io/clinic/bytesio.c.h
+++ b/Modules/_io/clinic/bytesio.c.h
@@ -4,11 +4,35 @@ preserve
#if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
# include "pycore_gc.h" // PyGC_Head
-# include "pycore_runtime.h" // _Py_ID()
#endif
#include "pycore_abstract.h" // _Py_convert_optional_to_ssize_t()
#include "pycore_critical_section.h"// Py_BEGIN_CRITICAL_SECTION()
#include "pycore_modsupport.h" // _PyArg_CheckPositional()
+#include "pycore_runtime.h" // _Py_SINGLETON()
+
+PyDoc_STRVAR(_io_BytesIO_closed__doc__,
+"True if the file is closed.");
+
+static int
+_io_BytesIO_closed_get_impl(bytesio *self);
+
+static PyObject *
+_io_BytesIO_closed_get(PyObject *self, void *Py_UNUSED(context))
+{
+ PyObject *return_value = NULL;
+ int _return_value;
+
+ Py_BEGIN_CRITICAL_SECTION(self);
+ _return_value = _io_BytesIO_closed_get_impl((bytesio *)self);
+ Py_END_CRITICAL_SECTION();
+ if ((_return_value == -1) && PyErr_Occurred()) {
+ goto exit;
+ }
+ return_value = PyBool_FromLong((long)_return_value);
+
+exit:
+ return return_value;
+}
PyDoc_STRVAR(_io_BytesIO_readable__doc__,
"readable($self, /)\n"
@@ -487,6 +511,21 @@ _io_BytesIO_truncate(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
return return_value;
}
+static PyObject *
+bytesio_iternext_impl(bytesio *self);
+
+static PyObject *
+bytesio_iternext(PyObject *self)
+{
+ PyObject *return_value = NULL;
+
+ Py_BEGIN_CRITICAL_SECTION(self);
+ return_value = bytesio_iternext_impl((bytesio *)self);
+ Py_END_CRITICAL_SECTION();
+
+ return return_value;
+}
+
PyDoc_STRVAR(_io_BytesIO_seek__doc__,
"seek($self, pos, whence=0, /)\n"
"--\n"
@@ -621,6 +660,52 @@ _io_BytesIO_close(PyObject *self, PyObject *Py_UNUSED(ignored))
return return_value;
}
+PyDoc_STRVAR(_io_BytesIO___getstate____doc__,
+"__getstate__($self, /)\n"
+"--\n"
+"\n");
+
+#define _IO_BYTESIO___GETSTATE___METHODDEF \
+ {"__getstate__", (PyCFunction)_io_BytesIO___getstate__, METH_NOARGS, _io_BytesIO___getstate____doc__},
+
+static PyObject *
+_io_BytesIO___getstate___impl(bytesio *self);
+
+static PyObject *
+_io_BytesIO___getstate__(PyObject *self, PyObject *Py_UNUSED(ignored))
+{
+ PyObject *return_value = NULL;
+
+ Py_BEGIN_CRITICAL_SECTION(self);
+ return_value = _io_BytesIO___getstate___impl((bytesio *)self);
+ Py_END_CRITICAL_SECTION();
+
+ return return_value;
+}
+
+PyDoc_STRVAR(_io_BytesIO___setstate____doc__,
+"__setstate__($self, state, /)\n"
+"--\n"
+"\n");
+
+#define _IO_BYTESIO___SETSTATE___METHODDEF \
+ {"__setstate__", (PyCFunction)_io_BytesIO___setstate__, METH_O, _io_BytesIO___setstate____doc__},
+
+static PyObject *
+_io_BytesIO___setstate___impl(bytesio *self, PyObject *state);
+
+static PyObject *
+_io_BytesIO___setstate__(PyObject *self, PyObject *state)
+{
+ PyObject *return_value = NULL;
+
+ Py_BEGIN_CRITICAL_SECTION(self);
+ return_value = _io_BytesIO___setstate___impl((bytesio *)self, state);
+ Py_END_CRITICAL_SECTION();
+
+ return return_value;
+}
+
PyDoc_STRVAR(_io_BytesIO___init____doc__,
"BytesIO(initial_bytes=b\'\')\n"
"--\n"
@@ -631,7 +716,8 @@ static int
_io_BytesIO___init___impl(bytesio *self, PyObject *initvalue);
static int
-_io_BytesIO___init__(PyObject *self, PyObject *args, PyObject *kwargs)
+_io_BytesIO___init___helper(PyObject *self, PyObject *const *args,
+ Py_ssize_t nargs, Py_ssize_t nkw, PyObject *kwargs, PyObject *kwnames)
{
int return_value = -1;
#if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
@@ -663,11 +749,10 @@ _io_BytesIO___init__(PyObject *self, PyObject *args, PyObject *kwargs)
#undef KWTUPLE
PyObject *argsbuf[1];
PyObject * const *fastargs;
- Py_ssize_t nargs = PyTuple_GET_SIZE(args);
- Py_ssize_t noptargs = nargs + (kwargs ? PyDict_GET_SIZE(kwargs) : 0) - 0;
+ Py_ssize_t noptargs = nargs + nkw - 0;
PyObject *initvalue = NULL;
- fastargs = _PyArg_UnpackKeywords(_PyTuple_CAST(args)->ob_item, nargs, kwargs, NULL, &_parser,
+ fastargs = _PyArg_UnpackKeywords(args, nargs, kwargs, kwnames, &_parser,
/*minpos*/ 0, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
if (!fastargs) {
goto exit;
@@ -684,4 +769,91 @@ _io_BytesIO___init__(PyObject *self, PyObject *args, PyObject *kwargs)
exit:
return return_value;
}
-/*[clinic end generated code: output=b5e625e31b2a82f0 input=a9049054013a1b77]*/
+
+static int
+_io_BytesIO___init__(PyObject *self, PyObject *args, PyObject *kwargs)
+{
+ return _io_BytesIO___init___helper(self, _PyTuple_CAST(args)->ob_item,
+ PyTuple_GET_SIZE(args),
+ kwargs ? PyDict_GET_SIZE(kwargs) : 0,
+ kwargs, NULL);
+}
+
+static PyObject *
+_io_BytesIO_vectorcall(PyObject *type, PyObject *const *args,
+ size_t nargsf, PyObject *kwnames)
+{
+ PyObject *return_value = NULL;
+ Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
+ PyObject *self;
+ int _result;
+ PyObject *initvalue = NULL;
+
+ assert(_PyType_CAST(type)->tp_init == _io_BytesIO___init__);
+ /* Make sure the type object is immutable: the generated
+ * vectorcall doesn't deal e.g. with users reassigning __init__. */
+ assert(PyType_HasFeature(_PyType_CAST(type), Py_TPFLAGS_IMMUTABLETYPE));
+ if (kwnames != NULL || nargs > 1) {
+ self = _PyType_CAST(type)->tp_new(_PyType_CAST(type),
+ (PyObject *)&_Py_SINGLETON(tuple_empty), NULL);
+ if (self == NULL) {
+ return NULL;
+ }
+ _result = _io_BytesIO___init___helper(self, args, nargs,
+ kwnames ? PyTuple_GET_SIZE(kwnames) : 0,
+ NULL, kwnames);
+ if (_result != 0) {
+ Py_DECREF(self);
+ return NULL;
+ }
+ return self;
+ }
+ if (nargs < 1) {
+ goto skip_optional;
+ }
+ initvalue = args[0];
+skip_optional:
+ self = _PyType_CAST(type)->tp_new(_PyType_CAST(type),
+ (PyObject *)&_Py_SINGLETON(tuple_empty), NULL);
+ if (self == NULL) {
+ goto exit;
+ }
+ Py_BEGIN_CRITICAL_SECTION(self);
+ _result = _io_BytesIO___init___impl((bytesio *)self, initvalue);
+ Py_END_CRITICAL_SECTION();
+ if (_result != 0) {
+ Py_DECREF(self);
+ goto exit;
+ }
+ return_value = self;
+
+exit:
+ return return_value;
+}
+
+PyDoc_STRVAR(_io_BytesIO___sizeof____doc__,
+"__sizeof__($self, /)\n"
+"--\n"
+"\n"
+"Size of object in memory, in bytes.");
+
+#define _IO_BYTESIO___SIZEOF___METHODDEF \
+ {"__sizeof__", (PyCFunction)_io_BytesIO___sizeof__, METH_NOARGS, _io_BytesIO___sizeof____doc__},
+
+static PyObject *
+_io_BytesIO___sizeof___impl(bytesio *self);
+
+static PyObject *
+_io_BytesIO___sizeof__(PyObject *self, PyObject *Py_UNUSED(ignored))
+{
+ PyObject *return_value = NULL;
+
+ Py_BEGIN_CRITICAL_SECTION(self);
+ return_value = _io_BytesIO___sizeof___impl((bytesio *)self);
+ Py_END_CRITICAL_SECTION();
+
+ return return_value;
+}
+#define _IO_BYTESIO_CLOSED_GETSETDEF {"closed", (getter)_io_BytesIO_closed_get, (setter)NULL, _io_BytesIO_closed__doc__},
+
+/*[clinic end generated code: output=b9d367ad8e0b44d2 input=a9049054013a1b77]*/
diff --git a/Modules/_io/clinic/fileio.c.h b/Modules/_io/clinic/fileio.c.h
index 890b6bc3fac9d55..9db31938f3334f3 100644
--- a/Modules/_io/clinic/fileio.c.h
+++ b/Modules/_io/clinic/fileio.c.h
@@ -8,6 +8,28 @@ preserve
#endif
#include "pycore_abstract.h" // _Py_convert_optional_to_ssize_t()
#include "pycore_modsupport.h" // _PyArg_UnpackKeywords()
+#include "pycore_unicodeobject.h" // _PyUnicode_AsUTF8NoNUL()
+
+PyDoc_STRVAR(_io_FileIO__dealloc_warn__doc__,
+"_dealloc_warn($self, source, /)\n"
+"--\n"
+"\n");
+
+#define _IO_FILEIO__DEALLOC_WARN_METHODDEF \
+ {"_dealloc_warn", (PyCFunction)_io_FileIO__dealloc_warn, METH_O, _io_FileIO__dealloc_warn__doc__},
+
+static PyObject *
+_io_FileIO__dealloc_warn_impl(fileio *self, PyObject *source);
+
+static PyObject *
+_io_FileIO__dealloc_warn(PyObject *self, PyObject *source)
+{
+ PyObject *return_value = NULL;
+
+ return_value = _io_FileIO__dealloc_warn_impl((fileio *)self, source);
+
+ return return_value;
+}
PyDoc_STRVAR(_io_FileIO_close__doc__,
"close($self, /)\n"
@@ -113,15 +135,10 @@ _io_FileIO___init__(PyObject *self, PyObject *args, PyObject *kwargs)
_PyArg_BadArgument("FileIO", "argument 'mode'", "str", fastargs[1]);
goto exit;
}
- Py_ssize_t mode_length;
- mode = PyUnicode_AsUTF8AndSize(fastargs[1], &mode_length);
+ mode = _PyUnicode_AsUTF8NoNUL(fastargs[1]);
if (mode == NULL) {
goto exit;
}
- if (strlen(mode) != (size_t)mode_length) {
- PyErr_SetString(PyExc_ValueError, "embedded null character");
- goto exit;
- }
if (!--noptargs) {
goto skip_optional_pos;
}
@@ -231,25 +248,12 @@ static PyObject *
_io_FileIO_readinto(PyObject *self, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "readinto",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
Py_buffer buffer = {NULL, NULL};
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("readinto", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("readinto", nargs, 1, 1)) {
goto exit;
}
if (PyObject_GetBuffer(args[0], &buffer, PyBUF_WRITABLE) < 0) {
@@ -322,34 +326,21 @@ static PyObject *
_io_FileIO_read(PyObject *self, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "read",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
Py_ssize_t size = -1;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 0, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("read", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("read", nargs, 0, 1)) {
goto exit;
}
if (nargs < 1) {
- goto skip_optional_posonly;
+ goto skip_optional;
}
if (!_Py_convert_optional_to_ssize_t(args[0], &size)) {
goto exit;
}
-skip_optional_posonly:
+skip_optional:
return_value = _io_FileIO_read_impl((fileio *)self, cls, size);
exit:
@@ -376,25 +367,12 @@ static PyObject *
_io_FileIO_write(PyObject *self, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "write",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
Py_buffer b = {NULL, NULL};
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("write", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("write", nargs, 1, 1)) {
goto exit;
}
if (PyObject_GetBuffer(args[0], &b, PyBUF_SIMPLE) != 0) {
@@ -498,32 +476,19 @@ static PyObject *
_io_FileIO_truncate(PyObject *self, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "truncate",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *posobj = Py_None;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 0, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("truncate", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("truncate", nargs, 0, 1)) {
goto exit;
}
if (nargs < 1) {
- goto skip_optional_posonly;
+ goto skip_optional;
}
posobj = args[0];
-skip_optional_posonly:
+skip_optional:
return_value = _io_FileIO_truncate_impl((fileio *)self, cls, posobj);
exit:
@@ -550,7 +515,110 @@ _io_FileIO_isatty(PyObject *self, PyObject *Py_UNUSED(ignored))
return _io_FileIO_isatty_impl((fileio *)self);
}
+PyDoc_STRVAR(_io_FileIO__isatty_open_only__doc__,
+"_isatty_open_only($self, /)\n"
+"--\n"
+"\n");
+
+#define _IO_FILEIO__ISATTY_OPEN_ONLY_METHODDEF \
+ {"_isatty_open_only", (PyCFunction)_io_FileIO__isatty_open_only, METH_NOARGS, _io_FileIO__isatty_open_only__doc__},
+
+static PyObject *
+_io_FileIO__isatty_open_only_impl(fileio *self);
+
+static PyObject *
+_io_FileIO__isatty_open_only(PyObject *self, PyObject *Py_UNUSED(ignored))
+{
+ return _io_FileIO__isatty_open_only_impl((fileio *)self);
+}
+
+PyDoc_STRVAR(_io_FileIO_closed__doc__,
+"True if the file is closed.");
+
+static int
+_io_FileIO_closed_get_impl(fileio *self);
+
+static PyObject *
+_io_FileIO_closed_get(PyObject *self, void *Py_UNUSED(context))
+{
+ PyObject *return_value = NULL;
+ int _return_value;
+
+ _return_value = _io_FileIO_closed_get_impl((fileio *)self);
+ if ((_return_value == -1) && PyErr_Occurred()) {
+ goto exit;
+ }
+ return_value = PyBool_FromLong((long)_return_value);
+
+exit:
+ return return_value;
+}
+
+PyDoc_STRVAR(_io_FileIO_closefd__doc__,
+"True if the file descriptor will be closed by close().");
+
+static int
+_io_FileIO_closefd_get_impl(fileio *self);
+
+static PyObject *
+_io_FileIO_closefd_get(PyObject *self, void *Py_UNUSED(context))
+{
+ PyObject *return_value = NULL;
+ int _return_value;
+
+ _return_value = _io_FileIO_closefd_get_impl((fileio *)self);
+ if ((_return_value == -1) && PyErr_Occurred()) {
+ goto exit;
+ }
+ return_value = PyBool_FromLong((long)_return_value);
+
+exit:
+ return return_value;
+}
+
+PyDoc_STRVAR(_io_FileIO_mode__doc__,
+"String giving the file mode.");
+
+static PyObject *
+_io_FileIO_mode_get_impl(fileio *self);
+
+static PyObject *
+_io_FileIO_mode_get(PyObject *self, void *Py_UNUSED(context))
+{
+ return _io_FileIO_mode_get_impl((fileio *)self);
+}
+
+PyDoc_STRVAR(_io_FileIO__blksize__doc__,
+"Stat st_blksize if available.");
+
+static long
+_io_FileIO__blksize_get_impl(fileio *self);
+
+static PyObject *
+_io_FileIO__blksize_get(PyObject *self, void *Py_UNUSED(context))
+{
+ PyObject *return_value = NULL;
+ long _return_value;
+
+ _return_value = _io_FileIO__blksize_get_impl((fileio *)self);
+ if ((_return_value == -1) && PyErr_Occurred()) {
+ goto exit;
+ }
+ return_value = PyLong_FromLong(_return_value);
+
+exit:
+ return return_value;
+}
+
#ifndef _IO_FILEIO_TRUNCATE_METHODDEF
#define _IO_FILEIO_TRUNCATE_METHODDEF
#endif /* !defined(_IO_FILEIO_TRUNCATE_METHODDEF) */
-/*[clinic end generated code: output=453d584e2e72f986 input=a9049054013a1b77]*/
+#define _IO_FILEIO_CLOSED_GETSETDEF {"closed", (getter)_io_FileIO_closed_get, (setter)NULL, _io_FileIO_closed__doc__},
+
+#define _IO_FILEIO_CLOSEFD_GETSETDEF {"closefd", (getter)_io_FileIO_closefd_get, (setter)NULL, _io_FileIO_closefd__doc__},
+
+#define _IO_FILEIO_MODE_GETSETDEF {"mode", (getter)_io_FileIO_mode_get, (setter)NULL, _io_FileIO_mode__doc__},
+
+#define _IO_FILEIO__BLKSIZE_GETSETDEF {"_blksize", (getter)_io_FileIO__blksize_get, (setter)NULL, _io_FileIO__blksize__doc__},
+
+/*[clinic end generated code: output=b8d6d338bfd0a58f input=a9049054013a1b77]*/
diff --git a/Modules/_io/clinic/iobase.c.h b/Modules/_io/clinic/iobase.c.h
index e4438c26431aa8e..c7adafe1580ea9a 100644
--- a/Modules/_io/clinic/iobase.c.h
+++ b/Modules/_io/clinic/iobase.c.h
@@ -2,11 +2,8 @@
preserve
[clinic start generated code]*/
-#if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
-# include "pycore_runtime.h" // _Py_SINGLETON()
-#endif
#include "pycore_abstract.h" // _Py_convert_optional_to_ssize_t()
-#include "pycore_modsupport.h" // _PyArg_UnpackKeywords()
+#include "pycore_modsupport.h" // _PyArg_CheckPositional()
PyDoc_STRVAR(_io__IOBase_seek__doc__,
"seek($self, offset, whence=os.SEEK_SET, /)\n"
@@ -41,26 +38,13 @@ static PyObject *
_io__IOBase_seek(PyObject *self, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", "", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "seek",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[2];
int offset;
int whence = 0;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 2, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("seek", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("seek", nargs, 1, 2)) {
goto exit;
}
offset = PyLong_AsInt(args[0]);
@@ -68,13 +52,13 @@ _io__IOBase_seek(PyObject *self, PyTypeObject *cls, PyObject *const *args, Py_ss
goto exit;
}
if (nargs < 2) {
- goto skip_optional_posonly;
+ goto skip_optional;
}
whence = PyLong_AsInt(args[1]);
if (whence == -1 && PyErr_Occurred()) {
goto exit;
}
-skip_optional_posonly:
+skip_optional:
return_value = _io__IOBase_seek_impl(self, cls, offset, whence);
exit:
@@ -119,32 +103,19 @@ static PyObject *
_io__IOBase_truncate(PyObject *self, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "truncate",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
PyObject *size = Py_None;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 0, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("truncate", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("truncate", nargs, 0, 1)) {
goto exit;
}
if (nargs < 1) {
- goto skip_optional_posonly;
+ goto skip_optional;
}
size = args[0];
-skip_optional_posonly:
+skip_optional:
return_value = _io__IOBase_truncate_impl(self, cls, size);
exit:
@@ -171,6 +142,96 @@ _io__IOBase_flush(PyObject *self, PyObject *Py_UNUSED(ignored))
return _io__IOBase_flush_impl(self);
}
+PyDoc_STRVAR(_io__IOBase_closed__doc__,
+"True if the file is closed.");
+
+static int
+_io__IOBase_closed_get_impl(PyObject *self);
+
+static PyObject *
+_io__IOBase_closed_get(PyObject *self, void *Py_UNUSED(context))
+{
+ PyObject *return_value = NULL;
+ int _return_value;
+
+ _return_value = _io__IOBase_closed_get_impl(self);
+ if ((_return_value == -1) && PyErr_Occurred()) {
+ goto exit;
+ }
+ return_value = PyBool_FromLong((long)_return_value);
+
+exit:
+ return return_value;
+}
+
+PyDoc_STRVAR(_io__IOBase__checkClosed__doc__,
+"_checkClosed($self, /)\n"
+"--\n"
+"\n");
+
+#define _IO__IOBASE__CHECKCLOSED_METHODDEF \
+ {"_checkClosed", (PyCFunction)_io__IOBase__checkClosed, METH_NOARGS, _io__IOBase__checkClosed__doc__},
+
+static PyObject *
+_io__IOBase__checkClosed_impl(PyObject *self);
+
+static PyObject *
+_io__IOBase__checkClosed(PyObject *self, PyObject *Py_UNUSED(ignored))
+{
+ return _io__IOBase__checkClosed_impl(self);
+}
+
+PyDoc_STRVAR(_io__IOBase__checkSeekable__doc__,
+"_checkSeekable($self, /)\n"
+"--\n"
+"\n");
+
+#define _IO__IOBASE__CHECKSEEKABLE_METHODDEF \
+ {"_checkSeekable", (PyCFunction)_io__IOBase__checkSeekable, METH_NOARGS, _io__IOBase__checkSeekable__doc__},
+
+static PyObject *
+_io__IOBase__checkSeekable_impl(PyObject *self);
+
+static PyObject *
+_io__IOBase__checkSeekable(PyObject *self, PyObject *Py_UNUSED(ignored))
+{
+ return _io__IOBase__checkSeekable_impl(self);
+}
+
+PyDoc_STRVAR(_io__IOBase__checkReadable__doc__,
+"_checkReadable($self, /)\n"
+"--\n"
+"\n");
+
+#define _IO__IOBASE__CHECKREADABLE_METHODDEF \
+ {"_checkReadable", (PyCFunction)_io__IOBase__checkReadable, METH_NOARGS, _io__IOBase__checkReadable__doc__},
+
+static PyObject *
+_io__IOBase__checkReadable_impl(PyObject *self);
+
+static PyObject *
+_io__IOBase__checkReadable(PyObject *self, PyObject *Py_UNUSED(ignored))
+{
+ return _io__IOBase__checkReadable_impl(self);
+}
+
+PyDoc_STRVAR(_io__IOBase__checkWritable__doc__,
+"_checkWritable($self, /)\n"
+"--\n"
+"\n");
+
+#define _IO__IOBASE__CHECKWRITABLE_METHODDEF \
+ {"_checkWritable", (PyCFunction)_io__IOBase__checkWritable, METH_NOARGS, _io__IOBase__checkWritable__doc__},
+
+static PyObject *
+_io__IOBase__checkWritable_impl(PyObject *self);
+
+static PyObject *
+_io__IOBase__checkWritable(PyObject *self, PyObject *Py_UNUSED(ignored))
+{
+ return _io__IOBase__checkWritable_impl(self);
+}
+
PyDoc_STRVAR(_io__IOBase_close__doc__,
"close($self, /)\n"
"--\n"
@@ -252,6 +313,55 @@ _io__IOBase_writable(PyObject *self, PyObject *Py_UNUSED(ignored))
return _io__IOBase_writable_impl(self);
}
+PyDoc_STRVAR(_io__IOBase___enter____doc__,
+"__enter__($self, /)\n"
+"--\n"
+"\n"
+"Context management protocol. Returns the stream itself.");
+
+#define _IO__IOBASE___ENTER___METHODDEF \
+ {"__enter__", (PyCFunction)_io__IOBase___enter__, METH_NOARGS, _io__IOBase___enter____doc__},
+
+static PyObject *
+_io__IOBase___enter___impl(PyObject *self);
+
+static PyObject *
+_io__IOBase___enter__(PyObject *self, PyObject *Py_UNUSED(ignored))
+{
+ return _io__IOBase___enter___impl(self);
+}
+
+PyDoc_STRVAR(_io__IOBase___exit____doc__,
+"__exit__($self, /, *args)\n"
+"--\n"
+"\n"
+"Context management protocol. Calls close().");
+
+#define _IO__IOBASE___EXIT___METHODDEF \
+ {"__exit__", _PyCFunction_CAST(_io__IOBase___exit__), METH_FASTCALL, _io__IOBase___exit____doc__},
+
+static PyObject *
+_io__IOBase___exit___impl(PyObject *self, PyObject *args);
+
+static PyObject *
+_io__IOBase___exit__(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
+{
+ PyObject *return_value = NULL;
+ PyObject *__clinic_args = NULL;
+
+ __clinic_args = PyTuple_FromArray(args, nargs);
+ if (__clinic_args == NULL) {
+ goto exit;
+ }
+ return_value = _io__IOBase___exit___impl(self, __clinic_args);
+
+exit:
+ /* Cleanup for args */
+ Py_XDECREF(__clinic_args);
+
+ return return_value;
+}
+
PyDoc_STRVAR(_io__IOBase_fileno__doc__,
"fileno($self, /)\n"
"--\n"
@@ -445,4 +555,22 @@ _io__RawIOBase_readall(PyObject *self, PyObject *Py_UNUSED(ignored))
{
return _io__RawIOBase_readall_impl(self);
}
-/*[clinic end generated code: output=28c06bb6db32c096 input=a9049054013a1b77]*/
+
+PyDoc_STRVAR(_io__RawIOBase_readinto__doc__,
+"readinto($self, buffer, /)\n"
+"--\n"
+"\n");
+
+#define _IO__RAWIOBASE_READINTO_METHODDEF \
+ {"readinto", (PyCFunction)_io__RawIOBase_readinto, METH_O, _io__RawIOBase_readinto__doc__},
+
+PyDoc_STRVAR(_io__RawIOBase_write__doc__,
+"write($self, buffer, /)\n"
+"--\n"
+"\n");
+
+#define _IO__RAWIOBASE_WRITE_METHODDEF \
+ {"write", (PyCFunction)_io__RawIOBase_write, METH_O, _io__RawIOBase_write__doc__},
+#define _IO__IOBASE_CLOSED_GETSETDEF {"closed", (getter)_io__IOBase_closed_get, (setter)NULL, _io__IOBase_closed__doc__},
+
+/*[clinic end generated code: output=fd729b0ef2ad52b8 input=a9049054013a1b77]*/
diff --git a/Modules/_io/clinic/stringio.c.h b/Modules/_io/clinic/stringio.c.h
index d6d4afb9b63c624..bda87205e6bb718 100644
--- a/Modules/_io/clinic/stringio.c.h
+++ b/Modules/_io/clinic/stringio.c.h
@@ -135,6 +135,21 @@ _io_StringIO_readline(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
return return_value;
}
+static PyObject *
+stringio_iternext_impl(stringio *self);
+
+static PyObject *
+stringio_iternext(PyObject *self)
+{
+ PyObject *return_value = NULL;
+
+ Py_BEGIN_CRITICAL_SECTION(self);
+ return_value = stringio_iternext_impl((stringio *)self);
+ Py_END_CRITICAL_SECTION();
+
+ return return_value;
+}
+
PyDoc_STRVAR(_io_StringIO_truncate__doc__,
"truncate($self, pos=None, /)\n"
"--\n"
@@ -477,66 +492,48 @@ _io_StringIO___setstate__(PyObject *self, PyObject *state)
return return_value;
}
-#if !defined(_io_StringIO_closed_DOCSTR)
-# define _io_StringIO_closed_DOCSTR NULL
-#endif
-#if defined(_IO_STRINGIO_CLOSED_GETSETDEF)
-# undef _IO_STRINGIO_CLOSED_GETSETDEF
-# define _IO_STRINGIO_CLOSED_GETSETDEF {"closed", (getter)_io_StringIO_closed_get, (setter)_io_StringIO_closed_set, _io_StringIO_closed_DOCSTR},
-#else
-# define _IO_STRINGIO_CLOSED_GETSETDEF {"closed", (getter)_io_StringIO_closed_get, NULL, _io_StringIO_closed_DOCSTR},
-#endif
-
-static PyObject *
+static int
_io_StringIO_closed_get_impl(stringio *self);
static PyObject *
_io_StringIO_closed_get(PyObject *self, void *Py_UNUSED(context))
{
PyObject *return_value = NULL;
+ int _return_value;
Py_BEGIN_CRITICAL_SECTION(self);
- return_value = _io_StringIO_closed_get_impl((stringio *)self);
+ _return_value = _io_StringIO_closed_get_impl((stringio *)self);
Py_END_CRITICAL_SECTION();
+ if ((_return_value == -1) && PyErr_Occurred()) {
+ goto exit;
+ }
+ return_value = PyBool_FromLong((long)_return_value);
+exit:
return return_value;
}
-#if !defined(_io_StringIO_line_buffering_DOCSTR)
-# define _io_StringIO_line_buffering_DOCSTR NULL
-#endif
-#if defined(_IO_STRINGIO_LINE_BUFFERING_GETSETDEF)
-# undef _IO_STRINGIO_LINE_BUFFERING_GETSETDEF
-# define _IO_STRINGIO_LINE_BUFFERING_GETSETDEF {"line_buffering", (getter)_io_StringIO_line_buffering_get, (setter)_io_StringIO_line_buffering_set, _io_StringIO_line_buffering_DOCSTR},
-#else
-# define _IO_STRINGIO_LINE_BUFFERING_GETSETDEF {"line_buffering", (getter)_io_StringIO_line_buffering_get, NULL, _io_StringIO_line_buffering_DOCSTR},
-#endif
-
-static PyObject *
+static int
_io_StringIO_line_buffering_get_impl(stringio *self);
static PyObject *
_io_StringIO_line_buffering_get(PyObject *self, void *Py_UNUSED(context))
{
PyObject *return_value = NULL;
+ int _return_value;
Py_BEGIN_CRITICAL_SECTION(self);
- return_value = _io_StringIO_line_buffering_get_impl((stringio *)self);
+ _return_value = _io_StringIO_line_buffering_get_impl((stringio *)self);
Py_END_CRITICAL_SECTION();
+ if ((_return_value == -1) && PyErr_Occurred()) {
+ goto exit;
+ }
+ return_value = PyBool_FromLong((long)_return_value);
+exit:
return return_value;
}
-#if !defined(_io_StringIO_newlines_DOCSTR)
-# define _io_StringIO_newlines_DOCSTR NULL
-#endif
-#if defined(_IO_STRINGIO_NEWLINES_GETSETDEF)
-# undef _IO_STRINGIO_NEWLINES_GETSETDEF
-# define _IO_STRINGIO_NEWLINES_GETSETDEF {"newlines", (getter)_io_StringIO_newlines_get, (setter)_io_StringIO_newlines_set, _io_StringIO_newlines_DOCSTR},
-#else
-# define _IO_STRINGIO_NEWLINES_GETSETDEF {"newlines", (getter)_io_StringIO_newlines_get, NULL, _io_StringIO_newlines_DOCSTR},
-#endif
-
static PyObject *
_io_StringIO_newlines_get_impl(stringio *self);
@@ -551,4 +548,10 @@ _io_StringIO_newlines_get(PyObject *self, void *Py_UNUSED(context))
return return_value;
}
-/*[clinic end generated code: output=730c34b2a6c0500b input=a9049054013a1b77]*/
+#define _IO_STRINGIO_CLOSED_GETSETDEF {"closed", (getter)_io_StringIO_closed_get, (setter)NULL, NULL},
+
+#define _IO_STRINGIO_LINE_BUFFERING_GETSETDEF {"line_buffering", (getter)_io_StringIO_line_buffering_get, (setter)NULL, NULL},
+
+#define _IO_STRINGIO_NEWLINES_GETSETDEF {"newlines", (getter)_io_StringIO_newlines_get, (setter)NULL, NULL},
+
+/*[clinic end generated code: output=38a0385529d9cbef input=a9049054013a1b77]*/
diff --git a/Modules/_io/clinic/textio.c.h b/Modules/_io/clinic/textio.c.h
index 8d59bda5f74b386..954fee5cd2d4bfb 100644
--- a/Modules/_io/clinic/textio.c.h
+++ b/Modules/_io/clinic/textio.c.h
@@ -4,11 +4,12 @@ preserve
#if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
# include "pycore_gc.h" // PyGC_Head
-# include "pycore_runtime.h" // _Py_SINGLETON()
#endif
#include "pycore_abstract.h" // _Py_convert_optional_to_ssize_t()
#include "pycore_critical_section.h"// Py_BEGIN_CRITICAL_SECTION()
-#include "pycore_modsupport.h" // _PyArg_UnpackKeywords()
+#include "pycore_modsupport.h" // _PyArg_CheckPositional()
+#include "pycore_runtime.h" // _Py_SINGLETON()
+#include "pycore_unicodeobject.h" // _PyUnicode_AsUTF8NoNUL()
PyDoc_STRVAR(_io__TextIOBase_detach__doc__,
"detach($self, /)\n"
@@ -55,35 +56,22 @@ static PyObject *
_io__TextIOBase_read(PyObject *self, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "read",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
int size = -1;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 0, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("read", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("read", nargs, 0, 1)) {
goto exit;
}
if (nargs < 1) {
- goto skip_optional_posonly;
+ goto skip_optional;
}
size = PyLong_AsInt(args[0]);
if (size == -1 && PyErr_Occurred()) {
goto exit;
}
-skip_optional_posonly:
+skip_optional:
return_value = _io__TextIOBase_read_impl(self, cls, size);
exit:
@@ -110,35 +98,22 @@ static PyObject *
_io__TextIOBase_readline(PyObject *self, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "readline",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
int size = -1;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 0, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("readline", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("readline", nargs, 0, 1)) {
goto exit;
}
if (nargs < 1) {
- goto skip_optional_posonly;
+ goto skip_optional;
}
size = PyLong_AsInt(args[0]);
if (size == -1 && PyErr_Occurred()) {
goto exit;
}
-skip_optional_posonly:
+skip_optional:
return_value = _io__TextIOBase_readline_impl(self, cls, size);
exit:
@@ -165,40 +140,22 @@ static PyObject *
_io__TextIOBase_write(PyObject *self, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "write",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
const char *s;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("write", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("write", nargs, 1, 1)) {
goto exit;
}
if (!PyUnicode_Check(args[0])) {
_PyArg_BadArgument("write", "argument 1", "str", args[0]);
goto exit;
}
- Py_ssize_t s_length;
- s = PyUnicode_AsUTF8AndSize(args[0], &s_length);
+ s = _PyUnicode_AsUTF8NoNUL(args[0]);
if (s == NULL) {
goto exit;
}
- if (strlen(s) != (size_t)s_length) {
- PyErr_SetString(PyExc_ValueError, "embedded null character");
- goto exit;
- }
return_value = _io__TextIOBase_write_impl(self, cls, s);
exit:
@@ -209,20 +166,6 @@ PyDoc_STRVAR(_io__TextIOBase_encoding__doc__,
"Encoding of the text stream.\n"
"\n"
"Subclasses should override.");
-#if defined(_io__TextIOBase_encoding_DOCSTR)
-# undef _io__TextIOBase_encoding_DOCSTR
-#endif
-#define _io__TextIOBase_encoding_DOCSTR _io__TextIOBase_encoding__doc__
-
-#if !defined(_io__TextIOBase_encoding_DOCSTR)
-# define _io__TextIOBase_encoding_DOCSTR NULL
-#endif
-#if defined(_IO__TEXTIOBASE_ENCODING_GETSETDEF)
-# undef _IO__TEXTIOBASE_ENCODING_GETSETDEF
-# define _IO__TEXTIOBASE_ENCODING_GETSETDEF {"encoding", (getter)_io__TextIOBase_encoding_get, (setter)_io__TextIOBase_encoding_set, _io__TextIOBase_encoding_DOCSTR},
-#else
-# define _IO__TEXTIOBASE_ENCODING_GETSETDEF {"encoding", (getter)_io__TextIOBase_encoding_get, NULL, _io__TextIOBase_encoding_DOCSTR},
-#endif
static PyObject *
_io__TextIOBase_encoding_get_impl(PyObject *self);
@@ -239,20 +182,6 @@ PyDoc_STRVAR(_io__TextIOBase_newlines__doc__,
"Only line endings translated during reading are considered.\n"
"\n"
"Subclasses should override.");
-#if defined(_io__TextIOBase_newlines_DOCSTR)
-# undef _io__TextIOBase_newlines_DOCSTR
-#endif
-#define _io__TextIOBase_newlines_DOCSTR _io__TextIOBase_newlines__doc__
-
-#if !defined(_io__TextIOBase_newlines_DOCSTR)
-# define _io__TextIOBase_newlines_DOCSTR NULL
-#endif
-#if defined(_IO__TEXTIOBASE_NEWLINES_GETSETDEF)
-# undef _IO__TEXTIOBASE_NEWLINES_GETSETDEF
-# define _IO__TEXTIOBASE_NEWLINES_GETSETDEF {"newlines", (getter)_io__TextIOBase_newlines_get, (setter)_io__TextIOBase_newlines_set, _io__TextIOBase_newlines_DOCSTR},
-#else
-# define _IO__TEXTIOBASE_NEWLINES_GETSETDEF {"newlines", (getter)_io__TextIOBase_newlines_get, NULL, _io__TextIOBase_newlines_DOCSTR},
-#endif
static PyObject *
_io__TextIOBase_newlines_get_impl(PyObject *self);
@@ -267,20 +196,6 @@ PyDoc_STRVAR(_io__TextIOBase_errors__doc__,
"The error setting of the decoder or encoder.\n"
"\n"
"Subclasses should override.");
-#if defined(_io__TextIOBase_errors_DOCSTR)
-# undef _io__TextIOBase_errors_DOCSTR
-#endif
-#define _io__TextIOBase_errors_DOCSTR _io__TextIOBase_errors__doc__
-
-#if !defined(_io__TextIOBase_errors_DOCSTR)
-# define _io__TextIOBase_errors_DOCSTR NULL
-#endif
-#if defined(_IO__TEXTIOBASE_ERRORS_GETSETDEF)
-# undef _IO__TEXTIOBASE_ERRORS_GETSETDEF
-# define _IO__TEXTIOBASE_ERRORS_GETSETDEF {"errors", (getter)_io__TextIOBase_errors_get, (setter)_io__TextIOBase_errors_set, _io__TextIOBase_errors_DOCSTR},
-#else
-# define _IO__TEXTIOBASE_ERRORS_GETSETDEF {"errors", (getter)_io__TextIOBase_errors_get, NULL, _io__TextIOBase_errors_DOCSTR},
-#endif
static PyObject *
_io__TextIOBase_errors_get_impl(PyObject *self);
@@ -310,7 +225,8 @@ _io_IncrementalNewlineDecoder___init___impl(nldecoder_object *self,
PyObject *errors);
static int
-_io_IncrementalNewlineDecoder___init__(PyObject *self, PyObject *args, PyObject *kwargs)
+_io_IncrementalNewlineDecoder___init___helper(PyObject *self, PyObject *const *args,
+ Py_ssize_t nargs, Py_ssize_t nkw, PyObject *kwargs, PyObject *kwnames)
{
int return_value = -1;
#if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
@@ -342,13 +258,12 @@ _io_IncrementalNewlineDecoder___init__(PyObject *self, PyObject *args, PyObject
#undef KWTUPLE
PyObject *argsbuf[3];
PyObject * const *fastargs;
- Py_ssize_t nargs = PyTuple_GET_SIZE(args);
- Py_ssize_t noptargs = nargs + (kwargs ? PyDict_GET_SIZE(kwargs) : 0) - 2;
+ Py_ssize_t noptargs = nargs + nkw - 2;
PyObject *decoder;
int translate;
PyObject *errors = NULL;
- fastargs = _PyArg_UnpackKeywords(_PyTuple_CAST(args)->ob_item, nargs, kwargs, NULL, &_parser,
+ fastargs = _PyArg_UnpackKeywords(args, nargs, kwargs, kwnames, &_parser,
/*minpos*/ 2, /*maxpos*/ 3, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
if (!fastargs) {
goto exit;
@@ -369,6 +284,72 @@ _io_IncrementalNewlineDecoder___init__(PyObject *self, PyObject *args, PyObject
return return_value;
}
+static int
+_io_IncrementalNewlineDecoder___init__(PyObject *self, PyObject *args, PyObject *kwargs)
+{
+ return _io_IncrementalNewlineDecoder___init___helper(self, _PyTuple_CAST(args)->ob_item,
+ PyTuple_GET_SIZE(args),
+ kwargs ? PyDict_GET_SIZE(kwargs) : 0,
+ kwargs, NULL);
+}
+
+static PyObject *
+_io_IncrementalNewlineDecoder_vectorcall(PyObject *type, PyObject *const *args,
+ size_t nargsf, PyObject *kwnames)
+{
+ PyObject *return_value = NULL;
+ Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
+ PyObject *self;
+ int _result;
+ PyObject *decoder;
+ int translate;
+ PyObject *errors = NULL;
+
+ assert(_PyType_CAST(type)->tp_init == _io_IncrementalNewlineDecoder___init__);
+ /* Make sure the type object is immutable: the generated
+ * vectorcall doesn't deal e.g. with users reassigning __init__. */
+ assert(PyType_HasFeature(_PyType_CAST(type), Py_TPFLAGS_IMMUTABLETYPE));
+ if (kwnames != NULL || nargs < 2 || nargs > 3) {
+ self = _PyType_CAST(type)->tp_new(_PyType_CAST(type),
+ (PyObject *)&_Py_SINGLETON(tuple_empty), NULL);
+ if (self == NULL) {
+ return NULL;
+ }
+ _result = _io_IncrementalNewlineDecoder___init___helper(self, args, nargs,
+ kwnames ? PyTuple_GET_SIZE(kwnames) : 0,
+ NULL, kwnames);
+ if (_result != 0) {
+ Py_DECREF(self);
+ return NULL;
+ }
+ return self;
+ }
+ decoder = args[0];
+ translate = PyObject_IsTrue(args[1]);
+ if (translate < 0) {
+ goto exit;
+ }
+ if (nargs < 3) {
+ goto skip_optional;
+ }
+ errors = args[2];
+skip_optional:
+ self = _PyType_CAST(type)->tp_new(_PyType_CAST(type),
+ (PyObject *)&_Py_SINGLETON(tuple_empty), NULL);
+ if (self == NULL) {
+ goto exit;
+ }
+ _result = _io_IncrementalNewlineDecoder___init___impl((nldecoder_object *)self, decoder, translate, errors);
+ if (_result != 0) {
+ Py_DECREF(self);
+ goto exit;
+ }
+ return_value = self;
+
+exit:
+ return return_value;
+}
+
PyDoc_STRVAR(_io_IncrementalNewlineDecoder_decode__doc__,
"decode($self, /, input, final=False)\n"
"--\n"
@@ -509,6 +490,15 @@ _io_IncrementalNewlineDecoder_reset(PyObject *self, PyObject *Py_UNUSED(ignored)
return return_value;
}
+static PyObject *
+_io_IncrementalNewlineDecoder_newlines_get_impl(nldecoder_object *self);
+
+static PyObject *
+_io_IncrementalNewlineDecoder_newlines_get(PyObject *self, void *Py_UNUSED(context))
+{
+ return _io_IncrementalNewlineDecoder_newlines_get_impl((nldecoder_object *)self);
+}
+
PyDoc_STRVAR(_io_TextIOWrapper___init____doc__,
"TextIOWrapper(buffer, encoding=None, errors=None, newline=None,\n"
" line_buffering=False, write_through=False)\n"
@@ -517,7 +507,10 @@ PyDoc_STRVAR(_io_TextIOWrapper___init____doc__,
"Character and line based layer over a BufferedIOBase object, buffer.\n"
"\n"
"encoding gives the name of the encoding that the stream will be\n"
-"decoded or encoded with. It defaults to locale.getencoding().\n"
+"decoded or encoded with. It defaults to UTF-8; if UTF-8 Mode is\n"
+"disabled, the encoding returned by locale.getencoding() is used\n"
+"instead. See the codecs module for the list of supported\n"
+"encodings.\n"
"\n"
"errors determines the strictness of encoding and decoding (see\n"
"help(codecs.Codec) or the documentation for codecs.register) and\n"
@@ -605,15 +598,10 @@ _io_TextIOWrapper___init__(PyObject *self, PyObject *args, PyObject *kwargs)
encoding = NULL;
}
else if (PyUnicode_Check(fastargs[1])) {
- Py_ssize_t encoding_length;
- encoding = PyUnicode_AsUTF8AndSize(fastargs[1], &encoding_length);
+ encoding = _PyUnicode_AsUTF8NoNUL(fastargs[1]);
if (encoding == NULL) {
goto exit;
}
- if (strlen(encoding) != (size_t)encoding_length) {
- PyErr_SetString(PyExc_ValueError, "embedded null character");
- goto exit;
- }
}
else {
_PyArg_BadArgument("TextIOWrapper", "argument 'encoding'", "str or None", fastargs[1]);
@@ -634,15 +622,10 @@ _io_TextIOWrapper___init__(PyObject *self, PyObject *args, PyObject *kwargs)
newline = NULL;
}
else if (PyUnicode_Check(fastargs[3])) {
- Py_ssize_t newline_length;
- newline = PyUnicode_AsUTF8AndSize(fastargs[3], &newline_length);
+ newline = _PyUnicode_AsUTF8NoNUL(fastargs[3]);
if (newline == NULL) {
goto exit;
}
- if (strlen(newline) != (size_t)newline_length) {
- PyErr_SetString(PyExc_ValueError, "embedded null character");
- goto exit;
- }
}
else {
_PyArg_BadArgument("TextIOWrapper", "argument 'newline'", "str or None", fastargs[3]);
@@ -1182,15 +1165,20 @@ _io_TextIOWrapper_close(PyObject *self, PyObject *Py_UNUSED(ignored))
return return_value;
}
-#if !defined(_io_TextIOWrapper_name_DOCSTR)
-# define _io_TextIOWrapper_name_DOCSTR NULL
-#endif
-#if defined(_IO_TEXTIOWRAPPER_NAME_GETSETDEF)
-# undef _IO_TEXTIOWRAPPER_NAME_GETSETDEF
-# define _IO_TEXTIOWRAPPER_NAME_GETSETDEF {"name", (getter)_io_TextIOWrapper_name_get, (setter)_io_TextIOWrapper_name_set, _io_TextIOWrapper_name_DOCSTR},
-#else
-# define _IO_TEXTIOWRAPPER_NAME_GETSETDEF {"name", (getter)_io_TextIOWrapper_name_get, NULL, _io_TextIOWrapper_name_DOCSTR},
-#endif
+static PyObject *
+textiowrapper_iternext_impl(textio *self);
+
+static PyObject *
+textiowrapper_iternext(PyObject *self)
+{
+ PyObject *return_value = NULL;
+
+ Py_BEGIN_CRITICAL_SECTION(self);
+ return_value = textiowrapper_iternext_impl((textio *)self);
+ Py_END_CRITICAL_SECTION();
+
+ return return_value;
+}
static PyObject *
_io_TextIOWrapper_name_get_impl(textio *self);
@@ -1207,16 +1195,6 @@ _io_TextIOWrapper_name_get(PyObject *self, void *Py_UNUSED(context))
return return_value;
}
-#if !defined(_io_TextIOWrapper_closed_DOCSTR)
-# define _io_TextIOWrapper_closed_DOCSTR NULL
-#endif
-#if defined(_IO_TEXTIOWRAPPER_CLOSED_GETSETDEF)
-# undef _IO_TEXTIOWRAPPER_CLOSED_GETSETDEF
-# define _IO_TEXTIOWRAPPER_CLOSED_GETSETDEF {"closed", (getter)_io_TextIOWrapper_closed_get, (setter)_io_TextIOWrapper_closed_set, _io_TextIOWrapper_closed_DOCSTR},
-#else
-# define _IO_TEXTIOWRAPPER_CLOSED_GETSETDEF {"closed", (getter)_io_TextIOWrapper_closed_get, NULL, _io_TextIOWrapper_closed_DOCSTR},
-#endif
-
static PyObject *
_io_TextIOWrapper_closed_get_impl(textio *self);
@@ -1232,16 +1210,6 @@ _io_TextIOWrapper_closed_get(PyObject *self, void *Py_UNUSED(context))
return return_value;
}
-#if !defined(_io_TextIOWrapper_newlines_DOCSTR)
-# define _io_TextIOWrapper_newlines_DOCSTR NULL
-#endif
-#if defined(_IO_TEXTIOWRAPPER_NEWLINES_GETSETDEF)
-# undef _IO_TEXTIOWRAPPER_NEWLINES_GETSETDEF
-# define _IO_TEXTIOWRAPPER_NEWLINES_GETSETDEF {"newlines", (getter)_io_TextIOWrapper_newlines_get, (setter)_io_TextIOWrapper_newlines_set, _io_TextIOWrapper_newlines_DOCSTR},
-#else
-# define _IO_TEXTIOWRAPPER_NEWLINES_GETSETDEF {"newlines", (getter)_io_TextIOWrapper_newlines_get, NULL, _io_TextIOWrapper_newlines_DOCSTR},
-#endif
-
static PyObject *
_io_TextIOWrapper_newlines_get_impl(textio *self);
@@ -1257,16 +1225,6 @@ _io_TextIOWrapper_newlines_get(PyObject *self, void *Py_UNUSED(context))
return return_value;
}
-#if !defined(_io_TextIOWrapper_errors_DOCSTR)
-# define _io_TextIOWrapper_errors_DOCSTR NULL
-#endif
-#if defined(_IO_TEXTIOWRAPPER_ERRORS_GETSETDEF)
-# undef _IO_TEXTIOWRAPPER_ERRORS_GETSETDEF
-# define _IO_TEXTIOWRAPPER_ERRORS_GETSETDEF {"errors", (getter)_io_TextIOWrapper_errors_get, (setter)_io_TextIOWrapper_errors_set, _io_TextIOWrapper_errors_DOCSTR},
-#else
-# define _IO_TEXTIOWRAPPER_ERRORS_GETSETDEF {"errors", (getter)_io_TextIOWrapper_errors_get, NULL, _io_TextIOWrapper_errors_DOCSTR},
-#endif
-
static PyObject *
_io_TextIOWrapper_errors_get_impl(textio *self);
@@ -1282,53 +1240,94 @@ _io_TextIOWrapper_errors_get(PyObject *self, void *Py_UNUSED(context))
return return_value;
}
-#if !defined(_io_TextIOWrapper__CHUNK_SIZE_DOCSTR)
-# define _io_TextIOWrapper__CHUNK_SIZE_DOCSTR NULL
-#endif
-#if defined(_IO_TEXTIOWRAPPER__CHUNK_SIZE_GETSETDEF)
-# undef _IO_TEXTIOWRAPPER__CHUNK_SIZE_GETSETDEF
-# define _IO_TEXTIOWRAPPER__CHUNK_SIZE_GETSETDEF {"_CHUNK_SIZE", (getter)_io_TextIOWrapper__CHUNK_SIZE_get, (setter)_io_TextIOWrapper__CHUNK_SIZE_set, _io_TextIOWrapper__CHUNK_SIZE_DOCSTR},
-#else
-# define _IO_TEXTIOWRAPPER__CHUNK_SIZE_GETSETDEF {"_CHUNK_SIZE", (getter)_io_TextIOWrapper__CHUNK_SIZE_get, NULL, _io_TextIOWrapper__CHUNK_SIZE_DOCSTR},
-#endif
-
-static PyObject *
+static Py_ssize_t
_io_TextIOWrapper__CHUNK_SIZE_get_impl(textio *self);
static PyObject *
_io_TextIOWrapper__CHUNK_SIZE_get(PyObject *self, void *Py_UNUSED(context))
{
PyObject *return_value = NULL;
+ Py_ssize_t _return_value;
Py_BEGIN_CRITICAL_SECTION(self);
- return_value = _io_TextIOWrapper__CHUNK_SIZE_get_impl((textio *)self);
+ _return_value = _io_TextIOWrapper__CHUNK_SIZE_get_impl((textio *)self);
Py_END_CRITICAL_SECTION();
+ if ((_return_value == -1) && PyErr_Occurred()) {
+ goto exit;
+ }
+ return_value = PyLong_FromSsize_t(_return_value);
+exit:
return return_value;
}
-#if !defined(_io_TextIOWrapper__CHUNK_SIZE_DOCSTR)
-# define _io_TextIOWrapper__CHUNK_SIZE_DOCSTR NULL
-#endif
-#if defined(_IO_TEXTIOWRAPPER__CHUNK_SIZE_GETSETDEF)
-# undef _IO_TEXTIOWRAPPER__CHUNK_SIZE_GETSETDEF
-# define _IO_TEXTIOWRAPPER__CHUNK_SIZE_GETSETDEF {"_CHUNK_SIZE", (getter)_io_TextIOWrapper__CHUNK_SIZE_get, (setter)_io_TextIOWrapper__CHUNK_SIZE_set, _io_TextIOWrapper__CHUNK_SIZE_DOCSTR},
-#else
-# define _IO_TEXTIOWRAPPER__CHUNK_SIZE_GETSETDEF {"_CHUNK_SIZE", NULL, (setter)_io_TextIOWrapper__CHUNK_SIZE_set, NULL},
-#endif
-
static int
-_io_TextIOWrapper__CHUNK_SIZE_set_impl(textio *self, PyObject *value);
+_io_TextIOWrapper__CHUNK_SIZE_set_impl(textio *self, Py_ssize_t value);
static int
-_io_TextIOWrapper__CHUNK_SIZE_set(PyObject *self, PyObject *value, void *Py_UNUSED(context))
+_io_TextIOWrapper__CHUNK_SIZE_set(PyObject *self, PyObject *arg, void *Py_UNUSED(context))
{
- int return_value;
+ int return_value = -1;
+ Py_ssize_t value;
+ if (arg == NULL) {
+ PyErr_Format(PyExc_AttributeError,
+ "attribute '_CHUNK_SIZE' of '%.100s' objects cannot be deleted",
+ Py_TYPE(self)->tp_name);
+ return -1;
+ }
+ {
+ Py_ssize_t ival = -1;
+ PyObject *iobj = _PyNumber_Index(arg);
+ if (iobj != NULL) {
+ ival = PyLong_AsSsize_t(iobj);
+ Py_DECREF(iobj);
+ }
+ if (ival == -1 && PyErr_Occurred()) {
+ goto exit;
+ }
+ value = ival;
+ }
Py_BEGIN_CRITICAL_SECTION(self);
return_value = _io_TextIOWrapper__CHUNK_SIZE_set_impl((textio *)self, value);
Py_END_CRITICAL_SECTION();
+exit:
return return_value;
}
-/*[clinic end generated code: output=8c571c9dba87d2b1 input=a9049054013a1b77]*/
+
+static PyObject *
+_io_TextIOWrapper_buffer_get_impl(textio *self);
+
+static PyObject *
+_io_TextIOWrapper_buffer_get(PyObject *self, void *Py_UNUSED(context))
+{
+ PyObject *return_value = NULL;
+
+ Py_BEGIN_CRITICAL_SECTION(self);
+ return_value = _io_TextIOWrapper_buffer_get_impl((textio *)self);
+ Py_END_CRITICAL_SECTION();
+
+ return return_value;
+}
+#define _IO__TEXTIOBASE_ENCODING_GETSETDEF {"encoding", (getter)_io__TextIOBase_encoding_get, (setter)NULL, _io__TextIOBase_encoding__doc__},
+
+#define _IO__TEXTIOBASE_NEWLINES_GETSETDEF {"newlines", (getter)_io__TextIOBase_newlines_get, (setter)NULL, _io__TextIOBase_newlines__doc__},
+
+#define _IO__TEXTIOBASE_ERRORS_GETSETDEF {"errors", (getter)_io__TextIOBase_errors_get, (setter)NULL, _io__TextIOBase_errors__doc__},
+
+#define _IO_INCREMENTALNEWLINEDECODER_NEWLINES_GETSETDEF {"newlines", (getter)_io_IncrementalNewlineDecoder_newlines_get, (setter)NULL, NULL},
+
+#define _IO_TEXTIOWRAPPER_NAME_GETSETDEF {"name", (getter)_io_TextIOWrapper_name_get, (setter)NULL, NULL},
+
+#define _IO_TEXTIOWRAPPER_CLOSED_GETSETDEF {"closed", (getter)_io_TextIOWrapper_closed_get, (setter)NULL, NULL},
+
+#define _IO_TEXTIOWRAPPER_NEWLINES_GETSETDEF {"newlines", (getter)_io_TextIOWrapper_newlines_get, (setter)NULL, NULL},
+
+#define _IO_TEXTIOWRAPPER_ERRORS_GETSETDEF {"errors", (getter)_io_TextIOWrapper_errors_get, (setter)NULL, NULL},
+
+#define _IO_TEXTIOWRAPPER__CHUNK_SIZE_GETSETDEF {"_CHUNK_SIZE", (getter)_io_TextIOWrapper__CHUNK_SIZE_get, (setter)_io_TextIOWrapper__CHUNK_SIZE_set, NULL},
+
+#define _IO_TEXTIOWRAPPER_BUFFER_GETSETDEF {"buffer", (getter)_io_TextIOWrapper_buffer_get, (setter)NULL, NULL},
+
+/*[clinic end generated code: output=d96cd0f7c06f36f5 input=a9049054013a1b77]*/
diff --git a/Modules/_io/clinic/winconsoleio.c.h b/Modules/_io/clinic/winconsoleio.c.h
index bd8073cd0af3f64..76baeb79e68cd0b 100644
--- a/Modules/_io/clinic/winconsoleio.c.h
+++ b/Modules/_io/clinic/winconsoleio.c.h
@@ -8,6 +8,7 @@ preserve
#endif
#include "pycore_abstract.h" // _Py_convert_optional_to_ssize_t()
#include "pycore_modsupport.h" // _PyArg_UnpackKeywords()
+#include "pycore_unicodeobject.h" // _PyUnicode_AsUTF8NoNUL()
#if defined(HAVE_WINDOWS_CONSOLE_IO)
@@ -109,15 +110,10 @@ _io__WindowsConsoleIO___init__(PyObject *self, PyObject *args, PyObject *kwargs)
_PyArg_BadArgument("_WindowsConsoleIO", "argument 'mode'", "str", fastargs[1]);
goto exit;
}
- Py_ssize_t mode_length;
- mode = PyUnicode_AsUTF8AndSize(fastargs[1], &mode_length);
+ mode = _PyUnicode_AsUTF8NoNUL(fastargs[1]);
if (mode == NULL) {
goto exit;
}
- if (strlen(mode) != (size_t)mode_length) {
- PyErr_SetString(PyExc_ValueError, "embedded null character");
- goto exit;
- }
if (!--noptargs) {
goto skip_optional_pos;
}
@@ -226,25 +222,12 @@ static PyObject *
_io__WindowsConsoleIO_readinto(PyObject *self, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "readinto",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
Py_buffer buffer = {NULL, NULL};
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("readinto", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("readinto", nargs, 1, 1)) {
goto exit;
}
if (PyObject_GetBuffer(args[0], &buffer, PyBUF_WRITABLE) < 0) {
@@ -311,34 +294,21 @@ static PyObject *
_io__WindowsConsoleIO_read(PyObject *self, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "read",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
Py_ssize_t size = -1;
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 0, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("read", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("read", nargs, 0, 1)) {
goto exit;
}
if (nargs < 1) {
- goto skip_optional_posonly;
+ goto skip_optional;
}
if (!_Py_convert_optional_to_ssize_t(args[0], &size)) {
goto exit;
}
-skip_optional_posonly:
+skip_optional:
return_value = _io__WindowsConsoleIO_read_impl((winconsoleio *)self, cls, size);
exit:
@@ -369,25 +339,12 @@ static PyObject *
_io__WindowsConsoleIO_write(PyObject *self, PyTypeObject *cls, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- # define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
- #else
- # define KWTUPLE NULL
- #endif
-
- static const char * const _keywords[] = {"", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "write",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
Py_buffer b = {NULL, NULL};
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
- /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
- if (!args) {
+ if (!_PyArg_NoKwnames("write", kwnames)) {
+ goto exit;
+ }
+ if (!_PyArg_CheckPositional("write", nargs, 1, 1)) {
goto exit;
}
if (PyObject_GetBuffer(args[0], &b, PyBUF_SIMPLE) != 0) {
@@ -428,6 +385,92 @@ _io__WindowsConsoleIO_isatty(PyObject *self, PyObject *Py_UNUSED(ignored))
#endif /* defined(HAVE_WINDOWS_CONSOLE_IO) */
+#if defined(HAVE_WINDOWS_CONSOLE_IO)
+
+PyDoc_STRVAR(_io__WindowsConsoleIO_closed__doc__,
+"True if the file is closed.");
+#if defined(_IO__WINDOWSCONSOLEIO_CLOSED_DOCSTR)
+# undef _IO__WINDOWSCONSOLEIO_CLOSED_DOCSTR
+#endif
+#define _IO__WINDOWSCONSOLEIO_CLOSED_DOCSTR _io__WindowsConsoleIO_closed__doc__
+
+#define _IO__WINDOWSCONSOLEIO_CLOSED_GETTER _io__WindowsConsoleIO_closed_get
+
+static int
+_io__WindowsConsoleIO_closed_get_impl(winconsoleio *self);
+
+static PyObject *
+_io__WindowsConsoleIO_closed_get(PyObject *self, void *Py_UNUSED(context))
+{
+ PyObject *return_value = NULL;
+ int _return_value;
+
+ _return_value = _io__WindowsConsoleIO_closed_get_impl((winconsoleio *)self);
+ if ((_return_value == -1) && PyErr_Occurred()) {
+ goto exit;
+ }
+ return_value = PyBool_FromLong((long)_return_value);
+
+exit:
+ return return_value;
+}
+
+#endif /* defined(HAVE_WINDOWS_CONSOLE_IO) */
+
+#if defined(HAVE_WINDOWS_CONSOLE_IO)
+
+PyDoc_STRVAR(_io__WindowsConsoleIO_closefd__doc__,
+"True if the file descriptor will be closed by close().");
+#if defined(_IO__WINDOWSCONSOLEIO_CLOSEFD_DOCSTR)
+# undef _IO__WINDOWSCONSOLEIO_CLOSEFD_DOCSTR
+#endif
+#define _IO__WINDOWSCONSOLEIO_CLOSEFD_DOCSTR _io__WindowsConsoleIO_closefd__doc__
+
+#define _IO__WINDOWSCONSOLEIO_CLOSEFD_GETTER _io__WindowsConsoleIO_closefd_get
+
+static int
+_io__WindowsConsoleIO_closefd_get_impl(winconsoleio *self);
+
+static PyObject *
+_io__WindowsConsoleIO_closefd_get(PyObject *self, void *Py_UNUSED(context))
+{
+ PyObject *return_value = NULL;
+ int _return_value;
+
+ _return_value = _io__WindowsConsoleIO_closefd_get_impl((winconsoleio *)self);
+ if ((_return_value == -1) && PyErr_Occurred()) {
+ goto exit;
+ }
+ return_value = PyBool_FromLong((long)_return_value);
+
+exit:
+ return return_value;
+}
+
+#endif /* defined(HAVE_WINDOWS_CONSOLE_IO) */
+
+#if defined(HAVE_WINDOWS_CONSOLE_IO)
+
+PyDoc_STRVAR(_io__WindowsConsoleIO_mode__doc__,
+"String giving the file mode.");
+#if defined(_IO__WINDOWSCONSOLEIO_MODE_DOCSTR)
+# undef _IO__WINDOWSCONSOLEIO_MODE_DOCSTR
+#endif
+#define _IO__WINDOWSCONSOLEIO_MODE_DOCSTR _io__WindowsConsoleIO_mode__doc__
+
+#define _IO__WINDOWSCONSOLEIO_MODE_GETTER _io__WindowsConsoleIO_mode_get
+
+static PyObject *
+_io__WindowsConsoleIO_mode_get_impl(winconsoleio *self);
+
+static PyObject *
+_io__WindowsConsoleIO_mode_get(PyObject *self, void *Py_UNUSED(context))
+{
+ return _io__WindowsConsoleIO_mode_get_impl((winconsoleio *)self);
+}
+
+#endif /* defined(HAVE_WINDOWS_CONSOLE_IO) */
+
#ifndef _IO__WINDOWSCONSOLEIO_CLOSE_METHODDEF
#define _IO__WINDOWSCONSOLEIO_CLOSE_METHODDEF
#endif /* !defined(_IO__WINDOWSCONSOLEIO_CLOSE_METHODDEF) */
@@ -463,4 +506,49 @@ _io__WindowsConsoleIO_isatty(PyObject *self, PyObject *Py_UNUSED(ignored))
#ifndef _IO__WINDOWSCONSOLEIO_ISATTY_METHODDEF
#define _IO__WINDOWSCONSOLEIO_ISATTY_METHODDEF
#endif /* !defined(_IO__WINDOWSCONSOLEIO_ISATTY_METHODDEF) */
-/*[clinic end generated code: output=dfe49dd71f4f4b1d input=a9049054013a1b77]*/
+#if defined(_IO__WINDOWSCONSOLEIO_CLOSED_GETTER) || defined(_IO__WINDOWSCONSOLEIO_CLOSED_SETTER)
+# if !defined(_IO__WINDOWSCONSOLEIO_CLOSED_GETTER)
+# define _IO__WINDOWSCONSOLEIO_CLOSED_GETTER NULL
+# endif
+# if !defined(_IO__WINDOWSCONSOLEIO_CLOSED_SETTER)
+# define _IO__WINDOWSCONSOLEIO_CLOSED_SETTER NULL
+# endif
+# if !defined(_IO__WINDOWSCONSOLEIO_CLOSED_DOCSTR)
+# define _IO__WINDOWSCONSOLEIO_CLOSED_DOCSTR NULL
+# endif
+# define _IO__WINDOWSCONSOLEIO_CLOSED_GETSETDEF {"closed", (getter)_IO__WINDOWSCONSOLEIO_CLOSED_GETTER, (setter)_IO__WINDOWSCONSOLEIO_CLOSED_SETTER, _IO__WINDOWSCONSOLEIO_CLOSED_DOCSTR},
+#else
+# define _IO__WINDOWSCONSOLEIO_CLOSED_GETSETDEF
+#endif
+
+#if defined(_IO__WINDOWSCONSOLEIO_CLOSEFD_GETTER) || defined(_IO__WINDOWSCONSOLEIO_CLOSEFD_SETTER)
+# if !defined(_IO__WINDOWSCONSOLEIO_CLOSEFD_GETTER)
+# define _IO__WINDOWSCONSOLEIO_CLOSEFD_GETTER NULL
+# endif
+# if !defined(_IO__WINDOWSCONSOLEIO_CLOSEFD_SETTER)
+# define _IO__WINDOWSCONSOLEIO_CLOSEFD_SETTER NULL
+# endif
+# if !defined(_IO__WINDOWSCONSOLEIO_CLOSEFD_DOCSTR)
+# define _IO__WINDOWSCONSOLEIO_CLOSEFD_DOCSTR NULL
+# endif
+# define _IO__WINDOWSCONSOLEIO_CLOSEFD_GETSETDEF {"closefd", (getter)_IO__WINDOWSCONSOLEIO_CLOSEFD_GETTER, (setter)_IO__WINDOWSCONSOLEIO_CLOSEFD_SETTER, _IO__WINDOWSCONSOLEIO_CLOSEFD_DOCSTR},
+#else
+# define _IO__WINDOWSCONSOLEIO_CLOSEFD_GETSETDEF
+#endif
+
+#if defined(_IO__WINDOWSCONSOLEIO_MODE_GETTER) || defined(_IO__WINDOWSCONSOLEIO_MODE_SETTER)
+# if !defined(_IO__WINDOWSCONSOLEIO_MODE_GETTER)
+# define _IO__WINDOWSCONSOLEIO_MODE_GETTER NULL
+# endif
+# if !defined(_IO__WINDOWSCONSOLEIO_MODE_SETTER)
+# define _IO__WINDOWSCONSOLEIO_MODE_SETTER NULL
+# endif
+# if !defined(_IO__WINDOWSCONSOLEIO_MODE_DOCSTR)
+# define _IO__WINDOWSCONSOLEIO_MODE_DOCSTR NULL
+# endif
+# define _IO__WINDOWSCONSOLEIO_MODE_GETSETDEF {"mode", (getter)_IO__WINDOWSCONSOLEIO_MODE_GETTER, (setter)_IO__WINDOWSCONSOLEIO_MODE_SETTER, _IO__WINDOWSCONSOLEIO_MODE_DOCSTR},
+#else
+# define _IO__WINDOWSCONSOLEIO_MODE_GETSETDEF
+#endif
+
+/*[clinic end generated code: output=7c7499116eefd498 input=a9049054013a1b77]*/
diff --git a/Modules/_io/fileio.c b/Modules/_io/fileio.c
index 3aeb30dfe24a357..a954bc5cd407d27 100644
--- a/Modules/_io/fileio.c
+++ b/Modules/_io/fileio.c
@@ -1,10 +1,10 @@
/* Author: Daniel Stutzbach */
#include "Python.h"
+#include "pycore_abstract.h" // _PyIndex_Check()
#include "pycore_fileutils.h" // _Py_BEGIN_SUPPRESS_IPH
#include "pycore_object.h" // _PyObject_GC_UNTRACK()
#include "pycore_pyerrors.h" // _PyErr_ChainExceptions1()
-#include "pycore_weakref.h" // FT_CLEAR_WEAKREFS()
#include // bool
#ifdef HAVE_UNISTD_H
@@ -80,8 +80,6 @@ typedef struct {
modified outside of the fileio object / Python (ex. gh-90102, GH-121941,
gh-109523). */
struct _Py_stat_struct *stat_atopen;
- PyObject *weakreflist;
- PyObject *dict;
} fileio;
#define PyFileIO_Check(state, op) (PyObject_TypeCheck((op), state->PyFileIO_Type))
@@ -99,10 +97,17 @@ _PyFileIO_closed(PyObject *self)
/* Because this can call arbitrary code, it shouldn't be called when
the refcount is 0 (that is, not directly from tp_dealloc unless
the refcount has been temporarily re-incremented). */
+/*[clinic input]
+_io.FileIO._dealloc_warn
+
+ source: object
+ /
+[clinic start generated code]*/
+
static PyObject *
-fileio_dealloc_warn(PyObject *op, PyObject *source)
+_io_FileIO__dealloc_warn_impl(fileio *self, PyObject *source)
+/*[clinic end generated code: output=c7b7d122decd6575 input=3ea7e1cc0685edc2]*/
{
- fileio *self = PyFileIO_CAST(op);
if (self->fd >= 0 && self->closefd) {
PyObject *exc = PyErr_GetRaisedException();
if (PyErr_ResourceWarning(source, 1, "unclosed file %R", source)) {
@@ -176,7 +181,7 @@ _io_FileIO_close_impl(fileio *self, PyTypeObject *cls)
exc = PyErr_GetRaisedException();
}
if (self->finalizing) {
- PyObject *r = fileio_dealloc_warn((PyObject*)self, (PyObject *) self);
+ PyObject *r = _io_FileIO__dealloc_warn_impl(self, (PyObject *)self);
if (r) {
Py_DECREF(r);
}
@@ -213,7 +218,6 @@ fileio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
self->truncate = 0;
self->stat_atopen = NULL;
self->closefd = 1;
- self->weakreflist = NULL;
return (PyObject *) self;
}
@@ -293,14 +297,17 @@ _io_FileIO___init___impl(fileio *self, PyObject *nameobj, const char *mode,
return -1;
}
}
- fd = PyLong_AsInt(nameobj);
- if (fd < 0) {
- if (!PyErr_Occurred()) {
- PyErr_SetString(PyExc_ValueError,
- "negative file descriptor");
- return -1;
+ if (_PyIndex_Check(nameobj)) {
+ fd = PyLong_AsInt(nameobj);
+ if (fd < 0) {
+ if (!PyErr_Occurred()) {
+ PyErr_SetString(PyExc_ValueError,
+ "negative file descriptor");
+ return -1;
+ }
+ /* Failed to convert; try other paths. */
+ PyErr_Clear();
}
- PyErr_Clear();
}
if (fd < 0) {
@@ -551,15 +558,13 @@ fileio_traverse(PyObject *op, visitproc visit, void *arg)
{
fileio *self = PyFileIO_CAST(op);
Py_VISIT(Py_TYPE(self));
- Py_VISIT(self->dict);
- return 0;
+ return PyObject_VisitManagedDict(op, visit, arg);
}
static int
fileio_clear(PyObject *op)
{
- fileio *self = PyFileIO_CAST(op);
- Py_CLEAR(self->dict);
+ PyObject_ClearManagedDict(op);
return 0;
}
@@ -577,7 +582,7 @@ fileio_dealloc(PyObject *op)
PyMem_Free(self->stat_atopen);
self->stat_atopen = NULL;
}
- FT_CLEAR_WEAKREFS(op, self->weakreflist);
+ PyObject_ClearWeakRefs(op);
(void)fileio_clear(op);
PyTypeObject *tp = Py_TYPE(op);
@@ -992,7 +997,14 @@ portable_lseek(fileio *self, PyObject *posobj, int whence, bool suppress_pipe_er
Py_BEGIN_ALLOW_THREADS
_Py_BEGIN_SUPPRESS_IPH
#ifdef MS_WINDOWS
- res = _lseeki64(fd, pos, whence);
+ HANDLE h = (HANDLE)_get_osfhandle(fd);
+ if (h != INVALID_HANDLE_VALUE && GetFileType(h) == FILE_TYPE_PIPE) {
+ res = -1;
+ errno = ESPIPE;
+ }
+ else {
+ res = _lseeki64(fd, pos, whence);
+ }
#else
res = lseek(fd, pos, whence);
#endif
@@ -1243,10 +1255,14 @@ _io_FileIO_isatty_impl(fileio *self)
information. Use the stat result to skip a system call. Outside of that
context TOCTOU issues (the fd could be arbitrarily modified by
surrounding code). */
+/*[clinic input]
+_io.FileIO._isatty_open_only
+[clinic start generated code]*/
+
static PyObject *
-_io_FileIO_isatty_open_only(PyObject *op, PyObject *Py_UNUSED(dummy))
+_io_FileIO__isatty_open_only_impl(fileio *self)
+/*[clinic end generated code: output=2b4689154d4b8b84 input=228767ff567cdfb6]*/
{
- fileio *self = PyFileIO_CAST(op);
if (self->stat_atopen != NULL && !S_ISCHR(self->stat_atopen->st_mode)) {
Py_RETURN_FALSE;
}
@@ -1269,60 +1285,85 @@ static PyMethodDef fileio_methods[] = {
_IO_FILEIO_WRITABLE_METHODDEF
_IO_FILEIO_FILENO_METHODDEF
_IO_FILEIO_ISATTY_METHODDEF
- {"_isatty_open_only", _io_FileIO_isatty_open_only, METH_NOARGS},
- {"_dealloc_warn", fileio_dealloc_warn, METH_O, NULL},
+ _IO_FILEIO__ISATTY_OPEN_ONLY_METHODDEF
+ _IO_FILEIO__DEALLOC_WARN_METHODDEF
{"__getstate__", _PyIOBase_cannot_pickle, METH_NOARGS},
{NULL, NULL} /* sentinel */
};
/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
-static PyObject *
-fileio_get_closed(PyObject *op, void *closure)
+/*[clinic input]
+@getter
+_io.FileIO.closed -> bool
+
+True if the file is closed.
+[clinic start generated code]*/
+
+static int
+_io_FileIO_closed_get_impl(fileio *self)
+/*[clinic end generated code: output=5052fd0688b475f2 input=6024cca6d484d9a2]*/
{
- fileio *self = PyFileIO_CAST(op);
- return PyBool_FromLong((long)(self->fd < 0));
+ return self->fd < 0;
}
-static PyObject *
-fileio_get_closefd(PyObject *op, void *closure)
+/*[clinic input]
+@getter
+_io.FileIO.closefd -> bool
+
+True if the file descriptor will be closed by close().
+[clinic start generated code]*/
+
+static int
+_io_FileIO_closefd_get_impl(fileio *self)
+/*[clinic end generated code: output=11963fca763399cc input=ed3d108a6f07ad5c]*/
{
- fileio *self = PyFileIO_CAST(op);
- return PyBool_FromLong((long)(self->closefd));
+ return self->closefd;
}
+/*[clinic input]
+@getter
+_io.FileIO.mode
+
+String giving the file mode.
+[clinic start generated code]*/
+
static PyObject *
-fileio_get_mode(PyObject *op, void *closure)
+_io_FileIO_mode_get_impl(fileio *self)
+/*[clinic end generated code: output=d5178215493e2e7e input=300a448fc9b2fea4]*/
{
- fileio *self = PyFileIO_CAST(op);
return PyUnicode_FromString(mode_string(self));
}
-static PyObject *
-fileio_get_blksize(PyObject *op, void *closure)
+/*[clinic input]
+@getter
+_io.FileIO._blksize -> long
+
+Stat st_blksize if available.
+[clinic start generated code]*/
+
+static long
+_io_FileIO__blksize_get_impl(fileio *self)
+/*[clinic end generated code: output=e47eaf8cd6c0079f input=699d87d750798ccb]*/
{
#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
- fileio *self = PyFileIO_CAST(op);
if (self->stat_atopen != NULL && self->stat_atopen->st_blksize > 1) {
- return PyLong_FromLong(self->stat_atopen->st_blksize);
+ return self->stat_atopen->st_blksize;
}
#endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
- return PyLong_FromLong(DEFAULT_BUFFER_SIZE);
+ return DEFAULT_BUFFER_SIZE;
}
static PyGetSetDef fileio_getsetlist[] = {
- {"closed", fileio_get_closed, NULL, "True if the file is closed"},
- {"closefd", fileio_get_closefd, NULL,
- "True if the file descriptor will be closed by close()."},
- {"mode", fileio_get_mode, NULL, "String giving the file mode"},
- {"_blksize", fileio_get_blksize, NULL, "Stat st_blksize if available"},
+ _IO_FILEIO_CLOSED_GETSETDEF
+ _IO_FILEIO_CLOSEFD_GETSETDEF
+ _IO_FILEIO_MODE_GETSETDEF
+ _IO_FILEIO__BLKSIZE_GETSETDEF
{NULL},
};
static PyMemberDef fileio_members[] = {
{"_finalizing", Py_T_BOOL, offsetof(fileio, finalizing), 0},
- {"__weaklistoffset__", Py_T_PYSSIZET, offsetof(fileio, weakreflist), Py_READONLY},
- {"__dictoffset__", Py_T_PYSSIZET, offsetof(fileio, dict), Py_READONLY},
{NULL}
};
diff --git a/Modules/_io/iobase.c b/Modules/_io/iobase.c
index 1253f124108bdbf..13de04d3b9ce772 100644
--- a/Modules/_io/iobase.c
+++ b/Modules/_io/iobase.c
@@ -14,7 +14,6 @@
#include "pycore_long.h" // _PyLong_GetOne()
#include "pycore_object.h" // _PyType_HasFeature()
#include "pycore_pyerrors.h" // _PyErr_ChainExceptions1()
-#include "pycore_weakref.h" // FT_CLEAR_WEAKREFS()
#include // offsetof()
#include "_iomodule.h"
@@ -33,8 +32,6 @@ class _io._RawIOBase "PyObject *" "clinic_state()->PyRawIOBase_Type"
typedef struct {
PyObject_HEAD
- PyObject *dict;
- PyObject *weakreflist;
} iobase;
#define iobase_CAST(op) ((iobase *)(op))
@@ -184,14 +181,18 @@ _io__IOBase_flush_impl(PyObject *self)
return NULL;
}
-static PyObject *
-iobase_closed_get(PyObject *self, void *context)
+/*[clinic input]
+@getter
+_io._IOBase.closed -> bool
+
+True if the file is closed.
+[clinic start generated code]*/
+
+static int
+_io__IOBase_closed_get_impl(PyObject *self)
+/*[clinic end generated code: output=561af4ea236d16d9 input=e730fe4ccc4c096c]*/
{
- int closed = iobase_is_closed(self);
- if (closed < 0) {
- return NULL;
- }
- return PyBool_FromLong(closed);
+ return iobase_is_closed(self);
}
static int
@@ -225,25 +226,51 @@ _PyIOBase_check_closed(PyObject *self, PyObject *args)
Py_RETURN_NONE;
}
+/*[clinic input]
+_io._IOBase._checkClosed
+[clinic start generated code]*/
+
+static PyObject *
+_io__IOBase__checkClosed_impl(PyObject *self)
+/*[clinic end generated code: output=8fb8412185623f1a input=8d18d2e67b2270bb]*/
+{
+ return _PyIOBase_check_closed(self, NULL);
+}
+
+/*[clinic input]
+_io._IOBase._checkSeekable
+[clinic start generated code]*/
+
static PyObject *
-iobase_check_seekable(PyObject *self, PyObject *args)
+_io__IOBase__checkSeekable_impl(PyObject *self)
+/*[clinic end generated code: output=10f09b515a9f4c4f input=479853eded776b0e]*/
{
_PyIO_State *state = find_io_state_by_def(Py_TYPE(self));
- return _PyIOBase_check_seekable(state, self, args);
+ return _PyIOBase_check_seekable(state, self, NULL);
}
+/*[clinic input]
+_io._IOBase._checkReadable
+[clinic start generated code]*/
+
static PyObject *
-iobase_check_readable(PyObject *self, PyObject *args)
+_io__IOBase__checkReadable_impl(PyObject *self)
+/*[clinic end generated code: output=33ccab8a7c4550fb input=63fbf50b36772323]*/
{
_PyIO_State *state = find_io_state_by_def(Py_TYPE(self));
- return _PyIOBase_check_readable(state, self, args);
+ return _PyIOBase_check_readable(state, self, NULL);
}
+/*[clinic input]
+_io._IOBase._checkWritable
+[clinic start generated code]*/
+
static PyObject *
-iobase_check_writable(PyObject *self, PyObject *args)
+_io__IOBase__checkWritable_impl(PyObject *self)
+/*[clinic end generated code: output=8cfc6b4b2469d2a3 input=2758c7291cf5911e]*/
{
_PyIO_State *state = find_io_state_by_def(Py_TYPE(self));
- return _PyIOBase_check_writable(state, self, args);
+ return _PyIOBase_check_writable(state, self, NULL);
}
PyObject *
@@ -353,15 +380,13 @@ iobase_traverse(PyObject *op, visitproc visit, void *arg)
{
iobase *self = iobase_CAST(op);
Py_VISIT(Py_TYPE(self));
- Py_VISIT(self->dict);
- return 0;
+ return PyObject_VisitManagedDict(op, visit, arg);
}
static int
iobase_clear(PyObject *op)
{
- iobase *self = iobase_CAST(op);
- Py_CLEAR(self->dict);
+ PyObject_ClearManagedDict(op);
return 0;
}
@@ -370,8 +395,8 @@ iobase_clear(PyObject *op)
static void
iobase_dealloc(PyObject *op)
{
- /* NOTE: since IOBaseObject has its own dict, Python-defined attributes
- are still available here for close() to use.
+ /* NOTE: since the managed dict is only cleared below, Python-defined
+ attributes are still available here for close() to use.
However, if the derived class declares a __slots__, those slots are
already gone.
*/
@@ -386,8 +411,8 @@ iobase_dealloc(PyObject *op)
}
PyTypeObject *tp = Py_TYPE(self);
_PyObject_GC_UNTRACK(self);
- FT_CLEAR_WEAKREFS(op, self->weakreflist);
- Py_CLEAR(self->dict);
+ PyObject_ClearWeakRefs(op);
+ PyObject_ClearManagedDict(op);
tp->tp_free(self);
Py_DECREF(tp);
}
@@ -495,8 +520,15 @@ _PyIOBase_check_writable(_PyIO_State *state, PyObject *self, PyObject *args)
/* Context manager */
+/*[clinic input]
+_io._IOBase.__enter__
+
+Context management protocol. Returns the stream itself.
+[clinic start generated code]*/
+
static PyObject *
-iobase_enter(PyObject *self, PyObject *args)
+_io__IOBase___enter___impl(PyObject *self)
+/*[clinic end generated code: output=d1e8e5b58bde3680 input=92e2d5e34ee714e5]*/
{
if (iobase_check_closed(self))
return NULL;
@@ -504,8 +536,16 @@ iobase_enter(PyObject *self, PyObject *args)
return Py_NewRef(self);
}
+/*[clinic input]
+_io._IOBase.__exit__
+ *args: tuple
+
+Context management protocol. Calls close().
+[clinic start generated code]*/
+
static PyObject *
-iobase_exit(PyObject *self, PyObject *args)
+_io__IOBase___exit___impl(PyObject *self, PyObject *args)
+/*[clinic end generated code: output=452f3e33a34e2c5c input=fd3f46a32773a170]*/
{
return PyObject_CallMethodNoArgs(self, &_Py_ID(close));
}
@@ -571,20 +611,19 @@ _io__IOBase_readline_impl(PyObject *self, Py_ssize_t limit)
{
/* For backwards compatibility, a (slowish) readline(). */
- PyObject *peek, *buffer, *result;
- Py_ssize_t old_size = -1;
+ PyObject *peek;
if (PyObject_GetOptionalAttr(self, &_Py_ID(peek), &peek) < 0) {
return NULL;
}
- buffer = PyByteArray_FromStringAndSize(NULL, 0);
- if (buffer == NULL) {
+ PyBytesWriter *writer = PyBytesWriter_Create(0);
+ if (writer == NULL) {
Py_XDECREF(peek);
return NULL;
}
- while (limit < 0 || PyByteArray_GET_SIZE(buffer) < limit) {
+ while (limit < 0 || PyBytesWriter_GetSize(writer) < limit) {
Py_ssize_t nreadahead = 1;
PyObject *b;
@@ -609,8 +648,9 @@ _io__IOBase_readline_impl(PyObject *self, Py_ssize_t limit)
Py_ssize_t n = 0;
const char *buf = PyBytes_AS_STRING(readahead);
if (limit >= 0) {
+ Py_ssize_t remaining = limit - PyBytesWriter_GetSize(writer);
do {
- if (n >= PyBytes_GET_SIZE(readahead) || n >= limit)
+ if (n >= PyBytes_GET_SIZE(readahead) || n >= remaining)
break;
if (buf[n++] == '\n')
break;
@@ -650,28 +690,25 @@ _io__IOBase_readline_impl(PyObject *self, Py_ssize_t limit)
break;
}
- old_size = PyByteArray_GET_SIZE(buffer);
- if (PyByteArray_Resize(buffer, old_size + PyBytes_GET_SIZE(b)) < 0) {
+ if (PyBytesWriter_WriteBytes(writer,
+ PyBytes_AS_STRING(b),
+ PyBytes_GET_SIZE(b)) < 0) {
Py_DECREF(b);
goto fail;
}
- memcpy(PyByteArray_AS_STRING(buffer) + old_size,
- PyBytes_AS_STRING(b), PyBytes_GET_SIZE(b));
Py_DECREF(b);
- if (PyByteArray_AS_STRING(buffer)[PyByteArray_GET_SIZE(buffer) - 1] == '\n')
+ char *data = PyBytesWriter_GetData(writer);
+ if (data[PyBytesWriter_GetSize(writer) - 1] == '\n')
break;
}
- result = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(buffer),
- PyByteArray_GET_SIZE(buffer));
Py_XDECREF(peek);
- Py_DECREF(buffer);
- return result;
+ return PyBytesWriter_Finish(writer);
fail:
Py_XDECREF(peek);
- Py_DECREF(buffer);
+ PyBytesWriter_Discard(writer);
return NULL;
}
@@ -841,16 +878,16 @@ static PyMethodDef iobase_methods[] = {
_IO__IOBASE_READABLE_METHODDEF
_IO__IOBASE_WRITABLE_METHODDEF
- {"_checkClosed", _PyIOBase_check_closed, METH_NOARGS},
- {"_checkSeekable", iobase_check_seekable, METH_NOARGS},
- {"_checkReadable", iobase_check_readable, METH_NOARGS},
- {"_checkWritable", iobase_check_writable, METH_NOARGS},
+ _IO__IOBASE__CHECKCLOSED_METHODDEF
+ _IO__IOBASE__CHECKSEEKABLE_METHODDEF
+ _IO__IOBASE__CHECKREADABLE_METHODDEF
+ _IO__IOBASE__CHECKWRITABLE_METHODDEF
_IO__IOBASE_FILENO_METHODDEF
_IO__IOBASE_ISATTY_METHODDEF
- {"__enter__", iobase_enter, METH_NOARGS},
- {"__exit__", iobase_exit, METH_VARARGS},
+ _IO__IOBASE___ENTER___METHODDEF
+ _IO__IOBASE___EXIT___METHODDEF
_IO__IOBASE_READLINE_METHODDEF
_IO__IOBASE_READLINES_METHODDEF
@@ -861,16 +898,10 @@ static PyMethodDef iobase_methods[] = {
static PyGetSetDef iobase_getset[] = {
{"__dict__", PyObject_GenericGetDict, NULL, NULL},
- {"closed", iobase_closed_get, NULL, NULL},
+ _IO__IOBASE_CLOSED_GETSETDEF
{NULL}
};
-static struct PyMemberDef iobase_members[] = {
- {"__weaklistoffset__", Py_T_PYSSIZET, offsetof(iobase, weakreflist), Py_READONLY},
- {"__dictoffset__", Py_T_PYSSIZET, offsetof(iobase, dict), Py_READONLY},
- {NULL},
-};
-
static PyType_Slot iobase_slots[] = {
{Py_tp_dealloc, iobase_dealloc},
@@ -880,7 +911,6 @@ static PyType_Slot iobase_slots[] = {
{Py_tp_iter, iobase_iter},
{Py_tp_iternext, iobase_iternext},
{Py_tp_methods, iobase_methods},
- {Py_tp_members, iobase_members},
{Py_tp_getset, iobase_getset},
{Py_tp_finalize, iobase_finalize},
{0, NULL},
@@ -890,7 +920,8 @@ PyType_Spec _Py_iobase_spec = {
.name = "_io._IOBase",
.basicsize = sizeof(iobase),
.flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_IMMUTABLETYPE),
+ Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_MANAGED_DICT |
+ Py_TPFLAGS_MANAGED_WEAKREF),
.slots = iobase_slots,
};
@@ -1018,15 +1049,29 @@ _io__RawIOBase_readall_impl(PyObject *self)
return PyBytesWriter_Finish(writer);
}
+/*[clinic input]
+_io._RawIOBase.readinto
+ buffer: object
+ /
+[clinic start generated code]*/
+
static PyObject *
-rawiobase_readinto(PyObject *self, PyObject *args)
+_io__RawIOBase_readinto(PyObject *self, PyObject *buffer)
+/*[clinic end generated code: output=081b8cdfaf3a40ff input=99d4bea2acd659c8]*/
{
PyErr_SetNone(PyExc_NotImplementedError);
return NULL;
}
+/*[clinic input]
+_io._RawIOBase.write
+ buffer: object
+ /
+[clinic start generated code]*/
+
static PyObject *
-rawiobase_write(PyObject *self, PyObject *args)
+_io__RawIOBase_write(PyObject *self, PyObject *buffer)
+/*[clinic end generated code: output=7add3f2c8715c3a8 input=e6a1534adb876fe2]*/
{
PyErr_SetNone(PyExc_NotImplementedError);
return NULL;
@@ -1035,8 +1080,8 @@ rawiobase_write(PyObject *self, PyObject *args)
static PyMethodDef rawiobase_methods[] = {
_IO__RAWIOBASE_READ_METHODDEF
_IO__RAWIOBASE_READALL_METHODDEF
- {"readinto", rawiobase_readinto, METH_VARARGS},
- {"write", rawiobase_write, METH_VARARGS},
+ _IO__RAWIOBASE_READINTO_METHODDEF
+ _IO__RAWIOBASE_WRITE_METHODDEF
{NULL, NULL}
};
diff --git a/Modules/_io/stringio.c b/Modules/_io/stringio.c
index b8601383ad0a26f..a5687207d65e089 100644
--- a/Modules/_io/stringio.c
+++ b/Modules/_io/stringio.c
@@ -1,7 +1,8 @@
#include "Python.h"
#include // offsetof()
+#include "pycore_critical_section.h" // _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED()
#include "pycore_object.h"
-#include "pycore_weakref.h" // FT_CLEAR_WEAKREFS()
+#include "pycore_unicodeobject.h" // _PyUnicode_ResizeCompact()
#include "_iomodule.h"
/* Implementation note: the buffer is always at least one character longer
@@ -41,8 +42,6 @@ typedef struct {
PyObject *readnl;
PyObject *writenl;
- PyObject *dict;
- PyObject *weakreflist;
_PyIO_State *module_state;
} stringio;
@@ -68,6 +67,20 @@ static int _io_StringIO___init__(PyObject *self, PyObject *args, PyObject *kwarg
return NULL; \
}
+#define CHECK_INITIALIZED_INT(self) \
+ if (self->ok <= 0) { \
+ PyErr_SetString(PyExc_ValueError, \
+ "I/O operation on uninitialized object"); \
+ return -1; \
+ }
+
+#define CHECK_CLOSED_INT(self) \
+ if (self->closed) { \
+ PyErr_SetString(PyExc_ValueError, \
+ "I/O operation on closed file"); \
+ return -1; \
+ }
+
#define ENSURE_REALIZED(self) \
if (realize(self) < 0) { \
return NULL; \
@@ -129,25 +142,52 @@ resize_buffer(stringio *self, size_t size)
return -1;
}
+/* Shrink the buffer of the writer to its contents, so that the following
+ PyUnicodeWriter_Finish() has nothing to allocate and cannot fail.
+ If this fails, the writer is unchanged. */
+static int
+shrink_writer(stringio *self)
+{
+ _PyUnicodeWriter *writer = (_PyUnicodeWriter *)self->writer;
+ if (writer->readonly || writer->buffer == NULL
+ || writer->pos == 0 || writer->pos == writer->size)
+ {
+ return 0;
+ }
+ PyObject *buffer = _PyUnicode_ResizeCompact(writer->buffer, writer->pos);
+ if (buffer == NULL) {
+ return -1;
+ }
+ writer->buffer = NULL;
+ _PyUnicodeWriter_SetBuffer(writer, buffer);
+ return 0;
+}
+
static PyObject *
make_intermediate(stringio *self)
{
- PyObject *intermediate = PyUnicodeWriter_Finish(self->writer);
- self->writer = NULL;
- self->state = STATE_REALIZED;
- if (intermediate == NULL)
+ /* Create the new writer and shrink the old one first: if this fails,
+ the object keeps its contents. */
+ PyUnicodeWriter *writer = PyUnicodeWriter_Create(0);
+ if (writer == NULL)
return NULL;
+ if (shrink_writer(self) < 0) {
+ PyUnicodeWriter_Discard(writer);
+ return NULL;
+ }
- self->writer = PyUnicodeWriter_Create(0);
- if (self->writer == NULL) {
- Py_DECREF(intermediate);
+ PyObject *intermediate = PyUnicodeWriter_Finish(self->writer);
+ self->writer = writer;
+ if (intermediate == NULL) {
+ /* The contents are lost, the new writer is empty. */
+ self->string_size = 0;
return NULL;
}
if (PyUnicodeWriter_WriteStr(self->writer, intermediate)) {
Py_DECREF(intermediate);
+ self->string_size = 0;
return NULL;
}
- self->state = STATE_ACCUMULATING;
return intermediate;
}
@@ -160,23 +200,30 @@ realize(stringio *self)
if (self->state == STATE_REALIZED)
return 0;
assert(self->state == STATE_ACCUMULATING);
+
+ /* Allocate the internal buffer and shrink the writer first: if this
+ fails, the object stays in the accumulating state and keeps its
+ contents. */
+ if (resize_buffer(self, self->string_size) < 0)
+ return -1;
+ if (shrink_writer(self) < 0)
+ return -1;
self->state = STATE_REALIZED;
intermediate = PyUnicodeWriter_Finish(self->writer);
self->writer = NULL;
- if (intermediate == NULL)
+ if (intermediate == NULL) {
+ /* The contents are lost, the internal buffer contains nothing. */
+ self->string_size = 0;
return -1;
+ }
- /* Append the intermediate string to the internal buffer.
- The length should be equal to the current cursor position.
- */
+ /* Copy the intermediate string to the internal buffer. */
len = PyUnicode_GET_LENGTH(intermediate);
- if (resize_buffer(self, len) < 0) {
- Py_DECREF(intermediate);
- return -1;
- }
+ assert(len == self->string_size);
if (!PyUnicode_AsUCS4(intermediate, self->buf, len, 0)) {
Py_DECREF(intermediate);
+ self->string_size = 0;
return -1;
}
@@ -344,7 +391,9 @@ _io_StringIO_read_impl(stringio *self, Py_ssize_t size)
/* Optimization for seek(0); read() */
if (self->state == STATE_ACCUMULATING && self->pos == 0 && size == n) {
PyObject *result = make_intermediate(self);
- self->pos = self->string_size;
+ if (result != NULL) {
+ self->pos = self->string_size;
+ }
return result;
}
@@ -406,11 +455,18 @@ _io_StringIO_readline_impl(stringio *self, Py_ssize_t size)
return _stringio_readline(self, size);
}
+/*[clinic input]
+@critical_section
+_io.StringIO.__next__ as stringio_iternext
+[clinic start generated code]*/
+
static PyObject *
-stringio_iternext(PyObject *op)
+stringio_iternext_impl(stringio *self)
+/*[clinic end generated code: output=51eb3991b1c79c41 input=b6cf3e73fab6b42e]*/
{
+ _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
+
PyObject *line;
- stringio *self = stringio_CAST(op);
CHECK_INITIALIZED(self);
CHECK_CLOSED(self);
@@ -422,7 +478,7 @@ stringio_iternext(PyObject *op)
}
else {
/* XXX is subclassing StringIO really supported? */
- line = PyObject_CallMethodNoArgs(op, &_Py_ID(readline));
+ line = PyObject_CallMethodNoArgs((PyObject *)self, &_Py_ID(readline));
if (line && !PyUnicode_Check(line)) {
PyErr_Format(PyExc_OSError,
"readline() should have returned a str object, "
@@ -469,7 +525,7 @@ _io_StringIO_truncate_impl(stringio *self, PyObject *pos)
size = self->pos;
}
else {
- size = PyLong_AsLong(pos);
+ size = PyNumber_AsSsize_t(pos, PyExc_OverflowError);
if (size == -1 && PyErr_Occurred()) {
return NULL;
}
@@ -478,6 +534,9 @@ _io_StringIO_truncate_impl(stringio *self, PyObject *pos)
"negative pos value %zd", size);
return NULL;
}
+ /* __index__ may have closed or reinitialized the stream. */
+ CHECK_INITIALIZED(self);
+ CHECK_CLOSED(self);
}
if (size < self->string_size) {
@@ -614,8 +673,7 @@ stringio_traverse(PyObject *op, visitproc visit, void *arg)
Py_VISIT(self->readnl);
Py_VISIT(self->writenl);
Py_VISIT(self->decoder);
- Py_VISIT(self->dict);
- return 0;
+ return PyObject_VisitManagedDict(op, visit, arg);
}
static int
@@ -625,7 +683,7 @@ stringio_clear(PyObject *op)
Py_CLEAR(self->readnl);
Py_CLEAR(self->writenl);
Py_CLEAR(self->decoder);
- Py_CLEAR(self->dict);
+ PyObject_ClearManagedDict(op);
return 0;
}
@@ -642,7 +700,7 @@ stringio_dealloc(PyObject *op)
}
PyUnicodeWriter_Discard(self->writer);
(void)stringio_clear(op);
- FT_CLEAR_WEAKREFS(op, self->weakreflist);
+ PyObject_ClearWeakRefs(op);
tp->tp_free(self);
Py_DECREF(tp);
}
@@ -869,11 +927,16 @@ _io_StringIO___getstate___impl(stringio *self)
if (initvalue == NULL)
return NULL;
- if (self->dict == NULL) {
+ if (_PyObject_IsInstanceDictEmpty((PyObject *)self)) {
dict = Py_NewRef(Py_None);
}
else {
- dict = PyDict_Copy(self->dict);
+ dict = PyObject_GenericGetDict((PyObject *)self, NULL);
+ if (dict == NULL) {
+ Py_DECREF(initvalue);
+ return NULL;
+ }
+ Py_SETREF(dict, PyDict_Copy(dict));
if (dict == NULL) {
Py_DECREF(initvalue);
return NULL;
@@ -984,14 +1047,16 @@ _io_StringIO___setstate___impl(stringio *self, PyObject *state)
Py_TYPE(dict)->tp_name);
return NULL;
}
- if (self->dict) {
- /* Alternatively, we could replace the internal dictionary
- completely. However, it seems more practical to just update it. */
- if (PyDict_Update(self->dict, dict) < 0)
- return NULL;
+ /* Alternatively, we could replace the internal dictionary
+ completely. However, it seems more practical to just update it. */
+ PyObject *self_dict = PyObject_GenericGetDict((PyObject *)self, NULL);
+ if (self_dict == NULL) {
+ return NULL;
}
- else {
- self->dict = Py_NewRef(dict);
+ int rc = PyDict_Update(self_dict, dict);
+ Py_DECREF(self_dict);
+ if (rc < 0) {
+ return NULL;
}
}
@@ -1001,30 +1066,30 @@ _io_StringIO___setstate___impl(stringio *self, PyObject *state)
/*[clinic input]
@critical_section
@getter
-_io.StringIO.closed
+_io.StringIO.closed -> bool
[clinic start generated code]*/
-static PyObject *
+static int
_io_StringIO_closed_get_impl(stringio *self)
-/*[clinic end generated code: output=531ddca7954331d6 input=178d2ef24395fd49]*/
+/*[clinic end generated code: output=754068c44422cafa input=ea05e89b945e721c]*/
{
- CHECK_INITIALIZED(self);
- return PyBool_FromLong(self->closed);
+ CHECK_INITIALIZED_INT(self);
+ return self->closed;
}
/*[clinic input]
@critical_section
@getter
-_io.StringIO.line_buffering
+_io.StringIO.line_buffering -> bool
[clinic start generated code]*/
-static PyObject *
+static int
_io_StringIO_line_buffering_get_impl(stringio *self)
-/*[clinic end generated code: output=360710e0112966ae input=6a7634e7f890745e]*/
+/*[clinic end generated code: output=56c0edde9001fb37 input=326f8b3bd1feb699]*/
{
- CHECK_INITIALIZED(self);
- CHECK_CLOSED(self);
- Py_RETURN_FALSE;
+ CHECK_INITIALIZED_INT(self);
+ CHECK_CLOSED_INT(self);
+ return 0;
}
/*[clinic input]
@@ -1077,12 +1142,6 @@ static PyGetSetDef stringio_getset[] = {
{NULL}
};
-static struct PyMemberDef stringio_members[] = {
- {"__weaklistoffset__", Py_T_PYSSIZET, offsetof(stringio, weakreflist), Py_READONLY},
- {"__dictoffset__", Py_T_PYSSIZET, offsetof(stringio, dict), Py_READONLY},
- {NULL},
-};
-
static PyType_Slot stringio_slots[] = {
{Py_tp_dealloc, stringio_dealloc},
{Py_tp_doc, (void *)_io_StringIO___init____doc__},
@@ -1090,7 +1149,6 @@ static PyType_Slot stringio_slots[] = {
{Py_tp_clear, stringio_clear},
{Py_tp_iternext, stringio_iternext},
{Py_tp_methods, stringio_methods},
- {Py_tp_members, stringio_members},
{Py_tp_getset, stringio_getset},
{Py_tp_init, _io_StringIO___init__},
{Py_tp_new, stringio_new},
diff --git a/Modules/_io/textio.c b/Modules/_io/textio.c
index 5b2a20a30c28cb2..049f999349f0d58 100644
--- a/Modules/_io/textio.c
+++ b/Modules/_io/textio.c
@@ -16,7 +16,6 @@
#include "pycore_pyerrors.h" // _PyErr_ChainExceptions1()
#include "pycore_pystate.h" // _PyInterpreterState_GET()
#include "pycore_unicodeobject.h" // _PyUnicode_AsASCIIString()
-#include "pycore_weakref.h" // FT_CLEAR_WEAKREFS()
#include "_iomodule.h"
@@ -229,6 +228,7 @@ struct nldecoder_object {
#define nldecoder_object_CAST(op) ((nldecoder_object *)(op))
/*[clinic input]
+@vectorcall
_io.IncrementalNewlineDecoder.__init__
decoder: object
translate: bool
@@ -248,7 +248,7 @@ static int
_io_IncrementalNewlineDecoder___init___impl(nldecoder_object *self,
PyObject *decoder, int translate,
PyObject *errors)
-/*[clinic end generated code: output=fbd04d443e764ec2 input=ed547aa257616b0e]*/
+/*[clinic end generated code: output=fbd04d443e764ec2 input=7fd0efad15bc0b69]*/
{
if (errors == NULL) {
@@ -336,8 +336,11 @@ _PyIncrementalNewlineDecoder_decode(PyObject *myself,
/* decode input (with the eventual \r from a previous pass) */
if (self->decoder != Py_None) {
- output = PyObject_CallMethodObjArgs(self->decoder,
+ /* The wrapper can be reinitialized by a decoding callback. */
+ PyObject *decoder = Py_NewRef(self->decoder);
+ output = PyObject_CallMethodObjArgs(decoder,
&_Py_ID(decode), input, final ? Py_True : Py_False, NULL);
+ Py_DECREF(decoder);
}
else {
output = Py_NewRef(input);
@@ -635,10 +638,15 @@ _io_IncrementalNewlineDecoder_reset_impl(nldecoder_object *self)
Py_RETURN_NONE;
}
+/*[clinic input]
+@getter
+_io.IncrementalNewlineDecoder.newlines
+[clinic start generated code]*/
+
static PyObject *
-incrementalnewlinedecoder_newlines_get(PyObject *op, void *Py_UNUSED(context))
+_io_IncrementalNewlineDecoder_newlines_get_impl(nldecoder_object *self)
+/*[clinic end generated code: output=4370cf5202a83d08 input=040f9a26aef317a8]*/
{
- nldecoder_object *self = nldecoder_object_CAST(op);
CHECK_INITIALIZED_DECODER(self);
switch (self->seennl) {
@@ -723,8 +731,6 @@ struct textio
/* Cache raw object if it's a FileIO object */
PyObject *raw;
- PyObject *weakreflist;
- PyObject *dict;
_PyIO_State *state;
};
@@ -753,10 +759,8 @@ buffer_access_safe(textio *self)
return NULL;
}
- /* Returning a borrowed reference is safe since TextIOWrapper methods are
- protected by critical sections. */
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
- return self->buffer;
+ return Py_NewRef(self->buffer);
}
static PyObject *
@@ -767,7 +771,9 @@ buffer_getattr(textio *self, PyObject *attr_name)
return NULL;
}
- return PyObject_GetAttr(buffer, attr_name);
+ PyObject *res = PyObject_GetAttr(buffer, attr_name);
+ Py_DECREF(buffer);
+ return res;
}
static PyObject *
@@ -778,7 +784,9 @@ buffer_callmethod_noargs(textio *self, PyObject *name)
return NULL;
}
- return PyObject_CallMethodNoArgs(buffer, name);
+ PyObject *res = PyObject_CallMethodNoArgs(buffer, name);
+ Py_DECREF(buffer);
+ return res;
}
static PyObject *
@@ -789,7 +797,9 @@ buffer_callmethod_onearg(textio *self, PyObject *name, PyObject *arg)
return NULL;
}
- return PyObject_CallMethodOneArg(buffer, name, arg);
+ PyObject *res = PyObject_CallMethodOneArg(buffer, name, arg);
+ Py_DECREF(buffer);
+ return res;
}
static void
@@ -997,11 +1007,17 @@ _textiowrapper_decode(_PyIO_State *state, PyObject *decoder, PyObject *bytes,
{
PyObject *chars;
+ if (decoder == NULL) {
+ return _unsupported(state, "not readable");
+ }
+ /* A codec callback may replace the wrapper's decoder. */
+ Py_INCREF(decoder);
if (Py_IS_TYPE(decoder, state->PyIncrementalNewlineDecoder_Type))
chars = _PyIncrementalNewlineDecoder_decode(decoder, bytes, eof);
else
chars = PyObject_CallMethodObjArgs(decoder, &_Py_ID(decode), bytes,
eof ? Py_True : Py_False, NULL);
+ Py_DECREF(decoder);
if (check_decoded(chars) < 0)
// check_decoded already decreases refcount
@@ -1135,7 +1151,10 @@ _io.TextIOWrapper.__init__
Character and line based layer over a BufferedIOBase object, buffer.
encoding gives the name of the encoding that the stream will be
-decoded or encoded with. It defaults to locale.getencoding().
+decoded or encoded with. It defaults to UTF-8; if UTF-8 Mode is
+disabled, the encoding returned by locale.getencoding() is used
+instead. See the codecs module for the list of supported
+encodings.
errors determines the strictness of encoding and decoding (see
help(codecs.Codec) or the documentation for codecs.register) and
@@ -1167,7 +1186,7 @@ _io_TextIOWrapper___init___impl(textio *self, PyObject *buffer,
const char *encoding, PyObject *errors,
const char *newline, int line_buffering,
int write_through)
-/*[clinic end generated code: output=72267c0c01032ed2 input=0f077220214c40a4]*/
+/*[clinic end generated code: output=72267c0c01032ed2 input=4f0bee5a0b2302fd]*/
{
PyObject *raw, *codec_info = NULL;
PyObject *res;
@@ -1524,7 +1543,7 @@ textiowrapper_clear(PyObject *op)
Py_CLEAR(self->errors);
Py_CLEAR(self->raw);
- Py_CLEAR(self->dict);
+ PyObject_ClearManagedDict(op);
return 0;
}
@@ -1538,7 +1557,7 @@ textiowrapper_dealloc(PyObject *op)
return;
self->ok = 0;
_PyObject_GC_UNTRACK(self);
- FT_CLEAR_WEAKREFS(op, self->weakreflist);
+ PyObject_ClearWeakRefs(op);
(void)textiowrapper_clear(op);
tp->tp_free(self);
Py_DECREF(tp);
@@ -1560,8 +1579,7 @@ textiowrapper_traverse(PyObject *op, visitproc visit, void *arg)
Py_VISIT(self->errors);
Py_VISIT(self->raw);
- Py_VISIT(self->dict);
- return 0;
+ return PyObject_VisitManagedDict(op, visit, arg);
}
static PyObject *
@@ -1639,7 +1657,7 @@ _io_TextIOWrapper_detach_impl(textio *self)
if (buffer == NULL) {
return NULL;
}
- self->buffer = NULL;
+ Py_CLEAR(self->buffer);
self->detached = 1;
return buffer;
}
@@ -1671,17 +1689,17 @@ _textiowrapper_writeflush(textio *self)
}
else {
assert(PyList_Check(pending));
- b = PyBytes_FromStringAndSize(NULL, self->pending_bytes_count);
- if (b == NULL) {
+ PyBytesWriter *writer = PyBytesWriter_Create(self->pending_bytes_count);
+ if (writer == NULL) {
return -1;
}
- char *buf = PyBytes_AsString(b);
+ char *buf = PyBytesWriter_GetData(writer);
Py_ssize_t pos = 0;
for (Py_ssize_t i = 0; i < PyList_GET_SIZE(pending); i++) {
PyObject *obj = PyList_GET_ITEM(pending, i);
- char *src;
+ const char *src;
Py_ssize_t len;
if (PyUnicode_Check(obj)) {
assert(PyUnicode_IS_ASCII(obj));
@@ -1690,15 +1708,18 @@ _textiowrapper_writeflush(textio *self)
}
else {
assert(PyBytes_Check(obj));
- if (PyBytes_AsStringAndSize(obj, &src, &len) < 0) {
- Py_DECREF(b);
- return -1;
- }
+ src = PyBytes_AS_STRING(obj);
+ len = PyBytes_GET_SIZE(obj);
}
memcpy(buf + pos, src, len);
pos += len;
}
assert(pos == self->pending_bytes_count);
+
+ b = PyBytesWriter_Finish(writer);
+ if (b == NULL) {
+ return -1;
+ }
}
self->pending_bytes_count = 0;
@@ -1718,84 +1739,27 @@ _textiowrapper_writeflush(textio *self)
return 0;
}
-/*[clinic input]
-@critical_section
-_io.TextIOWrapper.write
- text: unicode
- /
-[clinic start generated code]*/
-
+/* Return borrowed Py_None on success, or NULL on error. */
static PyObject *
-_io_TextIOWrapper_write_impl(textio *self, PyObject *text)
-/*[clinic end generated code: output=d2deb0d50771fcec input=73ec95c5c4a3489c]*/
+textiowrapper_check_write(textio *self)
{
- PyObject *ret;
- PyObject *b;
- Py_ssize_t textlen;
- int haslf = 0;
- int needflush = 0, text_needflush = 0;
-
CHECK_ATTACHED(self);
CHECK_CLOSED(self);
if (self->encoder == NULL) {
return _unsupported(self->state, "not writable");
}
+ return Py_None;
+}
- Py_INCREF(text);
-
- textlen = PyUnicode_GET_LENGTH(text);
-
- if ((self->writetranslate && self->writenl != NULL) || self->line_buffering)
- if (PyUnicode_FindChar(text, '\n', 0, PyUnicode_GET_LENGTH(text), 1) != -1)
- haslf = 1;
-
- if (haslf && self->writetranslate && self->writenl != NULL) {
- PyObject *newtext = _PyObject_CallMethod(text, &_Py_ID(replace),
- "ss", "\n", self->writenl);
- Py_DECREF(text);
- if (newtext == NULL)
- return NULL;
- text = newtext;
- }
-
- if (self->write_through)
- text_needflush = 1;
- if (self->line_buffering &&
- (haslf ||
- PyUnicode_FindChar(text, '\r', 0, PyUnicode_GET_LENGTH(text), 1) != -1))
- needflush = 1;
-
- /* XXX What if we were just reading? */
- if (self->encodefunc != NULL) {
- if (PyUnicode_IS_ASCII(text) &&
- // See bpo-43260
- PyUnicode_GET_LENGTH(text) <= self->chunk_size &&
- is_asciicompat_encoding(self->encodefunc)) {
- b = Py_NewRef(text);
- }
- else {
- b = (*self->encodefunc)((PyObject *) self, text);
- }
- self->encoding_start_of_stream = 0;
- }
- else {
- b = PyObject_CallMethodOneArg(self->encoder, &_Py_ID(encode), text);
- }
-
- Py_DECREF(text);
- if (b == NULL)
- return NULL;
- if (b != text && !PyBytes_Check(b)) {
- PyErr_Format(PyExc_TypeError,
- "encoder should return a bytes object, not '%.200s'",
- Py_TYPE(b)->tp_name);
- Py_DECREF(b);
- return NULL;
- }
-
+/* Consume b, which is either bytes or an ASCII string. */
+static int
+textiowrapper_write_bytes(textio *self, PyObject *b,
+ int needflush, int text_needflush)
+{
Py_ssize_t bytes_len;
- if (b == text) {
+ if (PyUnicode_Check(b)) {
+ assert(PyUnicode_IS_ASCII(b));
bytes_len = PyUnicode_GET_LENGTH(b);
}
else {
@@ -1815,7 +1779,7 @@ _io_TextIOWrapper_write_impl(textio *self, PyObject *text)
while (self->pending_bytes != NULL) {
if (_textiowrapper_writeflush(self) < 0) {
Py_DECREF(b);
- return NULL;
+ return -1;
}
}
}
@@ -1829,7 +1793,7 @@ _io_TextIOWrapper_write_impl(textio *self, PyObject *text)
PyObject *list = PyList_New(2);
if (list == NULL) {
Py_DECREF(b);
- return NULL;
+ return -1;
}
// Since Python 3.12, allocating GC object won't trigger GC and release
// GIL. See https://github.com/python/cpython/issues/97922
@@ -1841,7 +1805,7 @@ _io_TextIOWrapper_write_impl(textio *self, PyObject *text)
else {
if (PyList_Append(self->pending_bytes, b) < 0) {
Py_DECREF(b);
- return NULL;
+ return -1;
}
Py_DECREF(b);
}
@@ -1855,13 +1819,18 @@ _io_TextIOWrapper_write_impl(textio *self, PyObject *text)
if (self->pending_bytes_count >= self->chunk_size || needflush ||
text_needflush) {
if (_textiowrapper_writeflush(self) < 0)
- return NULL;
+ return -1;
}
if (needflush) {
PyObject *buffer = buffer_access_safe(self);
- if (buffer == NULL || _PyFile_Flush(buffer) < 0) {
- return NULL;
+ if (buffer == NULL) {
+ return -1;
+ }
+ int res = _PyFile_Flush(buffer);
+ Py_DECREF(buffer);
+ if (res < 0) {
+ return -1;
}
}
@@ -1871,15 +1840,112 @@ _io_TextIOWrapper_write_impl(textio *self, PyObject *text)
}
if (self->decoder) {
- ret = PyObject_CallMethodNoArgs(self->decoder, &_Py_ID(reset));
+ PyObject *ret = PyObject_CallMethodNoArgs(self->decoder, &_Py_ID(reset));
if (ret == NULL)
- return NULL;
+ return -1;
Py_DECREF(ret);
}
+ return 0;
+}
+
+static PyObject *
+textiowrapper_write_text(textio *self, PyObject *text)
+{
+ PyObject *b;
+ Py_ssize_t textlen;
+ int haslf = 0;
+ int needflush = 0, text_needflush = 0;
+
+ Py_INCREF(text);
+
+ textlen = PyUnicode_GET_LENGTH(text);
+
+ if ((self->writetranslate && self->writenl != NULL) || self->line_buffering)
+ if (PyUnicode_FindChar(text, '\n', 0, PyUnicode_GET_LENGTH(text), 1) != -1)
+ haslf = 1;
+
+ if (haslf && self->writetranslate && self->writenl != NULL) {
+ PyObject *newtext = _PyObject_CallMethod(text, &_Py_ID(replace),
+ "ss", "\n", self->writenl);
+ Py_DECREF(text);
+ if (newtext == NULL)
+ return NULL;
+ if (!PyUnicode_Check(newtext)) {
+ PyErr_Format(PyExc_TypeError,
+ "replace() should return a str, not %T", newtext);
+ Py_DECREF(newtext);
+ return NULL;
+ }
+ /* replace() may have closed, detached or reinitialized the stream. */
+ if (textiowrapper_check_write(self) == NULL) {
+ Py_DECREF(newtext);
+ return NULL;
+ }
+ text = newtext;
+ }
+
+ if (self->write_through)
+ text_needflush = 1;
+ if (self->line_buffering &&
+ (haslf ||
+ PyUnicode_FindChar(text, '\r', 0, PyUnicode_GET_LENGTH(text), 1) != -1))
+ needflush = 1;
+
+ /* XXX What if we were just reading? */
+ if (self->encodefunc != NULL) {
+ if (PyUnicode_IS_ASCII(text) &&
+ // See bpo-43260
+ PyUnicode_GET_LENGTH(text) <= self->chunk_size &&
+ is_asciicompat_encoding(self->encodefunc)) {
+ b = Py_NewRef(text);
+ }
+ else {
+ b = (*self->encodefunc)((PyObject *) self, text);
+ }
+ self->encoding_start_of_stream = 0;
+ }
+ else {
+ /* A codec callback may reconfigure the stream. */
+ PyObject *encoder = Py_NewRef(self->encoder);
+ b = PyObject_CallMethodOneArg(encoder, &_Py_ID(encode), text);
+ Py_DECREF(encoder);
+ }
+
+ Py_DECREF(text);
+ if (b == NULL)
+ return NULL;
+ if (b != text && !PyBytes_Check(b)) {
+ PyErr_Format(PyExc_TypeError,
+ "encoder should return a bytes object, not '%.200s'",
+ Py_TYPE(b)->tp_name);
+ Py_DECREF(b);
+ return NULL;
+ }
+
+ if (textiowrapper_write_bytes(self, b, needflush, text_needflush) < 0) {
+ return NULL;
+ }
return PyLong_FromSsize_t(textlen);
}
+/*[clinic input]
+@critical_section
+_io.TextIOWrapper.write
+ text: unicode
+ /
+[clinic start generated code]*/
+
+static PyObject *
+_io_TextIOWrapper_write_impl(textio *self, PyObject *text)
+/*[clinic end generated code: output=d2deb0d50771fcec input=73ec95c5c4a3489c]*/
+{
+ if (textiowrapper_check_write(self) == NULL) {
+ return NULL;
+ }
+ return textiowrapper_write_text(self, text);
+}
+
/* Steal a reference to chars and store it in the decoded_char buffer;
*/
static void
@@ -2015,8 +2081,9 @@ textiowrapper_read_chunk(textio *self, Py_ssize_t size_hint)
if (decoded_chars == NULL)
goto fail;
- textiowrapper_set_decoded_chars(self, decoded_chars);
+ /* The old chunk's finalizer can clear the new chunk. */
nchars = PyUnicode_GET_LENGTH(decoded_chars);
+ textiowrapper_set_decoded_chars(self, decoded_chars);
if (nchars > 0)
self->b2cratio = (double) nbytes / nchars;
else
@@ -2088,15 +2155,9 @@ _io_TextIOWrapper_read_impl(textio *self, Py_ssize_t n)
return NULL;
}
- _PyIO_State *state = self->state;
- if (Py_IS_TYPE(self->decoder, state->PyIncrementalNewlineDecoder_Type))
- decoded = _PyIncrementalNewlineDecoder_decode(self->decoder,
- bytes, 1);
- else
- decoded = PyObject_CallMethodObjArgs(
- self->decoder, &_Py_ID(decode), bytes, Py_True, NULL);
+ decoded = _textiowrapper_decode(self->state, self->decoder, bytes, 1);
Py_DECREF(bytes);
- if (check_decoded(decoded) < 0)
+ if (decoded == NULL)
goto fail;
result = textiowrapper_get_decoded_chars(self, -1);
@@ -2679,6 +2740,7 @@ _io_TextIOWrapper_seek_impl(textio *self, PyObject *cookieObj, int whence)
goto fail;
}
res = _PyObject_CallMethod(buf, &_Py_ID(seek), "ii", 0, 2);
+ Py_DECREF(buf);
Py_CLEAR(cookieObj);
if (res == NULL)
goto fail;
@@ -2823,7 +2885,7 @@ _io_TextIOWrapper_tell_impl(textio *self)
PyObject *res;
PyObject *posobj = NULL;
cookie_type cookie = {0,0,0,0,0};
- PyObject *next_input;
+ PyObject *next_input = NULL;
Py_ssize_t chars_to_skip, chars_decoded;
Py_ssize_t skip_bytes, skip_back;
PyObject *saved_state = NULL;
@@ -2875,11 +2937,15 @@ _io_TextIOWrapper_tell_impl(textio *self)
assert (PyBytes_Check(next_input));
+ /* Own next_input: a reentrant or concurrent seek can drop the snapshot. */
+ Py_INCREF(next_input);
+
cookie.start_pos -= PyBytes_GET_SIZE(next_input);
/* How many decoded characters have been used up since the snapshot? */
if (self->decoded_chars_used == 0) {
/* We haven't moved from the snapshot point. */
+ Py_DECREF(next_input);
return textiowrapper_build_cookie(&cookie);
}
@@ -2932,9 +2998,16 @@ _io_TextIOWrapper_tell_impl(textio *self)
/* Fast search for an acceptable start point, close to our
current pos */
- skip_bytes = (Py_ssize_t) (self->b2cratio * chars_to_skip);
+ double skip_estimate = self->b2cratio * chars_to_skip;
+ if (skip_estimate >= 0 &&
+ skip_estimate <= PyBytes_GET_SIZE(next_input))
+ {
+ skip_bytes = (Py_ssize_t)skip_estimate;
+ }
+ else {
+ skip_bytes = 0;
+ }
skip_back = 1;
- assert(skip_bytes <= PyBytes_GET_SIZE(next_input));
input = PyBytes_AS_STRING(next_input);
while (skip_bytes > 0) {
/* Decode up to temptative start point */
@@ -3020,6 +3093,7 @@ _io_TextIOWrapper_tell_impl(textio *self)
}
finally:
+ Py_XDECREF(next_input);
res = PyObject_CallMethodOneArg(
self->decoder, &_Py_ID(setstate), saved_state);
Py_DECREF(saved_state);
@@ -3032,6 +3106,7 @@ _io_TextIOWrapper_tell_impl(textio *self)
return textiowrapper_build_cookie(&cookie);
fail:
+ Py_XDECREF(next_input);
if (saved_state) {
PyObject *exc = PyErr_GetRaisedException();
res = PyObject_CallMethodOneArg(
@@ -3263,12 +3338,17 @@ _io_TextIOWrapper_close_impl(textio *self)
}
}
+/*[clinic input]
+@critical_section
+_io.TextIOWrapper.__next__ as textiowrapper_iternext
+[clinic start generated code]*/
+
static PyObject *
-textiowrapper_iternext_lock_held(PyObject *op)
+textiowrapper_iternext_impl(textio *self)
+/*[clinic end generated code: output=f365c4287cd43a1f input=c5b4c79faf0c98cb]*/
{
- _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op);
+ _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
PyObject *line;
- textio *self = textio_CAST(op);
CHECK_ATTACHED(self);
@@ -3278,7 +3358,7 @@ textiowrapper_iternext_lock_held(PyObject *op)
line = _textiowrapper_readline(self, -1);
}
else {
- line = PyObject_CallMethodNoArgs(op, &_Py_ID(readline));
+ line = PyObject_CallMethodNoArgs((PyObject *)self, &_Py_ID(readline));
if (line && !PyUnicode_Check(line)) {
PyErr_Format(PyExc_OSError,
"readline() should have returned a str object, "
@@ -3302,16 +3382,6 @@ textiowrapper_iternext_lock_held(PyObject *op)
return line;
}
-static PyObject *
-textiowrapper_iternext(PyObject *op)
-{
- PyObject *result;
- Py_BEGIN_CRITICAL_SECTION(op);
- result = textiowrapper_iternext_lock_held(op);
- Py_END_CRITICAL_SECTION();
- return result;
-}
-
/*[clinic input]
@critical_section
@getter
@@ -3385,45 +3455,55 @@ _io_TextIOWrapper_errors_get_impl(textio *self)
/*[clinic input]
@critical_section
@getter
-_io.TextIOWrapper._CHUNK_SIZE
+_io.TextIOWrapper._CHUNK_SIZE -> Py_ssize_t
[clinic start generated code]*/
-static PyObject *
+static Py_ssize_t
_io_TextIOWrapper__CHUNK_SIZE_get_impl(textio *self)
-/*[clinic end generated code: output=039925cd2df375bc input=e9715b0e06ff0fa6]*/
+/*[clinic end generated code: output=3fe34b873b6b2c8c input=cae767b74b6b46bd]*/
{
- CHECK_ATTACHED(self);
- return PyLong_FromSsize_t(self->chunk_size);
+ CHECK_ATTACHED_INT(self);
+ return self->chunk_size;
}
/*[clinic input]
@critical_section
@setter
_io.TextIOWrapper._CHUNK_SIZE
+ value: Py_ssize_t
[clinic start generated code]*/
static int
-_io_TextIOWrapper__CHUNK_SIZE_set_impl(textio *self, PyObject *value)
-/*[clinic end generated code: output=edb86d2db660a5ab input=32fc99861db02a0a]*/
+_io_TextIOWrapper__CHUNK_SIZE_set_impl(textio *self, Py_ssize_t value)
+/*[clinic end generated code: output=5170a93dd4d74917 input=ede7bae6145f941b]*/
{
- Py_ssize_t n;
CHECK_ATTACHED_INT(self);
- if (value == NULL) {
- PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
- return -1;
- }
- n = PyNumber_AsSsize_t(value, PyExc_ValueError);
- if (n == -1 && PyErr_Occurred())
- return -1;
- if (n <= 0) {
+ if (value <= 0) {
PyErr_SetString(PyExc_ValueError,
"a strictly positive integer is required");
return -1;
}
- self->chunk_size = n;
+ self->chunk_size = value;
return 0;
}
+/*[clinic input]
+@critical_section
+@getter
+_io.TextIOWrapper.buffer
+[clinic start generated code]*/
+
+static PyObject *
+_io_TextIOWrapper_buffer_get_impl(textio *self)
+/*[clinic end generated code: output=d265a34555aa5d4b input=5951cfa148f7350a]*/
+{
+ /* gh-160427: None once detached, matching the former member descriptor. */
+ if (self->buffer == NULL) {
+ Py_RETURN_NONE;
+ }
+ return Py_NewRef(self->buffer);
+}
+
static PyMethodDef incrementalnewlinedecoder_methods[] = {
_IO_INCREMENTALNEWLINEDECODER_DECODE_METHODDEF
_IO_INCREMENTALNEWLINEDECODER_GETSTATE_METHODDEF
@@ -3433,7 +3513,7 @@ static PyMethodDef incrementalnewlinedecoder_methods[] = {
};
static PyGetSetDef incrementalnewlinedecoder_getset[] = {
- {"newlines", incrementalnewlinedecoder_newlines_get, NULL, NULL},
+ _IO_INCREMENTALNEWLINEDECODER_NEWLINES_GETSETDEF
{NULL}
};
@@ -3445,6 +3525,7 @@ static PyType_Slot nldecoder_slots[] = {
{Py_tp_traverse, incrementalnewlinedecoder_traverse},
{Py_tp_clear, incrementalnewlinedecoder_clear},
{Py_tp_init, _io_IncrementalNewlineDecoder___init__},
+ {Py_tp_vectorcall, _io_IncrementalNewlineDecoder_vectorcall},
{0, NULL},
};
@@ -3482,12 +3563,9 @@ static PyMethodDef textiowrapper_methods[] = {
static PyMemberDef textiowrapper_members[] = {
{"encoding", _Py_T_OBJECT, offsetof(textio, encoding), Py_READONLY},
- {"buffer", _Py_T_OBJECT, offsetof(textio, buffer), Py_READONLY},
{"line_buffering", Py_T_BOOL, offsetof(textio, line_buffering), Py_READONLY},
{"write_through", Py_T_BOOL, offsetof(textio, write_through), Py_READONLY},
{"_finalizing", Py_T_BOOL, offsetof(textio, finalizing), 0},
- {"__weaklistoffset__", Py_T_PYSSIZET, offsetof(textio, weakreflist), Py_READONLY},
- {"__dictoffset__", Py_T_PYSSIZET, offsetof(textio, dict), Py_READONLY},
{NULL}
};
@@ -3497,6 +3575,7 @@ static PyGetSetDef textiowrapper_getset[] = {
_IO_TEXTIOWRAPPER_NEWLINES_GETSETDEF
_IO_TEXTIOWRAPPER_ERRORS_GETSETDEF
_IO_TEXTIOWRAPPER__CHUNK_SIZE_GETSETDEF
+ _IO_TEXTIOWRAPPER_BUFFER_GETSETDEF
{NULL}
};
diff --git a/Modules/_io/winconsoleio.c b/Modules/_io/winconsoleio.c
index 4cd71094e8f459e..a6e884fb9c5fc82 100644
--- a/Modules/_io/winconsoleio.c
+++ b/Modules/_io/winconsoleio.c
@@ -10,7 +10,6 @@
#include "pycore_fileutils.h" // _Py_BEGIN_SUPPRESS_IPH
#include "pycore_object.h" // _PyObject_GC_UNTRACK()
#include "pycore_pyerrors.h" // _PyErr_ChainExceptions1()
-#include "pycore_weakref.h" // FT_CLEAR_WEAKREFS()
#ifdef HAVE_WINDOWS_CONSOLE_IO
@@ -216,8 +215,6 @@ typedef struct {
unsigned int closefd : 1;
char finalizing;
unsigned int blksize;
- PyObject *weakreflist;
- PyObject *dict;
char buf[SMALLBUF];
wchar_t wbuf;
} winconsoleio;
@@ -300,7 +297,6 @@ winconsoleio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
self->writable = 0;
self->closefd = 0;
self->blksize = 0;
- self->weakreflist = NULL;
}
return (PyObject *) self;
@@ -498,15 +494,13 @@ winconsoleio_traverse(PyObject *op, visitproc visit, void *arg)
{
winconsoleio *self = winconsoleio_CAST(op);
Py_VISIT(Py_TYPE(self));
- Py_VISIT(self->dict);
- return 0;
+ return PyObject_VisitManagedDict(op, visit, arg);
}
static int
winconsoleio_clear(PyObject *op)
{
- winconsoleio *self = winconsoleio_CAST(op);
- Py_CLEAR(self->dict);
+ PyObject_ClearManagedDict(op);
return 0;
}
@@ -519,8 +513,8 @@ winconsoleio_dealloc(PyObject *op)
if (_PyIOBase_finalize(op) < 0)
return;
_PyObject_GC_UNTRACK(self);
- FT_CLEAR_WEAKREFS(op, self->weakreflist);
- Py_CLEAR(self->dict);
+ PyObject_ClearWeakRefs(op);
+ PyObject_ClearManagedDict(op);
tp->tp_free(self);
Py_DECREF(tp);
}
@@ -644,8 +638,8 @@ read_console_w(HANDLE handle, DWORD maxlen, DWORD *readlen) {
break;
err = 0;
HANDLE hInterruptEvent = _PyOS_SigintEvent();
- if (WaitForSingleObjectEx(hInterruptEvent, 100, FALSE)
- == WAIT_OBJECT_0) {
+ DWORD state = WaitForSingleObjectEx(hInterruptEvent, 100, FALSE);
+ if (state == WAIT_OBJECT_0) {
ResetEvent(hInterruptEvent);
Py_BLOCK_THREADS
sig = PyErr_CheckSignals();
@@ -653,6 +647,13 @@ read_console_w(HANDLE handle, DWORD maxlen, DWORD *readlen) {
if (sig < 0)
break;
}
+ else if (state != WAIT_TIMEOUT) {
+ err = GetLastError();
+ break;
+ }
+ /* The console cancelled the read and flushed its input buffer,
+ but no exception was raised. Start the read over. */
+ continue;
}
*readlen += n;
@@ -935,7 +936,7 @@ _io__WindowsConsoleIO_readall_impl(winconsoleio *self)
if (len == 0 && _buflen(self) == 0) {
/* when the result starts with ^Z we return an empty buffer */
PyMem_Free(buf);
- return PyBytes_FromStringAndSize(NULL, 0);
+ return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
}
if (len) {
@@ -955,6 +956,10 @@ _io__WindowsConsoleIO_readall_impl(winconsoleio *self)
bytes_size += _buflen(self);
bytes = PyBytes_FromStringAndSize(NULL, bytes_size);
+ if (bytes == NULL) {
+ PyMem_Free(buf);
+ return NULL;
+ }
rn = _copyfrombuf(self, PyBytes_AS_STRING(bytes), bytes_size);
if (len) {
@@ -1002,7 +1007,6 @@ _io__WindowsConsoleIO_read_impl(winconsoleio *self, PyTypeObject *cls,
Py_ssize_t size)
/*[clinic end generated code: output=7e569a586537c0ae input=a14570a5da273365]*/
{
- PyObject *bytes;
Py_ssize_t bytes_size;
if (self->fd == -1)
@@ -1019,26 +1023,20 @@ _io__WindowsConsoleIO_read_impl(winconsoleio *self, PyTypeObject *cls,
return NULL;
}
- bytes = PyBytes_FromStringAndSize(NULL, size);
- if (bytes == NULL)
+ PyBytesWriter *writer = PyBytesWriter_Create(size);
+ if (writer == NULL) {
return NULL;
+ }
_PyIO_State *state = get_io_state_by_cls(cls);
- bytes_size = readinto(state, self, PyBytes_AS_STRING(bytes),
- PyBytes_GET_SIZE(bytes));
+ bytes_size = readinto(state, self, PyBytesWriter_GetData(writer),
+ PyBytesWriter_GetSize(writer));
if (bytes_size < 0) {
- Py_CLEAR(bytes);
+ PyBytesWriter_Discard(writer);
return NULL;
}
- if (bytes_size < PyBytes_GET_SIZE(bytes)) {
- if (_PyBytes_Resize(&bytes, bytes_size) < 0) {
- Py_CLEAR(bytes);
- return NULL;
- }
- }
-
- return bytes;
+ return PyBytesWriter_FinishWithSize(writer, bytes_size);
}
/*[clinic input]
@@ -1093,7 +1091,10 @@ _io__WindowsConsoleIO_write_impl(winconsoleio *self, PyTypeObject *cls,
len = Py_MIN(len, max_wlen * 3);
while (1) {
/* Fix for github issues gh-110913 and gh-82052. */
- len = _find_last_utf8_boundary(b->buf, len);
+ DWORD boundary = _find_last_utf8_boundary(b->buf, len);
+ if (boundary != 0) {
+ len = boundary;
+ }
wlen = MultiByteToWideChar(CP_UTF8, 0, b->buf, len, NULL, 0);
if (wlen <= max_wlen) {
break;
@@ -1202,40 +1203,58 @@ static PyMethodDef winconsoleio_methods[] = {
/* 'closed' and 'mode' are attributes for compatibility with FileIO. */
-static PyObject *
-get_closed(PyObject *op, void *Py_UNUSED(closure))
+/*[clinic input]
+@getter
+_io._WindowsConsoleIO.closed -> bool
+
+True if the file is closed.
+[clinic start generated code]*/
+
+static int
+_io__WindowsConsoleIO_closed_get_impl(winconsoleio *self)
+/*[clinic end generated code: output=a3f8b93c6ddcf660 input=65b6d1bed0aadbb8]*/
{
- winconsoleio *self = winconsoleio_CAST(op);
- return PyBool_FromLong((long)(self->fd == -1));
+ return self->fd == -1;
}
-static PyObject *
-get_closefd(PyObject *op, void *Py_UNUSED(closure))
+/*[clinic input]
+@getter
+_io._WindowsConsoleIO.closefd -> bool
+
+True if the file descriptor will be closed by close().
+[clinic start generated code]*/
+
+static int
+_io__WindowsConsoleIO_closefd_get_impl(winconsoleio *self)
+/*[clinic end generated code: output=ec221c2f949530a3 input=5839d3a815edecee]*/
{
- winconsoleio *self = winconsoleio_CAST(op);
- return PyBool_FromLong((long)(self->closefd));
+ return self->closefd;
}
+/*[clinic input]
+@getter
+_io._WindowsConsoleIO.mode
+
+String giving the file mode.
+[clinic start generated code]*/
+
static PyObject *
-get_mode(PyObject *op, void *Py_UNUSED(closure))
+_io__WindowsConsoleIO_mode_get_impl(winconsoleio *self)
+/*[clinic end generated code: output=2d7c4cabf96e5281 input=e1fa9cd881117c0f]*/
{
- winconsoleio *self = winconsoleio_CAST(op);
return PyUnicode_FromString(self->readable ? "rb" : "wb");
}
static PyGetSetDef winconsoleio_getsetlist[] = {
- {"closed", get_closed, NULL, "True if the file is closed"},
- {"closefd", get_closefd, NULL,
- "True if the file descriptor will be closed by close()."},
- {"mode", get_mode, NULL, "String giving the file mode"},
+ _IO__WINDOWSCONSOLEIO_CLOSED_GETSETDEF
+ _IO__WINDOWSCONSOLEIO_CLOSEFD_GETSETDEF
+ _IO__WINDOWSCONSOLEIO_MODE_GETSETDEF
{NULL},
};
static PyMemberDef winconsoleio_members[] = {
{"_blksize", Py_T_UINT, offsetof(winconsoleio, blksize), 0},
{"_finalizing", Py_T_BOOL, offsetof(winconsoleio, finalizing), 0},
- {"__weaklistoffset__", Py_T_PYSSIZET, offsetof(winconsoleio, weakreflist), Py_READONLY},
- {"__dictoffset__", Py_T_PYSSIZET, offsetof(winconsoleio, dict), Py_READONLY},
{NULL}
};
diff --git a/Modules/_json.c b/Modules/_json.c
index 3a724a3e72b185b..e79b697f06c994c 100644
--- a/Modules/_json.c
+++ b/Modules/_json.c
@@ -1802,7 +1802,10 @@ encoder_listencode_dict(PyEncoderObject *s, PyUnicodeWriter *writer,
PyObject *ident = NULL;
bool first = true;
- if (PyDict_GET_SIZE(dct) == 0) {
+ // Only take the fast path for exact dicts: a subclass may keep its
+ // contents outside the dict storage, so PyDict_GET_SIZE could be 0 while
+ // the mapping is non-empty (gh-110941).
+ if (PyAnyDict_CheckExact(dct) && PyDict_GET_SIZE(dct) == 0) {
/* Fast path */
return PyUnicodeWriter_WriteASCII(writer, "{}", 2);
}
diff --git a/Modules/_localemodule.c b/Modules/_localemodule.c
index 0f71358a180dd29..ba8b421c25a47cc 100644
--- a/Modules/_localemodule.c
+++ b/Modules/_localemodule.c
@@ -126,7 +126,7 @@ check_locale_name_all(const char *locale)
_locale.setlocale
category: int
- locale: str(accept={str, NoneType}) = NULL
+ locale: str(accept={str, NoneType}) = None
/
Activates/queries locale processing.
@@ -134,7 +134,7 @@ Activates/queries locale processing.
static PyObject *
_locale_setlocale_impl(PyObject *module, int category, const char *locale)
-/*[clinic end generated code: output=a0e777ae5d2ff117 input=dbe18f1d66c57a6a]*/
+/*[clinic end generated code: output=a0e777ae5d2ff117 input=b53449b63407179b]*/
{
char *result;
PyObject *result_object;
@@ -443,6 +443,7 @@ _locale_strxfrm_impl(PyObject *module, PyObject *str)
{
Py_ssize_t n1;
wchar_t *s = NULL, *buf = NULL;
+ wchar_t dummy[1];
size_t n2;
PyObject *result = NULL;
@@ -456,7 +457,9 @@ _locale_strxfrm_impl(PyObject *module, PyObject *str)
}
errno = 0;
- n2 = wcsxfrm(NULL, s, 0);
+ /* Query the size with a real one-element buffer: DragonFly BSD's
+ wcsxfrm() crashes when the destination is NULL or the size is 0. */
+ n2 = wcsxfrm(dummy, s, 1);
if (errno && errno != ERANGE) {
PyErr_SetFromErrno(PyExc_OSError);
goto exit;
diff --git a/Modules/_lsprof.c b/Modules/_lsprof.c
index 4e50ca64f59af22..c11973d3ed1ff0f 100644
--- a/Modules/_lsprof.c
+++ b/Modules/_lsprof.c
@@ -52,6 +52,7 @@ typedef struct {
ProfilerContext *currentProfilerContext;
ProfilerContext *freelistProfilerContext;
int flags;
+ unsigned int activeTimers; /* may overlap if the profiler lock is released */
PyObject *externalTimer;
double externalTimerUnit;
int tool_id;
@@ -63,7 +64,6 @@ typedef struct {
#define POF_ENABLED 0x001
#define POF_SUBCALLS 0x002
#define POF_BUILTINS 0x004
-#define POF_EXT_TIMER 0x008
#define POF_NOMEMORY 0x100
/*[clinic input]
@@ -92,13 +92,8 @@ _lsprof_get_state(PyObject *module)
static PyTime_t CallExternalTimer(ProfilerObject *pObj)
{
- PyObject *o = NULL;
-
- // External timer can do arbitrary things so we need a flag to prevent
- // horrible things to happen
- pObj->flags |= POF_EXT_TIMER;
- o = _PyObject_CallNoArgs(pObj->externalTimer);
- pObj->flags &= ~POF_EXT_TIMER;
+ assert(pObj->externalTimer != NULL && pObj->externalTimer != Py_None);
+ PyObject *o = _PyObject_CallNoArgs(pObj->externalTimer);
if (o == NULL) {
PyErr_FormatUnraisable("Exception ignored while calling "
@@ -132,7 +127,12 @@ static inline PyTime_t
call_timer(ProfilerObject *pObj)
{
if (pObj->externalTimer != NULL) {
- return CallExternalTimer(pObj);
+ /* Converting or releasing the result and reporting an unraisable
+ exception can all run Python code. */
+ pObj->activeTimers++;
+ PyTime_t result = CallExternalTimer(pObj);
+ pObj->activeTimers--;
+ return result;
}
else {
PyTime_t t;
@@ -363,6 +363,12 @@ ptrace_enter_call(PyObject *self, void *key, PyObject *userObj)
ProfilerEntry *profEntry;
ProfilerContext *pContext;
+ /* Events raised by the external timer must be ignored: it can run
+ arbitrary code while a context is still being unwound. */
+ if (pObj->activeTimers) {
+ return;
+ }
+
/* In the case of entering a generator expression frame via a
* throw (gen_send_ex(.., 1)), we may already have an
* Exception set here. We must not mess around with this
@@ -405,6 +411,10 @@ ptrace_leave_call(PyObject *self, void *key)
ProfilerEntry *profEntry;
ProfilerContext *pContext;
+ if (pObj->activeTimers) {
+ return;
+ }
+
pContext = pObj->currentProfilerContext;
if (pContext == NULL)
return;
@@ -887,7 +897,7 @@ static PyObject *
_lsprof_Profiler_disable_impl(ProfilerObject *self)
/*[clinic end generated code: output=838cffef7f651870 input=f7e4787cae20f7f6]*/
{
- if (self->flags & POF_EXT_TIMER) {
+ if (self->activeTimers) {
PyErr_SetString(PyExc_RuntimeError,
"cannot disable profiler in external timer");
return NULL;
@@ -947,7 +957,7 @@ static PyObject *
_lsprof_Profiler_clear_impl(ProfilerObject *self)
/*[clinic end generated code: output=dd1c668fb84b1335 input=4aab219d5d7a9bec]*/
{
- if (self->flags & POF_EXT_TIMER) {
+ if (self->activeTimers) {
PyErr_SetString(PyExc_RuntimeError,
"cannot clear profiler in external timer");
return NULL;
@@ -980,16 +990,20 @@ profiler_dealloc(PyObject *op)
}
}
+ /* Drop the external timer before flushing: it is Python code, and the
+ profiler can be deallocated by the garbage collector. */
+ Py_CLEAR(self->externalTimer);
+
flush_unmatched(self);
clearEntries(self);
Py_XDECREF(self->missing);
- Py_XDECREF(self->externalTimer);
PyTypeObject *tp = Py_TYPE(self);
tp->tp_free(self);
Py_DECREF(tp);
}
/*[clinic input]
+@critical_section
_lsprof.Profiler.__init__ as profiler_init
timer: object(c_default='NULL') = None
@@ -1008,11 +1022,19 @@ is, in seconds).
static int
profiler_init_impl(ProfilerObject *self, PyObject *timer, double timeunit,
int subcalls, int builtins)
-/*[clinic end generated code: output=ac523803ec9f9df2 input=8285ca746f96a414]*/
+/*[clinic end generated code: output=ac523803ec9f9df2 input=5add5fc72beb63ba]*/
{
+ if (self->activeTimers) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "cannot initialize profiler in external timer");
+ return -1;
+ }
if (setSubcalls(self, subcalls) < 0 || setBuiltins(self, builtins) < 0) {
return -1;
}
+ if (timer == Py_None) {
+ timer = NULL;
+ }
self->externalTimerUnit = timeunit;
Py_XSETREF(self->externalTimer, Py_XNewRef(timer));
self->tool_id = PY_MONITORING_PROFILER_ID;
diff --git a/Modules/_lzmamodule.c b/Modules/_lzmamodule.c
index 4335a8bb162414d..92784904f3c9930 100644
--- a/Modules/_lzmamodule.c
+++ b/Modules/_lzmamodule.c
@@ -1509,6 +1509,62 @@ _lzma__decode_filter_properties_impl(PyObject *module, lzma_vli filter_id,
return result;
}
+
+PyDoc_STRVAR(lzma_version_info__doc__,
+"_lzma.lzma_version_info\n\
+\n\
+Lzma version information as a named tuple.");
+
+static PyStructSequence_Field lzma_version_info_fields[] = {
+ {"major", "Major release number"},
+ {"minor", "Minor release number"},
+ {"patch", "Patch release number"},
+ {"stability", "'alpha', 'beta', or 'stable'"},
+ {0}
+};
+
+static PyStructSequence_Desc lzma_version_info_desc = {
+ "_lzma.lzma_version_info", /* name */
+ lzma_version_info__doc__, /* doc */
+ lzma_version_info_fields, /* fields */
+ 4
+};
+
+static PyObject *
+make_lzma_version_info(PyTypeObject *type, unsigned int number)
+{
+ PyObject *version;
+ int pos = 0;
+ unsigned int major = number / 10000000u;
+ unsigned int minor = (number % 10000000u) / 10000u;
+ unsigned int patch = (number % 10000u) / 10u;
+ unsigned int stability = number % 10u;
+ const char *stability_string = (stability == 0) ? "alpha"
+ : (stability == 1) ? "beta"
+ : "stable";
+
+ version = PyStructSequence_New(type);
+ if (version == NULL) {
+ return NULL;
+ }
+
+#define SetItem(VALUE) \
+ PyStructSequence_SET_ITEM(version, pos++, VALUE); \
+ if (PyErr_Occurred()) { \
+ Py_DECREF(version); \
+ return NULL; \
+ }
+
+ SetItem(PyLong_FromUnsignedLong(major))
+ SetItem(PyLong_FromUnsignedLong(minor))
+ SetItem(PyLong_FromUnsignedLong(patch))
+ SetItem(PyUnicode_FromString(stability_string))
+#undef SetItem
+
+ return version;
+}
+
+
/* Some of our constants are more than 32 bits wide, so PyModule_AddIntConstant
would not work correctly on platforms with 32-bit longs. */
static int
@@ -1603,6 +1659,33 @@ lzma_exec(PyObject *module)
return -1;
}
+ /* lzma_version */
+ if (PyModule_Add(module, "LZMA_VERSION",
+ PyUnicode_FromString(LZMA_VERSION_STRING)) < 0) {
+ return -1;
+ }
+ if (PyModule_Add(module, "lzma_version",
+ PyUnicode_FromString(lzma_version_string())) < 0) {
+ return -1;
+ }
+ PyTypeObject *version_type;
+ version_type = PyStructSequence_NewType(&lzma_version_info_desc);
+ if (version_type == NULL) {
+ return -1;
+ }
+ if (PyModule_Add(module, "LZMA_VERSION_INFO",
+ make_lzma_version_info(version_type, LZMA_VERSION)) < 0)
+ {
+ Py_DECREF(version_type);
+ return -1;
+ }
+ if (PyModule_Add(module, "lzma_version_info",
+ make_lzma_version_info(version_type, lzma_version_number())) < 0)
+ {
+ Py_DECREF(version_type);
+ return -1;
+ }
+ Py_DECREF(version_type);
return 0;
}
diff --git a/Modules/_multiprocessing/clinic/multiprocessing.c.h b/Modules/_multiprocessing/clinic/multiprocessing.c.h
index 6d4f5c2afcfd398..ea6fffc428919b4 100644
--- a/Modules/_multiprocessing/clinic/multiprocessing.c.h
+++ b/Modules/_multiprocessing/clinic/multiprocessing.c.h
@@ -3,6 +3,7 @@ preserve
[clinic start generated code]*/
#include "pycore_modsupport.h" // _PyArg_CheckPositional()
+#include "pycore_unicodeobject.h" // _PyUnicode_AsUTF8NoNUL()
#if defined(MS_WINDOWS)
@@ -138,15 +139,10 @@ _multiprocessing_sem_unlink(PyObject *module, PyObject *arg)
_PyArg_BadArgument("sem_unlink", "argument", "str", arg);
goto exit;
}
- Py_ssize_t name_length;
- name = PyUnicode_AsUTF8AndSize(arg, &name_length);
+ name = _PyUnicode_AsUTF8NoNUL(arg);
if (name == NULL) {
goto exit;
}
- if (strlen(name) != (size_t)name_length) {
- PyErr_SetString(PyExc_ValueError, "embedded null character");
- goto exit;
- }
return_value = _multiprocessing_sem_unlink_impl(module, name);
exit:
@@ -164,4 +160,4 @@ _multiprocessing_sem_unlink(PyObject *module, PyObject *arg)
#ifndef _MULTIPROCESSING_SEND_METHODDEF
#define _MULTIPROCESSING_SEND_METHODDEF
#endif /* !defined(_MULTIPROCESSING_SEND_METHODDEF) */
-/*[clinic end generated code: output=73b4cb8428d816da input=a9049054013a1b77]*/
+/*[clinic end generated code: output=f5147f6a6e2cbd17 input=a9049054013a1b77]*/
diff --git a/Modules/_multiprocessing/clinic/semaphore.c.h b/Modules/_multiprocessing/clinic/semaphore.c.h
index 6b1c0092ce48160..962f0c88a3914fd 100644
--- a/Modules/_multiprocessing/clinic/semaphore.c.h
+++ b/Modules/_multiprocessing/clinic/semaphore.c.h
@@ -8,6 +8,7 @@ preserve
#endif
#include "pycore_critical_section.h"// Py_BEGIN_CRITICAL_SECTION()
#include "pycore_modsupport.h" // _PyArg_UnpackKeywords()
+#include "pycore_unicodeobject.h" // _PyUnicode_AsUTF8NoNUL()
#if defined(HAVE_MP_SEMAPHORE) && defined(MS_WINDOWS)
@@ -292,15 +293,10 @@ _multiprocessing_SemLock(PyTypeObject *type, PyObject *args, PyObject *kwargs)
_PyArg_BadArgument("SemLock", "argument 'name'", "str", fastargs[3]);
goto exit;
}
- Py_ssize_t name_length;
- name = PyUnicode_AsUTF8AndSize(fastargs[3], &name_length);
+ name = _PyUnicode_AsUTF8NoNUL(fastargs[3]);
if (name == NULL) {
goto exit;
}
- if (strlen(name) != (size_t)name_length) {
- PyErr_SetString(PyExc_ValueError, "embedded null character");
- goto exit;
- }
unlink = PyObject_IsTrue(fastargs[4]);
if (unlink < 0) {
goto exit;
@@ -337,7 +333,7 @@ _multiprocessing_SemLock__rebuild(PyObject *type, PyObject *const *args, Py_ssiz
int maxvalue;
const char *name;
- if (!_PyArg_ParseStack(args, nargs, ""F_SEM_HANDLE"iiz:_rebuild",
+ if (!PyArg_ParseArray(args, nargs, ""F_SEM_HANDLE"iiz:_rebuild",
&handle, &kind, &maxvalue, &name)) {
goto exit;
}
@@ -582,4 +578,4 @@ _multiprocessing_SemLock___exit__(PyObject *self, PyObject *const *args, Py_ssiz
#ifndef _MULTIPROCESSING_SEMLOCK___EXIT___METHODDEF
#define _MULTIPROCESSING_SEMLOCK___EXIT___METHODDEF
#endif /* !defined(_MULTIPROCESSING_SEMLOCK___EXIT___METHODDEF) */
-/*[clinic end generated code: output=d1e349d4ee3d4bbf input=a9049054013a1b77]*/
+/*[clinic end generated code: output=7a35732855b11781 input=a9049054013a1b77]*/
diff --git a/Modules/_multiprocessing/multiprocessing.c b/Modules/_multiprocessing/multiprocessing.c
index 201cedbb59818f2..6ca1bbe30f20c77 100644
--- a/Modules/_multiprocessing/multiprocessing.c
+++ b/Modules/_multiprocessing/multiprocessing.c
@@ -9,22 +9,6 @@
#include "multiprocessing.h"
-/*[python input]
-class HANDLE_converter(CConverter):
- type = "HANDLE"
- format_unit = '"F_HANDLE"'
-
- def parse_arg(self, argname, displayname, *, limited_capi):
- return self.format_code("""
- {paramname} = PyLong_AsVoidPtr({argname});
- if (!{paramname} && PyErr_Occurred()) {{{{
- goto exit;
- }}}}
- """,
- argname=argname)
-
-[python start generated code]*/
-/*[python end generated code: output=da39a3ee5e6b4b0d input=3cf0318efc6a8772]*/
/*[clinic input]
module _multiprocessing
diff --git a/Modules/_openssl_mem.h b/Modules/_openssl_mem.h
new file mode 100644
index 000000000000000..5284d9b5e63361a
--- /dev/null
+++ b/Modules/_openssl_mem.h
@@ -0,0 +1,56 @@
+// Route OpenSSL allocations through the raw memory allocators.
+// Shared by the _ssl and _hashlib modules.
+
+#ifndef Py_OPENSSL_MEM_H
+#define Py_OPENSSL_MEM_H
+
+#include "Python.h"
+
+#include // CRYPTO_set_mem_functions()
+
+// LibreSSL stubs out CRYPTO_set_mem_functions() and BoringSSL lacks it.
+// AWS-LC has it, but unlike OpenSSL it does not refuse to install hooks
+// after the first allocation, so earlier size-prefixed allocations would
+// be freed with the wrong allocator.
+#if !defined(LIBRESSL_VERSION_NUMBER) && !defined(OPENSSL_IS_BORINGSSL) \
+ && !defined(OPENSSL_IS_AWSLC)
+# define _Py_OPENSSL_CAN_SET_MEM_FUNCTIONS
+#endif
+
+#ifdef _Py_OPENSSL_CAN_SET_MEM_FUNCTIONS
+
+static void *
+_PyOpenSSL_Malloc(size_t size, const char *Py_UNUSED(file),
+ int Py_UNUSED(line))
+{
+ return PyMem_RawMalloc(size);
+}
+
+static void *
+_PyOpenSSL_Realloc(void *ptr, size_t size, const char *Py_UNUSED(file),
+ int Py_UNUSED(line))
+{
+ return PyMem_RawRealloc(ptr, size);
+}
+
+static void
+_PyOpenSSL_Free(void *ptr, const char *Py_UNUSED(file),
+ int Py_UNUSED(line))
+{
+ PyMem_RawFree(ptr);
+}
+
+#endif // _Py_OPENSSL_CAN_SET_MEM_FUNCTIONS
+
+static void
+_PyOpenSSL_SetupMemFunctions(void)
+{
+#ifdef _Py_OPENSSL_CAN_SET_MEM_FUNCTIONS
+ // Fails if OpenSSL has already allocated memory (e.g. another
+ // libcrypto user in the process); it then keeps its current allocator.
+ (void)CRYPTO_set_mem_functions(_PyOpenSSL_Malloc, _PyOpenSSL_Realloc,
+ _PyOpenSSL_Free);
+#endif
+}
+
+#endif // !Py_OPENSSL_MEM_H
diff --git a/Modules/_operator.c b/Modules/_operator.c
index 417403dc4c10c11..a0843971efe13e6 100644
--- a/Modules/_operator.c
+++ b/Modules/_operator.c
@@ -1740,7 +1740,7 @@ methodcaller_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
return (PyObject *)mc;
}
-static void
+static int
methodcaller_clear(PyObject *op)
{
methodcallerobject *mc = methodcallerobject_CAST(op);
@@ -1749,6 +1749,7 @@ methodcaller_clear(PyObject *op)
Py_CLEAR(mc->kwds);
Py_CLEAR(mc->vectorcall_args);
Py_CLEAR(mc->vectorcall_kwnames);
+ return 0;
}
static void
diff --git a/Modules/_pickle.c b/Modules/_pickle.c
index 034dd06b6ab4609..b8f9b1c92f20723 100644
--- a/Modules/_pickle.c
+++ b/Modules/_pickle.c
@@ -603,6 +603,13 @@ typedef struct {
Py_ssize_t me_value;
} PyMemoEntry;
+/* The top bit of me_value flags an object reached so far only through a weak
+ reference (memo indices are small non-negative ints, so it is free);
+ MEMO_INDEX() masks it out. Bit math in size_t; the store back into the
+ signed field relies on two's complement. */
+#define MEMO_WEAK_ONLY ((size_t)1 << (sizeof(size_t) * 8 - 1))
+#define MEMO_INDEX(v) ((Py_ssize_t)((size_t)(v) & ~MEMO_WEAK_ONLY))
+
typedef struct {
size_t mt_mask;
size_t mt_used;
@@ -647,6 +654,10 @@ typedef struct PicklerObject {
int running; /* True when a method of Pickler is executing. */
PyObject *fast_memo;
PyObject *buffer_callback; /* Callback for out-of-band buffers, or NULL */
+
+ Py_ssize_t weak_only_count; /* Number of memo entries flagged weak-only;
+ any left at the end of dump() are pickling
+ errors. */
} PicklerObject;
typedef struct UnpicklerObject {
@@ -669,6 +680,10 @@ typedef struct UnpicklerObject {
Py_ssize_t input_len;
Py_ssize_t next_read_idx;
Py_ssize_t prefetched_idx; /* index of first prefetched byte */
+ Py_ssize_t frame_end; /* End of the current frame, or -1 if not in a
+ frame. While in a frame, input_len is capped
+ here so reads can't cross it (PEP 3154). */
+ Py_ssize_t saved_input_len; /* input_len to restore when the frame ends. */
PyObject *read; /* read() method of the input stream. */
PyObject *readinto; /* readinto() method of the input stream. */
@@ -736,6 +751,8 @@ typedef struct {
/* Forward declarations */
static int save(PickleState *state, PicklerObject *, PyObject *, int);
+static int save_object(PickleState *state, PicklerObject *, PyObject *,
+ int pers_save, int weak);
static int save_reduce(PickleState *, PicklerObject *, PyObject *, PyObject *);
#include "clinic/_pickle.c.h"
@@ -1166,6 +1183,7 @@ _Pickler_New(PickleState *st)
self->running = 0;
self->fast_memo = NULL;
self->buffer_callback = NULL;
+ self->weak_only_count = 0;
PyObject_GC_Track(self);
return self;
@@ -1250,6 +1268,7 @@ _Unpickler_SetStringInput(UnpicklerObject *self, PyObject *input)
self->input_len = self->buffer.len;
self->next_read_idx = 0;
self->prefetched_idx = self->input_len;
+ self->frame_end = -1;
return self->input_len;
}
@@ -1260,6 +1279,30 @@ bad_readline(PickleState *st)
return -1;
}
+/* End the current frame, uncapping input_len. The frame must be fully read. */
+static void
+_Unpickler_EndFrame(UnpicklerObject *self)
+{
+ assert(self->frame_end >= 0);
+ assert(self->next_read_idx == self->frame_end);
+ self->input_len = self->saved_input_len;
+ self->frame_end = -1;
+}
+
+/* Reached the end of the current frame. If straddle, the read crosses the
+ frame boundary (PEP 3154) and fails; otherwise end the frame. */
+static int
+_Unpickler_LeaveFrame(PickleState *st, UnpicklerObject *self, int straddle)
+{
+ if (straddle) {
+ PyErr_SetString(st->UnpicklingError,
+ "pickle exhausted before end of frame");
+ return -1;
+ }
+ _Unpickler_EndFrame(self);
+ return 0;
+}
+
/* Skip any consumed data that was only prefetched using peek() */
static int
_Unpickler_SkipConsumed(UnpicklerObject *self)
@@ -1444,6 +1487,19 @@ _Unpickler_ReadImpl(UnpicklerObject *self, PickleState *st, char **s, Py_ssize_t
return -1;
}
+ if (self->frame_end >= 0) {
+ if (_Unpickler_LeaveFrame(st, self,
+ self->next_read_idx < self->frame_end) < 0) {
+ return -1;
+ }
+ /* Frame ended; the read may now be satisfied from the buffer. */
+ if (n <= self->input_len - self->next_read_idx) {
+ *s = self->input_buffer + self->next_read_idx;
+ self->next_read_idx += n;
+ return n;
+ }
+ }
+
/* This case is handled by the _Unpickler_Read() macro for efficiency */
assert(self->next_read_idx + n > self->input_len);
@@ -1489,6 +1545,25 @@ _Unpickler_ReadInto(PickleState *state, UnpicklerObject *self, char *buf,
}
}
+ if (self->frame_end >= 0) {
+ /* in_buffer > 0 is next_read_idx < frame_end on entry: frame data was
+ consumed above, so the read crosses the frame boundary. */
+ if (_Unpickler_LeaveFrame(state, self, in_buffer > 0) < 0) {
+ return -1;
+ }
+ in_buffer = self->input_len - self->next_read_idx;
+ if (in_buffer > 0) {
+ Py_ssize_t to_read = Py_MIN(in_buffer, n);
+ memcpy(buf, self->input_buffer + self->next_read_idx, to_read);
+ self->next_read_idx += to_read;
+ buf += to_read;
+ n -= to_read;
+ if (n == 0) {
+ return n;
+ }
+ }
+ }
+
/* Read from file */
if (!self->read) {
/* We're unpickling memory, this means the input is truncated */
@@ -1547,6 +1622,7 @@ _Unpickler_Readline(PickleState *state, UnpicklerObject *self, char **result)
{
Py_ssize_t i, num_read;
+rescan:
for (i = self->next_read_idx; i < self->input_len; i++) {
if (self->input_buffer[i] == '\n') {
char *line_start = self->input_buffer + self->next_read_idx;
@@ -1555,6 +1631,14 @@ _Unpickler_Readline(PickleState *state, UnpicklerObject *self, char **result)
return _Unpickler_CopyLine(self, line_start, num_read, result);
}
}
+ if (self->frame_end >= 0) {
+ if (_Unpickler_LeaveFrame(state, self,
+ self->next_read_idx < self->frame_end) < 0) {
+ return -1;
+ }
+ /* Frame ended; continue the line past its end. */
+ goto rescan;
+ }
if (!self->read)
return bad_readline(state);
@@ -1678,16 +1762,16 @@ _Unpickler_NewMemo(Py_ssize_t new_size)
return memo;
}
-/* Free the unpickler's memo, taking care to decref any items left in it. */
+/* Replace the unpickler's memo and release the old entries. */
static void
-_Unpickler_MemoCleanup(UnpicklerObject *self)
+_Unpickler_MemoCleanup(UnpicklerObject *self, PyObject **replacement)
{
Py_ssize_t i;
PyObject **memo = self->memo;
- if (self->memo == NULL)
+ self->memo = replacement;
+ if (memo == NULL)
return;
- self->memo = NULL;
i = self->memo_size;
while (--i >= 0) {
Py_XDECREF(memo[i]);
@@ -1729,6 +1813,8 @@ _Unpickler_New(PyObject *module)
self->input_len = 0;
self->next_read_idx = 0;
self->prefetched_idx = 0;
+ self->frame_end = -1;
+ self->saved_input_len = 0;
self->read = NULL;
self->readinto = NULL;
self->readline = NULL;
@@ -1836,25 +1922,26 @@ memo_get(PickleState *st, PicklerObject *self, PyObject *key)
PyErr_SetObject(PyExc_KeyError, key);
return -1;
}
+ Py_ssize_t idx = MEMO_INDEX(*value); /* mask off the weak-only flag bit */
if (!self->bin) {
pdata[0] = GET;
PyOS_snprintf(pdata + 1, sizeof(pdata) - 1,
- "%zd\n", *value);
+ "%zd\n", idx);
len = strlen(pdata);
}
else {
- if (*value < 256) {
+ if (idx < 256) {
pdata[0] = BINGET;
- pdata[1] = (unsigned char)(*value & 0xff);
+ pdata[1] = (unsigned char)(idx & 0xff);
len = 2;
}
- else if ((size_t)*value <= 0xffffffffUL) {
+ else if ((size_t)idx <= 0xffffffffUL) {
pdata[0] = LONG_BINGET;
- pdata[1] = (unsigned char)(*value & 0xff);
- pdata[2] = (unsigned char)((*value >> 8) & 0xff);
- pdata[3] = (unsigned char)((*value >> 16) & 0xff);
- pdata[4] = (unsigned char)((*value >> 24) & 0xff);
+ pdata[1] = (unsigned char)(idx & 0xff);
+ pdata[2] = (unsigned char)((idx >> 8) & 0xff);
+ pdata[3] = (unsigned char)((idx >> 16) & 0xff);
+ pdata[4] = (unsigned char)((idx >> 24) & 0xff);
len = 5;
}
else { /* unlikely */
@@ -4548,8 +4635,154 @@ save_reduce(PickleState *st, PicklerObject *self, PyObject *args,
return 0;
}
+/* Weak-only objects are flagged in place in the memo (the MEMO_WEAK_ONLY bit
+ of the value, see PyMemoEntry); self->weak_only_count tracks how many. The
+ value pointer comes from PyMemoTable_Get() and must not be held across an
+ insertion into the table (it may rehash). */
+
+static void
+memo_set_weak_only(PicklerObject *self, Py_ssize_t *value)
+{
+ if (*value >= 0) { /* not already flagged */
+ *value = (Py_ssize_t)((size_t)*value | MEMO_WEAK_ONLY);
+ self->weak_only_count++;
+ }
+}
+
+static void
+memo_clear_weak_only(PicklerObject *self, Py_ssize_t *value)
+{
+ if (*value < 0) { /* flagged */
+ *value = MEMO_INDEX(*value);
+ self->weak_only_count--;
+ }
+}
+
+/* Pickle a weakref.ref as weakref.ref(referent). The referent is pickled
+ *weakly* (no anchoring) and tagged weak-only only after its whole subtree,
+ so a strong cycle inside it cannot anchor it. See Lib/pickle.py. */
static int
-save(PickleState *st, PicklerObject *self, PyObject *obj, int pers_save)
+save_weakref(PickleState *st, PicklerObject *self, PyObject *obj)
+{
+ const char tuple1_op = TUPLE1;
+ const char tuple_op = TUPLE;
+ const char mark_op = MARK;
+ const char reduce_op = REDUCE;
+ const char pop_op = POP;
+ int status = -1;
+
+ PyObject *referent;
+ if (PyWeakref_GetRef(obj, &referent) < 0)
+ return -1;
+ if (referent == NULL) {
+ /* All dead references are interchangeable: pickle by name as the
+ weakref._dead_ref singleton. */
+ const char global_op = GLOBAL;
+ const char dead_ref_name[] = "weakref\n_dead_ref\n";
+ if (_Pickler_Write(self, &global_op, 1) < 0 ||
+ _Pickler_Write(self, dead_ref_name, sizeof(dead_ref_name) - 1) < 0)
+ {
+ return -1;
+ }
+ return 0;
+ }
+
+ /* Py_TYPE(obj) is exactly weakref.ref, the reconstructor. */
+ if (save(st, self, (PyObject *)Py_TYPE(obj), 0) < 0)
+ goto done;
+
+ /* A referent already in the memo is anchored or already tracked;
+ otherwise it is tagged below, until a strong save of it. */
+ int anchored = PyMemoTable_Get(self->memo, referent) != NULL;
+
+ /* Build the 1-tuple (referent,); TUPLE1 needs protocol 2. */
+ if (self->proto < 2 && _Pickler_Write(self, &mark_op, 1) < 0)
+ goto done;
+
+ if (save_object(st, self, referent, 0, 1) < 0)
+ goto done;
+
+ if (!anchored) {
+ Py_ssize_t *value = PyMemoTable_Get(self->memo, referent);
+ if (value != NULL)
+ memo_set_weak_only(self, value);
+ }
+
+ if (_Pickler_Write(self, self->proto >= 2 ? &tuple1_op : &tuple_op, 1) < 0 ||
+ _Pickler_Write(self, &reduce_op, 1) < 0)
+ goto done;
+
+ /* The referent's subtree may have pickled this very (cached) weakref
+ already; reuse the memoized one. */
+ if (PyMemoTable_Get(self->memo, obj)) {
+ if (_Pickler_Write(self, &pop_op, 1) < 0)
+ goto done;
+ if (memo_get(st, self, obj) < 0)
+ goto done;
+ }
+ else if (memo_put(st, self, obj) < 0) {
+ goto done;
+ }
+ status = 0;
+
+ done:
+ Py_DECREF(referent);
+ return status;
+}
+
+/* Build a sorted ", "-joined string of the distinct type names of the memo
+ objects still flagged weak-only, for the dump() error. */
+static PyObject *
+weak_only_type_names(PicklerObject *self)
+{
+ PyObject *names = PySet_New(NULL);
+ if (names == NULL)
+ return NULL;
+
+ PyMemoTable *memo = self->memo;
+ if (memo && memo->mt_table) {
+ for (size_t i = 0; i < memo->mt_allocated; i++) {
+ PyObject *key = memo->mt_table[i].me_key;
+ if (key == NULL || memo->mt_table[i].me_value >= 0)
+ continue; /* absent or not flagged weak-only */
+ PyObject *tname = PyType_GetFullyQualifiedName(Py_TYPE(key));
+ if (tname == NULL)
+ goto error;
+ int r = PySet_Add(names, tname);
+ Py_DECREF(tname);
+ if (r < 0)
+ goto error;
+ }
+ }
+
+ PyObject *lst = PySequence_List(names);
+ Py_CLEAR(names);
+ if (lst == NULL)
+ return NULL;
+ if (PyList_Sort(lst) < 0) {
+ Py_DECREF(lst);
+ return NULL;
+ }
+ PyObject *sep = PyUnicode_FromString(", ");
+ if (sep == NULL) {
+ Py_DECREF(lst);
+ return NULL;
+ }
+ PyObject *joined = PyUnicode_Join(sep, lst);
+ Py_DECREF(sep);
+ Py_DECREF(lst);
+ return joined;
+
+ error:
+ Py_DECREF(names);
+ return NULL;
+}
+
+/* `weak` is true only for save_weakref's immediate save of its referent; it
+ does not propagate to nested saves. All other callers go through save(). */
+static int
+save_object(PickleState *st, PicklerObject *self, PyObject *obj, int pers_save,
+ int weak)
{
PyTypeObject *type;
PyObject *reduce_func = NULL;
@@ -4596,7 +4829,11 @@ save(PickleState *st, PicklerObject *self, PyObject *obj, int pers_save)
/* Check the memo to see if it has the object. If so, generate
a GET (or BINGET) opcode, instead of pickling the object
once again. */
- if (PyMemoTable_Get(self->memo, obj)) {
+ Py_ssize_t *memo_value = PyMemoTable_Get(self->memo, obj);
+ if (memo_value != NULL) {
+ /* A strong reference anchors the object: no longer weak-only. */
+ if (!weak)
+ memo_clear_weak_only(self, memo_value);
return memo_get(st, self, obj);
}
@@ -4613,6 +4850,11 @@ save(PickleState *st, PicklerObject *self, PyObject *obj, int pers_save)
return -1;
}
+ if (PyWeakref_CheckRefExact(obj)) {
+ status = save_weakref(st, self, obj);
+ goto done;
+ }
+
if (type == &PyDict_Type) {
status = save_dict(st, self, obj);
goto done;
@@ -4673,17 +4915,9 @@ save(PickleState *st, PicklerObject *self, PyObject *obj, int pers_save)
* __reduce_ex__ method, or the object's __reduce__ method.
*/
if (self->dispatch_table == NULL) {
- reduce_func = PyDict_GetItemWithError(st->dispatch_table,
- (PyObject *)type);
- if (reduce_func == NULL) {
- if (PyErr_Occurred()) {
- goto error;
- }
- } else {
- /* PyDict_GetItemWithError() returns a borrowed reference.
- Increase the reference count to be consistent with
- PyObject_GetItem and _PyObject_GetAttrId used below. */
- Py_INCREF(reduce_func);
+ if (PyDict_GetItemRef(st->dispatch_table, (PyObject *)type,
+ &reduce_func) < 0) {
+ goto error;
}
}
else if (PyMapping_GetOptionalItem(self->dispatch_table, (PyObject *)type,
@@ -4755,6 +4989,14 @@ save(PickleState *st, PicklerObject *self, PyObject *obj, int pers_save)
if (status < 0) {
_PyErr_FormatNote("when serializing %T object", obj);
}
+ else if (!weak) {
+ /* A completed non-weak save anchors obj. Only save_reduce()
+ memoizes an object after its arguments, so only here can a weak
+ reference to a still-in-progress obj have tagged it. */
+ Py_ssize_t *value = PyMemoTable_Get(self->memo, obj);
+ if (value != NULL)
+ memo_clear_weak_only(self, value);
+ }
if (0) {
error:
@@ -4769,12 +5011,37 @@ save(PickleState *st, PicklerObject *self, PyObject *obj, int pers_save)
return status;
}
+static int
+save(PickleState *st, PicklerObject *self, PyObject *obj, int pers_save)
+{
+ return save_object(st, self, obj, pers_save, 0);
+}
+
static PyObject *
persistent_id(PyObject *self, PyObject *obj)
{
Py_RETURN_NONE;
}
+static PyObject *Pickler_getattr(PyObject *self, PyObject *name);
+
+/* Like PyObject_GetOptionalAttr(), but avoids creating an AttributeError
+ for a missing attribute. Must not be used for "persistent_id". */
+static int
+pickler_get_optional_attr(PicklerObject *self, PyObject *name,
+ PyObject **result)
+{
+ if (Py_TYPE(self)->tp_getattro == Pickler_getattr) {
+ *result = _PyObject_GenericGetAttrWithDict((PyObject *)self, name,
+ NULL, 1);
+ if (*result != NULL) {
+ return 1;
+ }
+ return PyErr_Occurred() ? -1 : 0;
+ }
+ return PyObject_GetOptionalAttr((PyObject *)self, name, result);
+}
+
static int
dump(PickleState *state, PicklerObject *self, PyObject *obj)
{
@@ -4796,8 +5063,8 @@ dump(PickleState *state, PicklerObject *self, PyObject *obj)
Py_XSETREF(self->persistent_id, tmp);
/* Cache the reducer_override method, if it exists. */
- if (PyObject_GetOptionalAttr((PyObject *)self, &_Py_ID(reducer_override),
- &tmp) < 0) {
+ if (pickler_get_optional_attr(self, &_Py_ID(reducer_override),
+ &tmp) < 0) {
goto error;
}
Py_XSETREF(self->reducer_override, tmp);
@@ -4814,8 +5081,22 @@ dump(PickleState *state, PicklerObject *self, PyObject *obj)
self->framing = 1;
}
- if (save(state, self, obj, 0) < 0 ||
- _Pickler_Write(self, &stop_op, 1) < 0 ||
+ if (save(state, self, obj, 0) < 0)
+ goto error;
+
+ if (self->weak_only_count > 0) {
+ /* These referents would be collected right after loading. */
+ PyObject *names = weak_only_type_names(self);
+ if (names == NULL)
+ goto error;
+ PyErr_Format(state->PicklingError,
+ "cannot pickle weak reference(s) whose referent(s) have "
+ "no strong reference in the pickle: %U", names);
+ Py_DECREF(names);
+ goto error;
+ }
+
+ if (_Pickler_Write(self, &stop_op, 1) < 0 ||
_Pickler_CommitFrame(self) < 0)
goto error;
@@ -4854,6 +5135,7 @@ _pickle_Pickler_clear_memo_impl(PicklerObject *self)
{
if (self->memo)
PyMemoTable_Clear(self->memo);
+ self->weak_only_count = 0;
Py_RETURN_NONE;
}
@@ -4956,6 +5238,8 @@ Pickler_clear(PyObject *op)
self->memo = NULL;
PyMemoTable_Del(memo);
}
+ /* The weak-only flags lived in the memo entries just freed. */
+ self->weak_only_count = 0;
return 0;
}
@@ -5077,8 +5361,8 @@ _pickle_Pickler___init___impl(PicklerObject *self, PyObject *file,
self->fast_memo = NULL;
if (self->dispatch_table == NULL) {
- if (PyObject_GetOptionalAttr((PyObject *)self, &_Py_ID(dispatch_table),
- &self->dispatch_table) < 0) {
+ if (pickler_get_optional_attr(self, &_Py_ID(dispatch_table),
+ &self->dispatch_table) < 0) {
goto error;
}
}
@@ -5143,7 +5427,7 @@ _pickle_PicklerMemoProxy_copy_impl(PicklerMemoProxyObject *self)
if (key == NULL) {
goto error;
}
- value = Py_BuildValue("nO", entry.me_value, entry.me_key);
+ value = Py_BuildValue("nO", MEMO_INDEX(entry.me_value), entry.me_key);
if (value == NULL) {
Py_DECREF(key);
goto error;
@@ -7078,6 +7362,17 @@ load_frame(PickleState *state, UnpicklerObject *self)
if (_Unpickler_Read(self, state, &s, 8) < 0)
return -1;
+ /* A new frame must not begin before the current one ends (PEP 3154). Its
+ header may lie at the tail of the current frame if it drains it. */
+ if (self->frame_end >= 0) {
+ if (self->next_read_idx < self->frame_end) {
+ PyErr_SetString(state->UnpicklingError,
+ "beginning of a new frame before end of current frame");
+ return -1;
+ }
+ _Unpickler_EndFrame(self);
+ }
+
frame_len = calc_binsize(s, 8);
if (frame_len < 0) {
PyErr_Format(PyExc_OverflowError,
@@ -7091,6 +7386,12 @@ load_frame(PickleState *state, UnpicklerObject *self)
/* Rewind to start of frame */
self->next_read_idx -= frame_len;
+
+ /* Cap input_len at the frame end so reads can't cross it (PEP 3154);
+ _Unpickler_EndFrame() restores it when the frame is fully read. */
+ self->frame_end = self->next_read_idx + frame_len;
+ self->saved_input_len = self->input_len;
+ self->input_len = self->frame_end;
return 0;
}
@@ -7468,7 +7769,7 @@ Unpickler_clear(PyObject *op)
}
Py_CLEAR(self->memo_dict);
- _Unpickler_MemoCleanup(self);
+ _Unpickler_MemoCleanup(self, NULL);
PyMem_Free(self->marks);
self->marks = NULL;
PyMem_Free(self->input_line);
@@ -7615,10 +7916,16 @@ static PyObject *
_pickle_UnpicklerMemoProxy_clear_impl(UnpicklerMemoProxyObject *self)
/*[clinic end generated code: output=d20cd43f4ba1fb1f input=b1df7c52e7afd9bd]*/
{
- _Unpickler_MemoCleanup(self->unpickler);
- self->unpickler->memo = _Unpickler_NewMemo(self->unpickler->memo_size);
- if (self->unpickler->memo == NULL)
+ UnpicklerObject *unpickler = self->unpickler;
+ PyObject **memo = _Unpickler_NewMemo(unpickler->memo_size);
+ if (memo == NULL) {
return NULL;
+ }
+ PyObject *memo_dict = unpickler->memo_dict;
+ unpickler->memo_dict = NULL;
+ unpickler->memo_len = 0;
+ _Unpickler_MemoCleanup(unpickler, memo);
+ Py_XDECREF(memo_dict);
Py_RETURN_NONE;
}
@@ -7823,7 +8130,7 @@ Unpickler_set_memo(PyObject *op, PyObject *obj, void *Py_UNUSED(closure))
return -1;
}
- _Unpickler_MemoCleanup(self);
+ _Unpickler_MemoCleanup(self, NULL);
self->memo_size = new_memo_size;
self->memo = new_memo;
diff --git a/Modules/_posixsubprocess.c b/Modules/_posixsubprocess.c
index 2aa3923f68e66ad..8ad01414ad80755 100644
--- a/Modules/_posixsubprocess.c
+++ b/Modules/_posixsubprocess.c
@@ -84,22 +84,6 @@ module _posixsubprocess
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=c62211df27cf7334]*/
-/*[python input]
-class pid_t_converter(CConverter):
- type = 'pid_t'
- format_unit = '" _Py_PARSE_PID "'
-
- def parse_arg(self, argname, displayname, *, limited_capi):
- return self.format_code("""
- {paramname} = PyLong_AsPid({argname});
- if ({paramname} == -1 && PyErr_Occurred()) {{{{
- goto exit;
- }}}}
- """,
- argname=argname)
-[python start generated code]*/
-/*[python end generated code: output=da39a3ee5e6b4b0d input=c94349aa1aad151d]*/
-
#include "clinic/_posixsubprocess.c.h"
/* Convert ASCII to a positive int, no libc call. no overflow. -1 on error. */
@@ -368,7 +352,8 @@ _close_range_except(int start_fd,
int (*closer)(int, int))
{
if (end_fd == -1) {
- end_fd = Py_MIN(safe_get_max_fd(), INT_MAX);
+ end_fd = safe_get_max_fd();
+ end_fd = Py_MIN(end_fd, INT_MAX);
}
Py_ssize_t keep_seq_idx;
/* As fds_to_keep is sorted we can loop through the list closing
@@ -388,20 +373,26 @@ _close_range_except(int start_fd,
return 0;
}
-#if defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)
+#if defined(_Py_HAVE_GETDENTS64) \
+ || (defined(__linux__) && defined(HAVE_SYS_SYSCALL_H))
+
+#ifdef _Py_HAVE_GETDENTS64
+# define py_dirent64 dirent64
+#else
/* It doesn't matter if d_name has room for NAME_MAX chars; we're using this
* only to read a directory of short file descriptor number names. The kernel
* will return an error if we didn't give it enough space. Highly Unlikely.
* This structure is very old and stable: It will not change unless the kernel
* chooses to break compatibility with all existing binaries. Highly Unlikely.
*/
-struct linux_dirent64 {
+struct py_dirent64 {
unsigned long long d_ino;
long long d_off;
unsigned short d_reclen; /* Length of this linux_dirent */
unsigned char d_type;
char d_name[256]; /* Filename (null-terminated) */
};
+#endif // !_Py_HAVE_GETDENTS64
static int
_brute_force_closer(int first, int last)
@@ -441,19 +432,31 @@ _close_open_fds_safe(int start_fd, int *fds_to_keep, Py_ssize_t fds_to_keep_len)
_brute_force_closer);
return;
} else {
- char buffer[sizeof(struct linux_dirent64)];
- int bytes;
- while ((bytes = syscall(SYS_getdents64, fd_dir_fd,
- (struct linux_dirent64 *)buffer,
- sizeof(buffer))) > 0) {
- struct linux_dirent64 *entry;
+ char buffer[sizeof(struct py_dirent64)];
+ Py_ssize_t bytes;
+ while (1) {
+#ifdef _Py_HAVE_GETDENTS64
+ /* musl <1.2.4 headers expose `getdents64` as an alias for `getdents`, whose buffer parameter
+ * is `struct dirent *`. We use `void *` to support both that interface and the glibc declaration
+ * without an incompatible-pointer diagnostic.
+ */
+ bytes = getdents64(fd_dir_fd, (void *)buffer, sizeof(buffer));
+#else
+ bytes = syscall(SYS_getdents64, fd_dir_fd,
+ (struct py_dirent64 *)buffer, sizeof(buffer));
+#endif
+ if (bytes <= 0) {
+ break;
+ }
+
+ struct py_dirent64 *entry;
int offset;
#ifdef _Py_MEMORY_SANITIZER
__msan_unpoison(buffer, bytes);
#endif
for (offset = 0; offset < bytes; offset += entry->d_reclen) {
int fd;
- entry = (struct linux_dirent64 *)(buffer + offset);
+ entry = (struct py_dirent64 *)(buffer + offset);
if ((fd = _pos_int_from_ascii(entry->d_name)) < 0)
continue; /* Not a number. */
if (fd != fd_dir_fd && fd >= start_fd &&
diff --git a/Modules/_queuemodule.c b/Modules/_queuemodule.c
index af54e42a6af584c..8ab5c7d5f2b88bc 100644
--- a/Modules/_queuemodule.c
+++ b/Modules/_queuemodule.c
@@ -51,13 +51,14 @@ RingBuf_Init(RingBuf *buf)
{
buf->put_idx = 0;
buf->get_idx = 0;
- buf->items_cap = INITIAL_RING_BUF_CAPACITY;
+ buf->items_cap = 0;
buf->num_items = 0;
- buf->items = PyMem_Calloc(buf->items_cap, sizeof(PyObject *));
+ buf->items = PyMem_Calloc(INITIAL_RING_BUF_CAPACITY, sizeof(PyObject *));
if (buf->items == NULL) {
PyErr_NoMemory();
return -1;
}
+ buf->items_cap = INITIAL_RING_BUF_CAPACITY;
return 0;
}
@@ -238,6 +239,7 @@ simplequeue_traverse(PyObject *op, visitproc visit, void *arg)
}
/*[clinic input]
+@vectorcall
@classmethod
_queue.SimpleQueue.__new__ as simplequeue_new
@@ -246,7 +248,7 @@ Simple, unbounded, reentrant FIFO queue.
static PyObject *
simplequeue_new_impl(PyTypeObject *type)
-/*[clinic end generated code: output=ba97740608ba31cd input=a0674a1643e3e2fb]*/
+/*[clinic end generated code: output=ba97740608ba31cd input=9113a69fd48c8e74]*/
{
simplequeueobject *self;
@@ -567,6 +569,7 @@ static PyType_Slot simplequeue_slots[] = {
{Py_tp_members, simplequeue_members},
{Py_tp_methods, simplequeue_methods},
{Py_tp_new, simplequeue_new},
+ {Py_tp_vectorcall, simplequeue_vectorcall},
{0, NULL},
};
diff --git a/Modules/_remote_debugging/_remote_debugging.h b/Modules/_remote_debugging/_remote_debugging.h
index fa37fb7b2167ecf..532fed28741738b 100644
--- a/Modules/_remote_debugging/_remote_debugging.h
+++ b/Modules/_remote_debugging/_remote_debugging.h
@@ -56,7 +56,6 @@ extern "C" {
# if TARGET_OS_OSX
# include
# include
-# define MAX_NATIVE_THREADS 4096
# endif
#endif
@@ -104,17 +103,7 @@ typedef struct {
#ifdef MS_WINDOWS
#define STATUS_SUCCESS ((NTSTATUS)0x00000000L)
-#define STATUS_INFO_LENGTH_MISMATCH ((NTSTATUS)0xC0000004L)
-typedef enum _WIN32_THREADSTATE {
- WIN32_THREADSTATE_INITIALIZED = 0,
- WIN32_THREADSTATE_READY = 1,
- WIN32_THREADSTATE_RUNNING = 2,
- WIN32_THREADSTATE_STANDBY = 3,
- WIN32_THREADSTATE_TERMINATED = 4,
- WIN32_THREADSTATE_WAITING = 5,
- WIN32_THREADSTATE_TRANSITION = 6,
- WIN32_THREADSTATE_UNKNOWN = 7
-} WIN32_THREADSTATE;
+#define STATUS_NO_MORE_ENTRIES ((NTSTATUS)0x8000001AL)
#endif
/* ============================================================================
@@ -132,7 +121,6 @@ typedef enum _WIN32_THREADSTATE {
#define SIZEOF_GEN_OBJ sizeof(PyGenObject)
#define SIZEOF_INTERP_FRAME sizeof(_PyInterpreterFrame)
#define SIZEOF_LLIST_NODE sizeof(struct llist_node)
-#define SIZEOF_PAGE_CACHE_ENTRY sizeof(page_cache_entry_t)
#define SIZEOF_PYOBJECT sizeof(PyObject)
#define SIZEOF_SET_OBJ sizeof(PySetObject)
#define SIZEOF_TASK_OBJ 4096
@@ -147,6 +135,8 @@ typedef enum _WIN32_THREADSTATE {
#define MAX_STACK_CHUNK_SIZE (16 * 1024 * 1024) /* 16 MB max for stack chunks */
#define MAX_LONG_DIGITS 64 /* Allows values up to ~2^1920 */
#define MAX_SET_TABLE_SIZE (1 << 20) /* 1 million entries max for set iteration */
+#define MAX_FRAME_CHAIN_DEPTH (1024 + 512) /* Iteration bound for frame chain walks */
+#define MAX_TASK_WAITER_WALK_TASKS (1 << 14) /* Total-task bound for waiter walks */
#ifndef MAX
#define MAX(a, b) ((a) > (b) ? (a) : (b))
@@ -180,7 +170,7 @@ typedef enum _WIN32_THREADSTATE {
#define set_exception_cause(unwinder, exc_type, message) \
do { \
assert(PyErr_Occurred() && "function returned -1 without setting exception"); \
- if (unwinder->debug && !_Py_RemoteDebug_HasPermissionError()) { \
+ if (unwinder->debug && !_Py_RemoteDebug_IsFatalReadError()) { \
_set_debug_exception_cause(exc_type, message); \
} \
} while (0)
@@ -384,14 +374,6 @@ typedef struct {
#ifdef Py_GIL_DISABLED
uint32_t tlbc_generation;
_Py_hashtable_t *tlbc_cache;
-#endif
-#ifdef __APPLE__
- uint64_t thread_id_offset;
- int thread_id_offset_initialized;
-#endif
-#ifdef MS_WINDOWS
- PVOID win_process_buffer;
- ULONG win_process_buffer_size;
#endif
// Thread stopping state (only on platforms that support it)
#ifdef Py_REMOTE_DEBUG_SUPPORTS_BLOCKING
@@ -478,12 +460,6 @@ typedef int (*thread_processor_func)(
void *context
);
-typedef int (*set_entry_processor_func)(
- RemoteUnwinderObject *unwinder,
- uintptr_t key_addr,
- void *context
-);
-
typedef int (*interpreter_processor_func)(
RuntimeOffsets *offsets,
uintptr_t interpreter_state_addr,
@@ -528,7 +504,6 @@ extern int validate_debug_offsets(struct _Py_DebugOffsets *debug_offsets);
* ============================================================================ */
extern int read_ptr(RemoteUnwinderObject *unwinder, uintptr_t address, uintptr_t *result);
-extern int read_Py_ssize_t(RemoteUnwinderObject *unwinder, uintptr_t address, Py_ssize_t *result);
extern int read_char(RemoteUnwinderObject *unwinder, uintptr_t address, char *result);
extern int read_py_ptr(RemoteUnwinderObject *unwinder, uintptr_t address, uintptr_t *ptr_addr);
@@ -599,7 +574,6 @@ extern int parse_frame_object(
RemoteUnwinderObject *unwinder,
PyObject** result,
uintptr_t address,
- uintptr_t* address_of_code_object,
uintptr_t* previous_frame
);
@@ -608,7 +582,6 @@ extern int parse_frame_from_chunks(
PyObject **result,
uintptr_t address,
uintptr_t *previous_frame,
- uintptr_t *stackpointer,
StackChunkList *chunks
);
@@ -685,8 +658,6 @@ extern int find_running_frame(
uintptr_t *frame
);
-extern int get_thread_status(RemoteUnwinderObject *unwinder, uint64_t tid, uint64_t pthread_id);
-
extern PyObject* unwind_stack_for_thread(
RemoteUnwinderObject *unwinder,
uintptr_t *current_tstate,
@@ -729,33 +700,11 @@ extern int parse_task(
PyObject *render_to
);
-extern int parse_coro_chain(
- RemoteUnwinderObject *unwinder,
- uintptr_t coro_address,
- PyObject *render_to
-);
-
extern int parse_async_frame_chain(
RemoteUnwinderObject *unwinder,
PyObject *calls,
uintptr_t address_of_thread,
- uintptr_t running_task_code_obj
-);
-
-/* Set iteration */
-extern int iterate_set_entries(
- RemoteUnwinderObject *unwinder,
- uintptr_t set_addr,
- set_entry_processor_func processor,
- void *context
-);
-
-/* Task awaited_by processing */
-extern int process_task_awaited_by(
- RemoteUnwinderObject *unwinder,
- uintptr_t task_address,
- set_entry_processor_func processor,
- void *context
+ uintptr_t running_task_frame
);
extern int process_single_task_node(
@@ -765,22 +714,16 @@ extern int process_single_task_node(
PyObject *result
);
-extern int process_task_and_waiters(
- RemoteUnwinderObject *unwinder,
- uintptr_t task_addr,
- PyObject *result
-);
-
extern int find_running_task_in_thread(
RemoteUnwinderObject *unwinder,
uintptr_t thread_state_addr,
uintptr_t *running_task_addr
);
-extern int get_task_code_object(
+extern int get_task_frame(
RemoteUnwinderObject *unwinder,
uintptr_t task_addr,
- uintptr_t *code_obj_addr
+ uintptr_t *frame_addr
);
extern int append_awaited_by(
diff --git a/Modules/_remote_debugging/asyncio.c b/Modules/_remote_debugging/asyncio.c
index 44a9a3cbce0061a..165d32ad31308bb 100644
--- a/Modules/_remote_debugging/asyncio.c
+++ b/Modules/_remote_debugging/asyncio.c
@@ -22,7 +22,7 @@ _Py_RemoteDebug_GetAsyncioDebugAddress(proc_handle_t* handle)
address = search_windows_map_for_section(handle, "AsyncioD", L"_asyncio",
NULL);
if (address == 0) {
- if (!_Py_RemoteDebug_HasPermissionError()) {
+ if (!_Py_RemoteDebug_IsFatalReadError()) {
PyObject *exc = PyErr_GetRaisedException();
PyErr_SetString(PyExc_RuntimeError, "Failed to find the AsyncioDebug section in the process.");
_PyErr_ChainExceptions1(exc);
@@ -33,23 +33,16 @@ _Py_RemoteDebug_GetAsyncioDebugAddress(proc_handle_t* handle)
address = search_linux_map_for_section(handle, "AsyncioDebug", "python",
NULL);
if (address == 0) {
- if (!_Py_RemoteDebug_HasPermissionError()) {
+ if (!_Py_RemoteDebug_IsFatalReadError()) {
PyObject *exc = PyErr_GetRaisedException();
PyErr_SetString(PyExc_RuntimeError, "Failed to find the AsyncioDebug section in the process.");
_PyErr_ChainExceptions1(exc);
}
}
#elif defined(__APPLE__) && TARGET_OS_OSX
- // On macOS, try libpython first, then fall back to python
- address = search_map_for_section(handle, "AsyncioDebug", "libpython",
- NULL);
- if (address == 0 && !_Py_RemoteDebug_HasPermissionError()) {
- PyErr_Clear();
- address = search_map_for_section(handle, "AsyncioDebug", "python",
- NULL);
- }
+ address = search_loaded_images_for_section(handle, "AsyncioDebug", NULL);
if (address == 0) {
- if (!_Py_RemoteDebug_HasPermissionError()) {
+ if (!_Py_RemoteDebug_IsFatalReadError()) {
PyObject *exc = PyErr_GetRaisedException();
PyErr_SetString(PyExc_RuntimeError, "Failed to find the AsyncioDebug section in the process.");
_PyErr_ChainExceptions1(exc);
@@ -99,12 +92,22 @@ ensure_async_debug_offsets(RemoteUnwinderObject *unwinder)
return -1;
}
if (result < 0) {
- if (!_Py_RemoteDebug_HasPermissionError()) {
- PyErr_Clear();
- PyErr_SetString(PyExc_RuntimeError, "AsyncioDebug section not available");
- set_exception_cause(unwinder, PyExc_RuntimeError,
- "AsyncioDebug section unavailable - asyncio module may not be loaded in target process");
+ if (_Py_RemoteDebug_IsFatalReadError()) {
+ return -1;
+ }
+ PyErr_Clear();
+ /* Image discovery can fail without reporting that the target exited.
+ Read a known runtime address before reporting unavailable asyncio. */
+ char runtime_byte;
+ if (_Py_RemoteDebug_ReadRemoteMemory(&unwinder->handle,
+ unwinder->runtime_start_address, sizeof(runtime_byte),
+ &runtime_byte) < 0)
+ {
+ return -1;
}
+ PyErr_SetString(PyExc_RuntimeError, "AsyncioDebug section not available");
+ set_exception_cause(unwinder, PyExc_RuntimeError,
+ "AsyncioDebug section unavailable - asyncio module may not be loaded in target process");
return -1;
}
@@ -116,12 +119,11 @@ ensure_async_debug_offsets(RemoteUnwinderObject *unwinder)
* SET ITERATION FUNCTIONS
* ============================================================================ */
-int
+static int
iterate_set_entries(
RemoteUnwinderObject *unwinder,
uintptr_t set_addr,
- set_entry_processor_func processor,
- void *context
+ PyObject *awaited_by
) {
char set_object[SIZEOF_SET_OBJ];
if (_Py_RemoteDebug_PagedReadRemoteMemory(&unwinder->handle, set_addr,
@@ -146,28 +148,22 @@ iterate_set_entries(
Py_ssize_t i = 0;
Py_ssize_t els = 0;
while (i < set_len && els < num_els) {
- uintptr_t key_addr;
- if (read_py_ptr(unwinder, table_ptr, &key_addr) < 0) {
- set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to read set entry key");
+ setentry entry;
+ if (_Py_RemoteDebug_PagedReadRemoteMemory(
+ &unwinder->handle, table_ptr, sizeof(entry), &entry) < 0)
+ {
+ set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to read set entry");
return -1;
}
- if ((void*)key_addr != NULL) {
- Py_ssize_t ref_cnt;
- if (read_Py_ssize_t(unwinder, table_ptr, &ref_cnt) < 0) {
- set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to read set entry ref count");
+ uintptr_t key_addr = (uintptr_t)entry.key;
+ if (key_addr != 0 && entry.hash != -1) {
+ if (parse_task(unwinder, key_addr, awaited_by) < 0) {
return -1;
}
-
- if (ref_cnt) {
- // Process this valid set entry
- if (processor(unwinder, key_addr, context) < 0) {
- return -1;
- }
- els++;
- }
+ els++;
}
- table_ptr += sizeof(void*) * 2;
+ table_ptr += sizeof(entry);
i++;
}
@@ -247,13 +243,67 @@ parse_task_name(
* COROUTINE CHAIN PARSING
* ============================================================================ */
+// gh-159620
+/* Return in *coro_addr the coroutine, generator or async generator to walk
+ for the awaitable at addr, or 0 if it is none (for example, a future). */
+static int
+get_coro_like_address(
+ RemoteUnwinderObject *unwinder,
+ uintptr_t addr,
+ uintptr_t *coro_addr
+) {
+ *coro_addr = 0;
+
+ // Skip user classes that share a name with the generator types below
+ uintptr_t type_addr;
+ unsigned long tp_flags;
+ if (read_ptr(unwinder, addr + (uintptr_t)unwinder->debug_offsets.pyobject.ob_type,
+ &type_addr) < 0
+ || _Py_RemoteDebug_PagedReadRemoteMemory(&unwinder->handle,
+ type_addr + (uintptr_t)unwinder->debug_offsets.type_object.tp_flags,
+ sizeof(tp_flags), &tp_flags) < 0)
+ {
+ set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to read awaitable type");
+ return -1;
+ }
+
+ if (tp_flags & Py_TPFLAGS_HEAPTYPE) {
+ return 0;
+ }
+
+ uintptr_t name_addr;
+ char name[32] = {0};
+ if (read_ptr(unwinder, type_addr + (uintptr_t)unwinder->debug_offsets.type_object.tp_name,
+ &name_addr) < 0
+ || _Py_RemoteDebug_PagedReadRemoteMemory(&unwinder->handle, name_addr,
+ sizeof(name) - 1, name) < 0)
+ {
+ set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to read awaitable type name");
+ return -1;
+ }
+
+ if (strcmp(name, "coroutine") == 0 || strcmp(name, "generator") == 0) {
+ *coro_addr = addr;
+ }
+ else if (strcmp(name, "async_generator_asend") == 0
+ || strcmp(name, "async_generator_athrow") == 0)
+ {
+ // asend and athrow are separate wrapper objects: read the pointer
+ // to their parent async generator, stored right after PyObject_HEAD
+ return read_ptr(unwinder, addr + (uintptr_t)unwinder->debug_offsets.pyobject.size,
+ coro_addr);
+ }
+ return 0;
+}
+
static int
-handle_yield_from_frame(
+get_awaited_coro_address(
RemoteUnwinderObject *unwinder,
uintptr_t gi_iframe_addr,
- uintptr_t gen_type_addr,
- PyObject *render_to
+ uintptr_t *next_coro
) {
+ *next_coro = 0;
+
// Read the entire interpreter frame at once
char iframe[SIZEOF_INTERP_FRAME];
int err = _Py_RemoteDebug_PagedReadRemoteMemory(
@@ -277,51 +327,20 @@ handle_yield_from_frame(
uintptr_t stackpointer_addr = GET_MEMBER_NO_TAG(uintptr_t, iframe, unwinder->debug_offsets.interpreter_frame.stackpointer);
if ((void*)stackpointer_addr != NULL) {
- uintptr_t gi_await_addr;
err = read_py_ptr(
unwinder,
stackpointer_addr - sizeof(void*) * 2,
- &gi_await_addr);
+ next_coro);
if (err) {
set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to read gi_await address");
return -1;
}
-
- if ((void*)gi_await_addr != NULL) {
- uintptr_t gi_await_addr_type_addr;
- err = read_ptr(
- unwinder,
- gi_await_addr + (uintptr_t)unwinder->debug_offsets.pyobject.ob_type,
- &gi_await_addr_type_addr);
- if (err) {
- set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to read gi_await type address");
- return -1;
- }
-
- if (gen_type_addr == gi_await_addr_type_addr) {
- /* This needs an explanation. We always start with parsing
- native coroutine / generator frames. Ultimately they
- are awaiting on something. That something can be
- a native coroutine frame or... an iterator.
- If it's the latter -- we can't continue building
- our chain. So the condition to bail out of this is
- to do that when the type of the current coroutine
- doesn't match the type of whatever it points to
- in its cr_await.
- */
- err = parse_coro_chain(unwinder, gi_await_addr, render_to);
- if (err) {
- set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to parse coroutine chain in yield_from");
- return -1;
- }
- }
- }
}
return 0;
}
-int
+static int
parse_coro_chain(
RemoteUnwinderObject *unwinder,
uintptr_t coro_address,
@@ -329,49 +348,67 @@ parse_coro_chain(
) {
assert((void*)coro_address != NULL);
- // Read the entire generator object at once
- char gen_object[SIZEOF_GEN_OBJ];
- int err = _Py_RemoteDebug_PagedReadRemoteMemory(
- &unwinder->handle,
- coro_address,
- SIZEOF_GEN_OBJ,
- gen_object);
- if (err < 0) {
- set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to read generator object in coro chain");
- return -1;
- }
+ for (size_t depth = 0; (void*)coro_address != NULL; depth++) {
+ if (depth >= MAX_FRAME_CHAIN_DEPTH) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "Too many coroutine frames (possible infinite loop)");
+ set_exception_cause(unwinder, PyExc_RuntimeError,
+ "Coroutine chain depth limit exceeded");
+ return -1;
+ }
- int8_t frame_state = GET_MEMBER(int8_t, gen_object, unwinder->debug_offsets.gen_object.gi_frame_state);
- if (frame_state == FRAME_CLEARED) {
- return 0;
- }
+ if (get_coro_like_address(unwinder, coro_address, &coro_address) < 0) {
+ return -1;
+ }
+ if ((void*)coro_address == NULL) {
+ return 0;
+ }
- uintptr_t gen_type_addr = GET_MEMBER(uintptr_t, gen_object, unwinder->debug_offsets.pyobject.ob_type);
+ // Read the entire generator object at once
+ char gen_object[SIZEOF_GEN_OBJ];
+ int err = _Py_RemoteDebug_PagedReadRemoteMemory(
+ &unwinder->handle,
+ coro_address,
+ SIZEOF_GEN_OBJ,
+ gen_object);
+ if (err < 0) {
+ set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to read generator object in coro chain");
+ return -1;
+ }
- PyObject* name = NULL;
+ int8_t frame_state = GET_MEMBER(int8_t, gen_object, unwinder->debug_offsets.gen_object.gi_frame_state);
+ if (frame_state == FRAME_CLEARED) {
+ return 0;
+ }
- // Parse the previous frame using the gi_iframe from local copy
- uintptr_t prev_frame;
- uintptr_t gi_iframe_addr = coro_address + (uintptr_t)unwinder->debug_offsets.gen_object.gi_iframe;
- uintptr_t address_of_code_object = 0;
- if (parse_frame_object(unwinder, &name, gi_iframe_addr, &address_of_code_object, &prev_frame) < 0) {
- set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to parse frame object in coro chain");
- return -1;
- }
+ PyObject* name = NULL;
- if (!name) {
- return 0;
- }
+ // Parse the previous frame using the gi_iframe from local copy
+ uintptr_t prev_frame;
+ uintptr_t gi_iframe_addr = coro_address + (uintptr_t)unwinder->debug_offsets.gen_object.gi_iframe;
+ if (parse_frame_object(unwinder, &name, gi_iframe_addr, &prev_frame) < 0) {
+ set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to parse frame object in coro chain");
+ return -1;
+ }
+
+ if (!name) {
+ return 0;
+ }
- if (PyList_Append(render_to, name)) {
+ if (PyList_Append(render_to, name)) {
+ Py_DECREF(name);
+ set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to append frame to coro chain");
+ return -1;
+ }
Py_DECREF(name);
- set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to append frame to coro chain");
- return -1;
- }
- Py_DECREF(name);
- if (frame_state == FRAME_SUSPENDED_YIELD_FROM) {
- return handle_yield_from_frame(unwinder, gi_iframe_addr, gen_type_addr, render_to);
+ if (frame_state != FRAME_SUSPENDED_YIELD_FROM) {
+ return 0;
+ }
+
+ if (get_awaited_coro_address(unwinder, gi_iframe_addr, &coro_address) < 0) {
+ return -1;
+ }
}
return 0;
@@ -384,13 +421,12 @@ parse_coro_chain(
static PyObject*
create_task_result(
RemoteUnwinderObject *unwinder,
- uintptr_t task_address
+ uintptr_t task_address,
+ char is_task
) {
PyObject* result = NULL;
PyObject *call_stack = NULL;
PyObject *tn = NULL;
- char task_obj[SIZEOF_TASK_OBJ];
- uintptr_t coro_addr;
// Create call_stack first since it's the first tuple element
call_stack = PyList_New(0);
@@ -406,25 +442,27 @@ create_task_result(
goto error;
}
- // Parse coroutine chain
- if (_Py_RemoteDebug_PagedReadRemoteMemory(&unwinder->handle, task_address,
- (size_t)unwinder->async_debug_offsets.asyncio_task_object.size,
- task_obj) < 0) {
- set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to read task object for coro chain");
- goto error;
- }
-
- coro_addr = GET_MEMBER_NO_TAG(uintptr_t, task_obj, unwinder->async_debug_offsets.asyncio_task_object.task_coro);
-
- if ((void*)coro_addr != NULL) {
- if (parse_coro_chain(unwinder, coro_addr, call_stack) < 0) {
- set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to parse coroutine chain");
+ if (is_task) {
+ char task_obj[SIZEOF_TASK_OBJ];
+ if (_Py_RemoteDebug_PagedReadRemoteMemory(&unwinder->handle, task_address,
+ (size_t)unwinder->async_debug_offsets.asyncio_task_object.size,
+ task_obj) < 0) {
+ set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to read task object for coro chain");
goto error;
}
- if (PyList_Reverse(call_stack)) {
- set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to reverse call stack");
- goto error;
+ uintptr_t coro_addr = GET_MEMBER_NO_TAG(uintptr_t, task_obj, unwinder->async_debug_offsets.asyncio_task_object.task_coro);
+
+ if ((void*)coro_addr != NULL) {
+ if (parse_coro_chain(unwinder, coro_addr, call_stack) < 0) {
+ set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to parse coroutine chain");
+ goto error;
+ }
+
+ if (PyList_Reverse(call_stack)) {
+ set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to reverse call stack");
+ goto error;
+ }
}
}
@@ -468,33 +506,10 @@ parse_task(
goto error;
}
- if (is_task) {
- result = create_task_result(unwinder, task_address);
- if (!result) {
- set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to create task result");
- goto error;
- }
- } else {
- // Create an empty CoroInfo for non-task objects
- RemoteDebuggingState *state = RemoteDebugging_GetStateFromObject((PyObject*)unwinder);
- result = PyStructSequence_New(state->CoroInfo_Type);
- if (result == NULL) {
- set_exception_cause(unwinder, PyExc_MemoryError, "Failed to create empty CoroInfo");
- goto error;
- }
- PyObject *empty_list = PyList_New(0);
- if (empty_list == NULL) {
- set_exception_cause(unwinder, PyExc_MemoryError, "Failed to create empty list");
- goto error;
- }
- PyObject *task_name = PyLong_FromUnsignedLongLong(task_address);
- if (task_name == NULL) {
- Py_DECREF(empty_list);
- set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to create task name");
- goto error;
- }
- PyStructSequence_SetItem(result, 0, empty_list); // This steals the reference
- PyStructSequence_SetItem(result, 1, task_name); // This steals the reference
+ result = create_task_result(unwinder, task_address, is_task);
+ if (result == NULL) {
+ set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to create task result");
+ goto error;
}
if (PyList_Append(render_to, result)) {
set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to append task result to render list");
@@ -513,40 +528,17 @@ parse_task(
* TASK AWAITED_BY PROCESSING
* ============================================================================ */
-// Forward declaration for mutual recursion
-static int process_waiter_task(RemoteUnwinderObject *unwinder, uintptr_t key_addr, void *context);
-
-// Processor function for parsing tasks in sets
-static int
-process_task_parser(
- RemoteUnwinderObject *unwinder,
- uintptr_t key_addr,
- void *context
-) {
- PyObject *awaited_by = (PyObject *)context;
- return parse_task(unwinder, key_addr, awaited_by);
-}
-
static int
parse_task_awaited_by(
RemoteUnwinderObject *unwinder,
uintptr_t task_address,
PyObject *awaited_by
) {
- return process_task_awaited_by(unwinder, task_address, process_task_parser, awaited_by);
-}
-
-int
-process_task_awaited_by(
- RemoteUnwinderObject *unwinder,
- uintptr_t task_address,
- set_entry_processor_func processor,
- void *context
-) {
- // Read the entire TaskObj at once
char task_obj[SIZEOF_TASK_OBJ];
+ size_t size = unwinder->async_debug_offsets.asyncio_task_object.task_awaited_by_is_set
+ + sizeof(char);
if (_Py_RemoteDebug_PagedReadRemoteMemory(&unwinder->handle, task_address,
- (size_t)unwinder->async_debug_offsets.asyncio_task_object.size,
+ size,
task_obj) < 0) {
set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to read task object");
return -1;
@@ -560,10 +552,10 @@ process_task_awaited_by(
char awaited_by_is_a_set = GET_MEMBER(char, task_obj, unwinder->async_debug_offsets.asyncio_task_object.task_awaited_by_is_set);
if (awaited_by_is_a_set) {
- return iterate_set_entries(unwinder, task_ab_addr, processor, context);
+ return iterate_set_entries(unwinder, task_ab_addr, awaited_by);
} else {
// Single task waiting
- return processor(unwinder, task_ab_addr, context);
+ return parse_task(unwinder, task_ab_addr, awaited_by);
}
}
@@ -580,7 +572,16 @@ process_single_task_node(
PyObject *result_item = NULL;
PyObject *coroutine_stack = NULL;
- tn = parse_task_name(unwinder, task_addr);
+ char is_task;
+ // task_is_task = 1 => task
+ // task_is_task = 0 => future
+ if (read_char(unwinder,
+ task_addr + unwinder->async_debug_offsets.asyncio_task_object.task_is_task,
+ &is_task) < 0) {
+ goto error;
+ }
+ tn = is_task ? parse_task_name(unwinder, task_addr)
+ : PyUnicode_FromFormat("Future-%p", (void *)task_addr);
if (tn == NULL) {
set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to parse task name in single task node");
goto error;
@@ -621,6 +622,7 @@ process_single_task_node(
PyStructSequence_SetItem(result_item, 1, tn); // steals ref
PyStructSequence_SetItem(result_item, 2, coroutine_stack); // steals ref
PyStructSequence_SetItem(result_item, 3, current_awaited_by); // steals ref
+ PyStructSequence_SetItem(result_item, 4, PyBool_FromLong(!is_task));
// References transferred to tuple
task_id = NULL;
@@ -658,30 +660,71 @@ process_single_task_node(
return -1;
}
-int
-process_task_and_waiters(
+static int
+process_task_waiters(
RemoteUnwinderObject *unwinder,
- uintptr_t task_addr,
- PyObject *result
+ PyObject *result,
+ bool futures_only
) {
- // First, add this task to the result
- if (process_single_task_node(unwinder, task_addr, NULL, result) < 0) {
+ Py_ssize_t initial_count = futures_only ? PyList_GET_SIZE(result) : 0;
+ PyObject *visited = PySet_New(NULL);
+ if (visited == NULL) {
return -1;
}
+ for (Py_ssize_t i = 0; i < PyList_GET_SIZE(result); i++) {
+ PyObject *task_info = PyList_GET_ITEM(result, i);
+ if (PySet_Add(visited, PyStructSequence_GET_ITEM(task_info, 0)) < 0) {
+ goto error;
+ }
+ PyObject *waiters = PyStructSequence_GET_ITEM(task_info, 3);
+ for (Py_ssize_t j = 0; j < PyList_GET_SIZE(waiters); j++) {
+ PyObject *waiter = PyList_GET_ITEM(waiters, j);
+ PyObject *task_id = PyStructSequence_GET_ITEM(waiter, 1);
+ int seen = PySet_Contains(visited, task_id);
+ if (seen > 0) {
+ continue;
+ }
+ if (seen < 0 || PySet_Add(visited, task_id) < 0) {
+ goto error;
+ }
+ void *task_ptr = PyLong_AsVoidPtr(task_id);
+ if (task_ptr == NULL && PyErr_Occurred()) {
+ set_exception_cause(unwinder, PyExc_RuntimeError,
+ "Failed to parse waiter task ID");
+ goto error;
+ }
+ if (futures_only) {
+ char is_task;
+ if (read_char(unwinder,
+ (uintptr_t)task_ptr + unwinder->async_debug_offsets.asyncio_task_object.task_is_task,
+ &is_task) < 0) {
+ goto error;
+ }
+ if (is_task) {
+ continue;
+ }
+ }
+ if (PyList_GET_SIZE(result) - initial_count >= MAX_TASK_WAITER_WALK_TASKS) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "Too many task waiters (possible infinite loop)");
+ set_exception_cause(unwinder, PyExc_RuntimeError,
+ "Task waiter walk size limit exceeded");
+ goto error;
+ }
+ if (process_single_task_node(
+ unwinder, (uintptr_t)task_ptr, NULL, result) < 0)
+ {
+ goto error;
+ }
+ }
+ }
- // Now find all tasks that are waiting for this task and process them
- return process_task_awaited_by(unwinder, task_addr, process_waiter_task, result);
-}
+ Py_DECREF(visited);
+ return 0;
-// Processor function for task waiters
-static int
-process_waiter_task(
- RemoteUnwinderObject *unwinder,
- uintptr_t key_addr,
- void *context
-) {
- PyObject *result = (PyObject *)context;
- return process_task_and_waiters(unwinder, key_addr, result);
+error:
+ Py_DECREF(visited);
+ return -1;
}
/* ============================================================================
@@ -724,7 +767,7 @@ find_running_task_in_thread(
}
int
-get_task_code_object(RemoteUnwinderObject *unwinder, uintptr_t task_addr, uintptr_t *code_obj_addr) {
+get_task_frame(RemoteUnwinderObject *unwinder, uintptr_t task_addr, uintptr_t *frame_addr) {
uintptr_t running_coro_addr = 0;
if(read_py_ptr(
@@ -741,21 +784,15 @@ get_task_code_object(RemoteUnwinderObject *unwinder, uintptr_t task_addr, uintpt
return -1;
}
- // note: genobject's gi_iframe is an embedded struct so the address to
- // the offset leads directly to its first field: f_executable
- if (read_py_ptr(
- unwinder,
- running_coro_addr + (uintptr_t)unwinder->debug_offsets.gen_object.gi_iframe, code_obj_addr) < 0) {
- set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to read running task code object");
+ if (get_coro_like_address(unwinder, running_coro_addr, &running_coro_addr) < 0) {
return -1;
}
-
- if (*code_obj_addr == 0) {
- PyErr_SetString(PyExc_RuntimeError, "Running task code object is NULL");
- set_exception_cause(unwinder, PyExc_RuntimeError, "Running task code object address is NULL");
- return -1;
+ if (running_coro_addr == 0) {
+ *frame_addr = 0;
+ return 0;
}
+ *frame_addr = running_coro_addr + (uintptr_t)unwinder->debug_offsets.gen_object.gi_iframe;
return 0;
}
@@ -768,22 +805,29 @@ parse_async_frame_chain(
RemoteUnwinderObject *unwinder,
PyObject *calls,
uintptr_t address_of_thread,
- uintptr_t running_task_code_obj
+ uintptr_t running_task_frame
) {
+ Py_ssize_t coro_chain_size = PyList_GET_SIZE(calls);
uintptr_t address_of_current_frame;
if (find_running_frame(unwinder, address_of_thread, &address_of_current_frame) < 0) {
set_exception_cause(unwinder, PyExc_RuntimeError, "Running frame search failed in async chain");
return -1;
}
+ size_t frame_count = 0;
while ((void*)address_of_current_frame != NULL) {
+ if (++frame_count > MAX_FRAME_CHAIN_DEPTH) {
+ PyErr_SetString(PyExc_RuntimeError, "Too many async stack frames (possible infinite loop)");
+ set_exception_cause(unwinder, PyExc_RuntimeError, "Async frame chain iteration limit exceeded");
+ return -1;
+ }
PyObject* frame_info = NULL;
- uintptr_t address_of_code_object;
+
+ uintptr_t this_frame = address_of_current_frame;
int res = parse_frame_object(
unwinder,
&frame_info,
address_of_current_frame,
- &address_of_code_object,
&address_of_current_frame
);
@@ -804,12 +848,15 @@ parse_async_frame_chain(
Py_DECREF(frame_info);
- if (address_of_code_object == running_task_code_obj) {
- break;
+ // Stop at the task's own frame. Code objects are shared by
+ // recursive calls, so they cannot identify it.
+ if (this_frame == running_task_frame) {
+ return PyList_SetSlice(calls, 0, coro_chain_size, NULL);
}
}
- return 0;
+ // gh-159645: keep the coroutine chain if the task's frame was not found.
+ return PyList_SetSlice(calls, coro_chain_size, PY_SSIZE_T_MAX, NULL);
}
/* ============================================================================
@@ -870,11 +917,11 @@ append_awaited_by_for_thread(
return 0;
}
-int
-append_awaited_by(
+static int
+append_awaited_info(
RemoteUnwinderObject *unwinder,
unsigned long tid,
- uintptr_t head_addr,
+ PyObject *task_list,
PyObject *result)
{
PyObject *tid_py = PyLong_FromUnsignedLong(tid);
@@ -883,24 +930,16 @@ append_awaited_by(
return -1;
}
- PyObject* awaited_by_for_thread = PyList_New(0);
- if (awaited_by_for_thread == NULL) {
- Py_DECREF(tid_py);
- set_exception_cause(unwinder, PyExc_MemoryError, "Failed to create awaited_by thread list");
- return -1;
- }
-
RemoteDebuggingState *state = RemoteDebugging_GetStateFromObject((PyObject*)unwinder);
PyObject *result_item = PyStructSequence_New(state->AwaitedInfo_Type);
if (result_item == NULL) {
Py_DECREF(tid_py);
- Py_DECREF(awaited_by_for_thread);
set_exception_cause(unwinder, PyExc_MemoryError, "Failed to create AwaitedInfo");
return -1;
}
- PyStructSequence_SetItem(result_item, 0, tid_py); // steals ref
- PyStructSequence_SetItem(result_item, 1, awaited_by_for_thread); // steals ref
+ PyStructSequence_SetItem(result_item, 0, tid_py);
+ PyStructSequence_SetItem(result_item, 1, Py_NewRef(task_list));
if (PyList_Append(result, result_item)) {
Py_DECREF(result_item);
set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to append awaited_by result item");
@@ -908,13 +947,35 @@ append_awaited_by(
}
Py_DECREF(result_item);
- if (append_awaited_by_for_thread(unwinder, head_addr, awaited_by_for_thread))
- {
+ return 0;
+}
+
+int
+append_awaited_by(
+ RemoteUnwinderObject *unwinder,
+ unsigned long tid,
+ uintptr_t head_addr,
+ PyObject *result)
+{
+ PyObject *task_list = PyList_New(0);
+ if (task_list == NULL) {
+ set_exception_cause(unwinder, PyExc_MemoryError, "Failed to create awaited_by thread list");
+ return -1;
+ }
+
+ if (append_awaited_info(unwinder, tid, task_list, result) < 0) {
+ Py_DECREF(task_list);
+ return -1;
+ }
+
+ int err = append_awaited_by_for_thread(unwinder, head_addr, task_list);
+ Py_DECREF(task_list);
+ if (err < 0) {
set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to append awaited_by for thread");
return -1;
}
- return 0;
+ return process_task_waiters(unwinder, task_list, true);
}
/* ============================================================================
@@ -940,8 +1001,8 @@ process_running_task_chain(
uintptr_t thread_state_addr,
PyObject *result
) {
- uintptr_t running_task_code_obj = 0;
- if(get_task_code_object(unwinder, running_task_addr, &running_task_code_obj) < 0) {
+ uintptr_t running_task_frame = 0;
+ if(get_task_frame(unwinder, running_task_addr, &running_task_frame) < 0) {
return -1;
}
@@ -951,6 +1012,11 @@ process_running_task_chain(
return -1;
}
+ // gh-159645: non-native coroutines have no frame to look for.
+ if (running_task_frame == 0) {
+ return process_task_waiters(unwinder, result, false);
+ }
+
// Get the chain from the current frame to this task
PyObject *coro_chain = PyStructSequence_GET_ITEM(task_info, 2);
assert(coro_chain != NULL);
@@ -966,19 +1032,13 @@ process_running_task_chain(
PyObject *frame_chain = PyStructSequence_GET_ITEM(coro_info, 0);
assert(frame_chain != NULL);
- // Clear the coro_chain
- if (PyList_Clear(frame_chain) < 0) {
- set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to clear coroutine chain");
- return -1;
- }
-
// Add the chain from the current frame to this task
- if (parse_async_frame_chain(unwinder, frame_chain, thread_state_addr, running_task_code_obj) < 0) {
+ if (parse_async_frame_chain(unwinder, frame_chain, thread_state_addr, running_task_frame) < 0) {
return -1;
}
// Now find all tasks that are waiting for this task and process them
- if (process_task_awaited_by(unwinder, running_task_addr, process_waiter_task, result) < 0) {
+ if (process_task_waiters(unwinder, result, false) < 0) {
return -1;
}
@@ -1014,32 +1074,9 @@ process_thread_for_async_stack_trace(
return -1;
}
- // Create AwaitedInfo structure for this thread
- PyObject *tid_py = PyLong_FromUnsignedLong(tid);
- if (tid_py == NULL) {
- Py_DECREF(task_list);
- set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to create thread ID");
- return -1;
- }
-
- RemoteDebuggingState *state = RemoteDebugging_GetStateFromObject((PyObject*)unwinder);
- PyObject *awaited_info = PyStructSequence_New(state->AwaitedInfo_Type);
- if (awaited_info == NULL) {
- Py_DECREF(tid_py);
- Py_DECREF(task_list);
- set_exception_cause(unwinder, PyExc_MemoryError, "Failed to create AwaitedInfo");
- return -1;
- }
-
- PyStructSequence_SetItem(awaited_info, 0, tid_py); // steals ref
- PyStructSequence_SetItem(awaited_info, 1, task_list); // steals ref
-
- if (PyList_Append(result, awaited_info)) {
- Py_DECREF(awaited_info);
- set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to append AwaitedInfo to result");
- return -1;
- }
- Py_DECREF(awaited_info);
+ int err = append_awaited_info(unwinder, tid, task_list, result);
+ Py_DECREF(task_list);
+ return err;
}
return 0;
diff --git a/Modules/_remote_debugging/binary_io.h b/Modules/_remote_debugging/binary_io.h
index 8c34668ab15ae7e..b89bb9bbedf67d2 100644
--- a/Modules/_remote_debugging/binary_io.h
+++ b/Modules/_remote_debugging/binary_io.h
@@ -2,7 +2,7 @@
* Python Remote Debugging Module - Binary I/O Header
*
* This header provides declarations for high-performance binary file I/O
- * for profiling data with optional zstd streaming compression.
+ * for profiling data with optional zstd compression.
******************************************************************************/
#ifndef Py_BINARY_IO_H
@@ -23,7 +23,7 @@ extern "C" {
#define BINARY_FORMAT_MAGIC 0x54414348 /* "TACH" (Tachyon) in native byte order */
#define BINARY_FORMAT_MAGIC_SWAPPED 0x48434154 /* Byte-swapped magic for endianness detection */
-#define BINARY_FORMAT_VERSION 1
+#define BINARY_FORMAT_VERSION 2
/* Sentinel values for optional frame fields */
#define OPCODE_NONE 255 /* No opcode captured (u8 sentinel) */
@@ -59,23 +59,40 @@ extern "C" {
#define HDR_SIZE_FRAME_TABLE 8
#define HDR_OFF_COMPRESSION (HDR_OFF_FRAME_TABLE + HDR_SIZE_FRAME_TABLE)
#define HDR_SIZE_COMPRESSION 4
-#define FILE_HEADER_SIZE (HDR_OFF_COMPRESSION + HDR_SIZE_COMPRESSION)
+#define HDR_OFF_CONFIG (HDR_OFF_COMPRESSION + HDR_SIZE_COMPRESSION)
+#define HDR_SIZE_CONFIG 4
+#define FILE_HEADER_SIZE (HDR_OFF_CONFIG + HDR_SIZE_CONFIG)
#define FILE_HEADER_PLACEHOLDER_SIZE 64
static_assert(FILE_HEADER_SIZE <= FILE_HEADER_PLACEHOLDER_SIZE,
"FILE_HEADER_SIZE exceeds FILE_HEADER_PLACEHOLDER_SIZE");
-/* Sample header field offsets and sizes */
-#define SMP_OFF_THREAD_ID 0
-#define SMP_SIZE_THREAD_ID sizeof(uint64_t)
-#define SMP_OFF_INTERPRETER_ID (SMP_OFF_THREAD_ID + SMP_SIZE_THREAD_ID)
-#define SMP_SIZE_INTERPRETER_ID sizeof(uint32_t)
-#define SMP_OFF_ENCODING (SMP_OFF_INTERPRETER_ID + SMP_SIZE_INTERPRETER_ID)
-#define SMP_SIZE_ENCODING sizeof(uint8_t)
-#define SAMPLE_HEADER_FIXED_SIZE (SMP_OFF_ENCODING + SMP_SIZE_ENCODING)
-
-static_assert(SAMPLE_HEADER_FIXED_SIZE == 13,
- "SAMPLE_HEADER_FIXED_SIZE must remain 13");
+/* Sample blocks */
+#define BLOCK_MAGIC "TBLK"
+#define BLOCK_MAGIC_SIZE (sizeof(BLOCK_MAGIC) - 1)
+#define MAX_BLOCK_SIZE (1024 * 1024)
+#define MAX_BLOCK_STREAMS 4096
+
+/* Block columns */
+enum {
+ COLUMN_STREAM_TABLE,
+ COLUMN_SAMPLE_STREAM_IDS,
+ COLUMN_TIMESTAMP_RESIDUALS,
+ COLUMN_STATUS_BITMAPS,
+ COLUMN_STACK_INSTRUCTIONS,
+ COLUMN_FRAME_IDS,
+ COLUMN_COUNT
+};
+
+/* Stream table entry offsets and sizes */
+#define STM_OFF_THREAD_ID 0
+#define STM_SIZE_THREAD_ID sizeof(uint64_t)
+#define STM_OFF_INTERPRETER_ID (STM_OFF_THREAD_ID + STM_SIZE_THREAD_ID)
+#define STM_SIZE_INTERPRETER_ID sizeof(uint32_t)
+#define STREAM_ENTRY_SIZE (STM_OFF_INTERPRETER_ID + STM_SIZE_INTERPRETER_ID)
+
+static_assert(STREAM_ENTRY_SIZE == 12,
+ "STREAM_ENTRY_SIZE must remain 12");
/* Footer field offsets and sizes */
#define FTR_OFF_STRINGS 0
@@ -91,32 +108,79 @@ static_assert(SAMPLE_HEADER_FIXED_SIZE == 13,
static_assert(FILE_FOOTER_SIZE == 32,
"FILE_FOOTER_SIZE must remain 32");
+/* Optional profiling statistics immediately precede the footer. The
+ * signature and size live at the end so readers can discover extensions
+ * without changing the fixed header or moving streamed sample data. */
+#define PROFILE_STATS_MAGIC "TACHSTAT"
+#define PROFILE_STATS_MAGIC_SIZE 8
+#define PROFILE_STATS_VERSION 1
+#define PST_OFF_DURATION 0
+#define PST_SIZE_DURATION 8
+#define PST_OFF_SAMPLE_RATE (PST_OFF_DURATION + PST_SIZE_DURATION)
+#define PST_SIZE_SAMPLE_RATE 8
+#define PST_OFF_ERROR_RATE (PST_OFF_SAMPLE_RATE + PST_SIZE_SAMPLE_RATE)
+#define PST_SIZE_ERROR_RATE 8
+#define PST_OFF_MISSED_SAMPLES (PST_OFF_ERROR_RATE + PST_SIZE_ERROR_RATE)
+#define PST_SIZE_MISSED_SAMPLES 8
+#define PST_OFF_PRESENT (PST_OFF_MISSED_SAMPLES + PST_SIZE_MISSED_SAMPLES)
+#define PST_SIZE_PRESENT 4
+#define PST_OFF_RESERVED (PST_OFF_PRESENT + PST_SIZE_PRESENT)
+#define PST_SIZE_RESERVED 4
+#define PST_OFF_MAGIC (PST_OFF_RESERVED + PST_SIZE_RESERVED)
+#define PST_OFF_VERSION (PST_OFF_MAGIC + PROFILE_STATS_MAGIC_SIZE)
+#define PST_SIZE_VERSION 4
+#define PST_OFF_SIZE (PST_OFF_VERSION + PST_SIZE_VERSION)
+#define PST_SIZE_SIZE 4
+#define PROFILE_STATS_SIZE (PST_OFF_SIZE + PST_SIZE_SIZE)
+#define PROFILE_STATS_V1_SIZE 32
+#define PROFILE_STATS_ERROR_RATE 0x01
+#define PROFILE_STATS_MISSED 0x02
+
+static_assert(PROFILE_STATS_SIZE == 56,
+ "PROFILE_STATS_SIZE must remain 56");
+
/* Minimum on-disk bytes of a string (1) and frame (7) table entry. */
#define MIN_STRING_ENTRY_SIZE 1
#define MIN_FRAME_ENTRY_SIZE 7
-/* Buffer sizes: 512KB balances syscall amortization against memory use,
- * and aligns well with filesystem block sizes and zstd dictionary windows */
-#define WRITE_BUFFER_SIZE (512 * 1024)
-#define COMPRESSED_BUFFER_SIZE (512 * 1024)
-
/* Compression types */
#define COMPRESSION_NONE 0
#define COMPRESSION_ZSTD 1
+#define COLUMN_CONSTANT 2 /* Column stored as one repeated byte */
+
+/* Profiling configuration. The mode occupies the low three bits and is
+ * stored plus one so zero remains compatible with files written before this
+ * field was defined. Capture features are valid when bit 3 is set. */
+#define PROFILING_CONFIG_MODE_MASK 0x7U
+#define PROFILING_CONFIG_FEATURES_KNOWN (1U << 3)
+#define PROFILING_CONFIG_FEATURES_SHIFT 4
+#define PROFILING_FEATURE_ALL_THREADS (1U << 0)
+#define PROFILING_FEATURE_NATIVE (1U << 1)
+#define PROFILING_FEATURE_GC (1U << 2)
+#define PROFILING_FEATURE_OPCODES (1U << 3)
+#define PROFILING_FEATURE_BLOCKING (1U << 4)
+#define PROFILING_FEATURE_MASK 0x1FU
/* Stack encoding types for delta compression */
#define STACK_REPEAT 0x00 /* RLE: identical to previous, with count */
-#define STACK_FULL 0x01 /* Full stack (first sample or no match) */
-#define STACK_SUFFIX 0x02 /* Shares N frames from bottom */
-#define STACK_POP_PUSH 0x03 /* Remove M frames, add N frames */
+#define STACK_REPLACE_SUFFIX 0x01 /* Keep outer frames, append new ones */
+#define STACK_REUSE 0x02 /* Stack stored earlier in the block */
/* Maximum stack depth we'll buffer for delta encoding */
#define MAX_STACK_DEPTH 256
+/* Writer's stack cache size per block */
+#define STACK_CACHE_SIZE 4096
+#define STACK_CACHE_BUCKET_SIZE 2
+#define STACK_CACHE_BUCKET_COUNT \
+ (STACK_CACHE_SIZE / STACK_CACHE_BUCKET_SIZE)
+
/* Initial capacities for dynamic arrays - sized to reduce reallocations */
#define INITIAL_STRING_CAPACITY 4096
#define INITIAL_FRAME_CAPACITY 4096
#define INITIAL_THREAD_CAPACITY 256
+#define INITIAL_BLOCK_CAPACITY 256
+#define INITIAL_BLOCK_STREAM_CAPACITY 16
/* ============================================================================
* STATISTICS STRUCTURES
@@ -128,7 +192,7 @@ typedef struct {
uint64_t repeat_samples; /* Total samples encoded via RLE */
uint64_t full_records; /* Number of full stack records */
uint64_t suffix_records; /* Number of suffix match records */
- uint64_t pop_push_records; /* Number of pop-push records */
+ uint64_t reuse_records; /* Number of stack reuse records */
uint64_t total_frames_written;/* Total frame indices written */
uint64_t frames_saved; /* Frames avoided due to delta encoding */
uint64_t bytes_written; /* Total bytes written (before compression) */
@@ -140,7 +204,7 @@ typedef struct {
uint64_t repeat_samples; /* Samples decoded from RLE */
uint64_t full_records; /* Full stack records decoded */
uint64_t suffix_records; /* Suffix match records decoded */
- uint64_t pop_push_records; /* Pop-push records decoded */
+ uint64_t reuse_records; /* Stack reuse records decoded */
uint64_t total_samples; /* Total samples reconstructed */
uint64_t stack_reconstructions; /* Number of stack array reconstructions */
} BinaryReaderStats;
@@ -199,8 +263,6 @@ typedef struct {
#else
void *cctx; /* Placeholder */
#endif
- uint8_t *compressed_buffer;
- size_t compressed_buffer_size;
} ZstdCompressor;
/* Frame entry - combines all frame data for better cache locality.
@@ -227,31 +289,93 @@ typedef struct {
uint8_t opcode;
} FrameKey;
-/* Thread entry - tracks per-thread state for delta encoding */
+/* One entry per (thread, interpreter) pair seen in the file */
typedef struct {
uint64_t thread_id;
- uint64_t prev_timestamp;
uint32_t interpreter_id;
+ /* Stream index in the current block, or UINT32_MAX */
+ uint32_t block_stream_index;
+} ThreadEntry;
+
+/* Delta encoding state of a stream, reset with each block */
+typedef struct {
+ uint64_t prev_timestamp;
+ size_t thread_index;
+ uint32_t current_repeat;
+
/* Previous stack for delta encoding (frame indices, innermost first) */
- uint32_t *prev_stack;
size_t prev_stack_depth;
- size_t prev_stack_capacity;
+ uint32_t prev_stack[MAX_STACK_DEPTH];
+} BlockStream;
+
+/* Limit errors occur before emitting an incomplete sample. Other write
+ * failures may leave partial records and must prevent finalization. */
+typedef enum {
+ BINARY_WRITER_OPEN,
+ BINARY_WRITER_LIMIT_REACHED,
+ BINARY_WRITER_BROKEN,
+} BinaryWriterState;
+
+/* Byte buffer for block data */
+typedef struct {
+ uint8_t *data;
+ size_t size;
+ size_t capacity;
+} ByteBuffer;
- /* RLE pending buffer - samples waiting to be written as a repeat group */
- uint8_t *pending_rle;
- size_t pending_rle_bytes;
- size_t pending_rle_samples;
-} ThreadEntry;
+/* Column size and encoding */
+typedef struct {
+ uint32_t decoded_size;
+ uint32_t stored_size;
+ uint8_t encoding;
+} ColumnDescriptor;
+
+/* Block header as stored in the file */
+typedef struct {
+ uint32_t sample_count;
+ uint64_t base_timestamp;
+ uint8_t frame_width;
+ uint8_t common_status_flags;
+ uint8_t status_bitmap_flags;
+ ColumnDescriptor columns[COLUMN_COUNT];
+} BlockHeader;
+
+/* Complete stack that later samples can REUSE */
+typedef struct {
+ Py_uhash_t hash;
+ uint32_t offset;
+ uint32_t depth;
+} StackCacheEntry;
+
+/* REPEAT instruction position and count */
+typedef struct {
+ uint32_t offset;
+ uint32_t count;
+} Repeat;
+
+/* Samples buffered until the next flush */
+typedef struct {
+ ByteBuffer columns[COLUMN_COUNT];
+ ByteBuffer repeats;
+ ByteBuffer transformed;
+ ByteBuffer compressed;
+ ByteBuffer output;
+ StackCacheEntry cache[STACK_CACHE_BUCKET_COUNT][STACK_CACHE_BUCKET_SIZE];
+ BlockStream *streams;
+ size_t stream_capacity;
+ uint64_t base_timestamp;
+ uint32_t sample_count;
+ uint32_t stream_count;
+ uint32_t max_frame;
+ size_t size;
+} SampleBlock;
/* Main binary writer structure */
typedef struct {
FILE *fp;
-
- /* Write buffer for batched I/O */
- uint8_t *write_buffer;
- size_t buffer_pos;
- size_t buffer_size;
+ BinaryWriterState state;
+ SampleBlock *block;
/* Compression */
int compression_type;
@@ -261,6 +385,14 @@ typedef struct {
uint64_t start_time_us;
uint64_t sample_interval_us;
uint64_t total_samples;
+ double duration_sec;
+ double sample_rate;
+ double error_rate;
+ double missed_samples;
+ uint32_t profile_stats_present;
+ int has_profile_stats;
+ int profiling_mode;
+ int capture_features;
/* String hash table: PyObject* -> uint32_t index */
_Py_hashtable_t *string_hash;
@@ -290,34 +422,57 @@ typedef struct {
* BINARY READER STRUCTURES
* ============================================================================ */
-/* Per-thread state for stack reconstruction during replay */
+typedef struct {
+ uint32_t frame_index;
+ PyObject *frame_info;
+} ReaderFrameCacheEntry;
+
+/* Decoded sample block */
+typedef struct {
+ BlockHeader header;
+ uint32_t stream_count;
+ uint32_t frame_count;
+ ByteBuffer columns[COLUMN_COUNT];
+ const uint32_t *stream_ids;
+ const uint64_t *timestamps;
+ const uint8_t *statuses;
+ const uint32_t *frames;
+ size_t instruction_offset;
+ uint32_t frame_offset;
+} DecodedBlock;
+
+/* Per-stream replay state */
typedef struct {
uint64_t thread_id;
uint32_t interpreter_id;
uint64_t prev_timestamp;
-
- /* Reconstructed stack buffer (frame indices, innermost first) */
- uint32_t *current_stack;
+ uint32_t current_stack[MAX_STACK_DEPTH];
size_t current_stack_depth;
- size_t current_stack_capacity;
-} ReaderThreadState;
+ uint32_t pending_repeats;
+ int has_stack;
+ PyObject *batch;
+ uint8_t batch_status;
+} ReaderBlockStream;
/* Main binary reader structure */
typedef struct {
#if USE_MMAP
uint8_t *mapped_data;
size_t mapped_size;
+ size_t page_size;
#else
FILE *fp;
- uint8_t *file_data;
size_t file_size;
+ uint8_t *table_data;
+ ByteBuffer sample_window;
+ size_t sample_window_start;
#endif
/* Decompression state */
int compression_type;
- /* Note: ZSTD_DCtx is not stored - created/freed during decompression */
- uint8_t *decompressed_data;
- size_t decompressed_size;
+#ifdef HAVE_ZSTD
+ ZSTD_DCtx *dctx;
+#endif
/* Header metadata */
uint8_t py_major;
@@ -328,8 +483,16 @@ typedef struct {
uint64_t sample_interval_us;
uint64_t sample_count;
uint32_t thread_count;
+ double duration_sec;
+ double sample_rate;
+ double error_rate;
+ double missed_samples;
+ uint32_t profile_stats_present;
+ int has_profile_stats;
uint64_t string_table_offset;
uint64_t frame_table_offset;
+ int profiling_mode;
+ int capture_features;
/* Parsed string table: array of Python string objects */
PyObject **strings;
@@ -338,13 +501,24 @@ typedef struct {
/* Parsed frame table: array of FrameEntry structures */
FrameEntry *frames;
uint32_t frames_count;
+ ReaderFrameCacheEntry *frame_info_cache;
+ size_t frame_info_cache_size;
/* Sample data region */
uint8_t *sample_data;
size_t sample_data_size;
- /* Per-thread state for stack reconstruction (used during replay) */
- ReaderThreadState *thread_states;
+ ByteBuffer block_data;
+ ByteBuffer block_stream_ids;
+ ByteBuffer block_timestamps;
+ ByteBuffer block_statuses;
+ ByteBuffer block_frames;
+ ReaderBlockStream *block_streams;
+ size_t block_stream_capacity;
+ int replaying;
+
+ /* Threads seen during replay */
+ ThreadEntry *thread_states;
size_t thread_state_count;
size_t thread_state_capacity;
@@ -391,6 +565,14 @@ encode_varint_i32(uint8_t *buf, int32_t value)
return encode_varint_u32(buf, zigzag);
}
+/* Encode signed 64-bit varint (zigzag encoding). Returns bytes written. */
+static inline size_t
+encode_varint_i64(uint8_t *buf, int64_t value)
+{
+ uint64_t zigzag = ((uint64_t)value << 1) ^ (uint64_t)(value >> 63);
+ return encode_varint_u64(buf, zigzag);
+}
+
/* Decode unsigned 64-bit varint (LEB128). Updates offset only on success.
* On error (overflow or incomplete), offset is NOT updated, allowing callers
* to detect errors via (offset == prev_offset) check. Sets PyErr on error. */
@@ -454,10 +636,64 @@ decode_varint_i32(const uint8_t *data, size_t *offset, size_t max_size)
return (int32_t)((zigzag >> 1) ^ -(int32_t)(zigzag & 1));
}
+/* Decode signed 64-bit varint (zigzag encoding). */
+static inline int64_t
+decode_varint_i64(const uint8_t *data, size_t *offset, size_t max_size)
+{
+ size_t saved_offset = *offset;
+ uint64_t zigzag = decode_varint_u64(data, offset, max_size);
+ if (*offset == saved_offset) {
+ return 0; /* decode_varint_u64 already set PyErr */
+ }
+ return (int64_t)((zigzag >> 1) ^ (0 - (zigzag & 1)));
+}
+
/* ============================================================================
* SHARED UTILITY FUNCTIONS
* ============================================================================ */
+/* Grow a byte buffer to hold at least size bytes */
+static inline int
+buffer_reserve(ByteBuffer *buffer, size_t size)
+{
+ if (size <= buffer->capacity) {
+ return 0;
+ }
+ size_t capacity = buffer->capacity ? buffer->capacity
+ : INITIAL_BLOCK_CAPACITY;
+ while (capacity < size) {
+ if (capacity > SIZE_MAX / 2) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ capacity *= 2;
+ }
+ uint8_t *data = PyMem_Realloc(buffer->data, capacity);
+ if (data == NULL) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ buffer->data = data;
+ buffer->capacity = capacity;
+ return 0;
+}
+
+static inline void
+buffer_clear(ByteBuffer *buffer)
+{
+ PyMem_Free(buffer->data);
+ buffer->data = NULL;
+ buffer->size = 0;
+ buffer->capacity = 0;
+}
+
+/* Bytes in one status bitmap */
+static inline size_t
+status_bitmap_size(uint32_t sample_count)
+{
+ return ((size_t)sample_count + CHAR_BIT - 1) / CHAR_BIT;
+}
+
/* Generic array growth - returns new pointer or NULL (sets PyErr_NoMemory)
* Includes overflow checking for capacity doubling and allocation size. */
static inline void *
@@ -516,6 +752,8 @@ grow_array_inplace(void **ptr_addr, size_t count, size_t *capacity, size_t elem_
* sample_interval_us: Sampling interval in microseconds
* compression_type: COMPRESSION_NONE or COMPRESSION_ZSTD
* start_time_us: Start timestamp in microseconds (from time.monotonic() * 1e6)
+ * profiling_mode: PROFILING_MODE_* value, or -1 if unknown
+ * capture_features: PROFILING_FEATURE_* bit mask, or -1 if unknown
*
* Returns:
* New BinaryWriter* on success, NULL on failure (PyErr set)
@@ -524,7 +762,9 @@ BinaryWriter *binary_writer_create(
PyObject *path,
uint64_t sample_interval_us,
int compression_type,
- uint64_t start_time_us
+ uint64_t start_time_us,
+ int profiling_mode,
+ int capture_features
);
/*
@@ -556,6 +796,16 @@ int binary_writer_write_sample(
*/
int binary_writer_finalize(BinaryWriter *writer);
+/* Store measured statistics to write during finalization. */
+int binary_writer_set_stats(
+ BinaryWriter *writer,
+ double duration_sec,
+ double sample_rate,
+ double error_rate,
+ double missed_samples,
+ uint32_t present
+);
+
/*
* Destroy a binary writer and free all resources.
* Safe to call even if writer is partially initialized.
@@ -631,6 +881,12 @@ void binary_reader_close(BinaryReader *reader);
*/
PyObject *binary_writer_get_stats(BinaryWriter *writer);
+/*
+ * Decoded bytes of the samples buffered in the current block, not yet
+ * counted in the writer's bytes_written statistic.
+ */
+size_t binary_writer_buffered_size(BinaryWriter *writer);
+
/*
* Get reader statistics as a Python dict.
*
diff --git a/Modules/_remote_debugging/binary_io_reader.c b/Modules/_remote_debugging/binary_io_reader.c
index 07352f94cc805d7..e627feeb53bd49a 100644
--- a/Modules/_remote_debugging/binary_io_reader.c
+++ b/Modules/_remote_debugging/binary_io_reader.c
@@ -12,22 +12,36 @@
#include "binary_io.h"
#include "_remote_debugging.h"
#include "pycore_bitutils.h" /* _Py_bswap32, _Py_bswap64 for cross-endian reading */
+#include
#include
#ifdef HAVE_ZSTD
#include
#endif
+#ifdef _Py_MEMORY_SANITIZER
+# include
+#endif
+
/* ============================================================================
* CONSTANTS FOR BINARY FORMAT SIZES
* ============================================================================ */
-/* File structure sizes */
-#define MIN_DECOMPRESS_BUFFER_SIZE (64 * 1024) /* Minimum decompression buffer */
-
/* Progress callback frequency */
#define PROGRESS_CALLBACK_INTERVAL 1000
+/* Cap per-batch RLE samples to bound the timestamp list (gh-151378) */
+#define MAX_RLE_BATCH_SAMPLES 8192
+
+#define FRAME_INFO_CACHE_SIZE 1024
+
+#if !USE_MMAP
+/* The block parser limits stored columns to MAX_BLOCK_SIZE */
+#define MAX_STORED_BLOCK_SIZE (MAX_BLOCK_SIZE + 1024)
+/* Replay reads samples through a window that fits any block */
+#define SAMPLE_WINDOW_SIZE (2 * MAX_BLOCK_SIZE)
+#endif
+
/* ============================================================================
* BINARY READER IMPLEMENTATION
* ============================================================================ */
@@ -84,7 +98,7 @@ reader_parse_header(BinaryReader *reader, const uint8_t *data, size_t file_size)
/* Read header fields with byte-swapping if needed */
uint64_t start_time_us, sample_interval_us, string_table_offset, frame_table_offset;
uint64_t sample_count;
- uint32_t thread_count, compression_type;
+ uint32_t thread_count, compression_type, profiling_config;
memcpy(&start_time_us, &data[HDR_OFF_START_TIME], HDR_SIZE_START_TIME);
memcpy(&sample_interval_us, &data[HDR_OFF_INTERVAL], HDR_SIZE_INTERVAL);
@@ -93,6 +107,7 @@ reader_parse_header(BinaryReader *reader, const uint8_t *data, size_t file_size)
memcpy(&string_table_offset, &data[HDR_OFF_STR_TABLE], HDR_SIZE_STR_TABLE);
memcpy(&frame_table_offset, &data[HDR_OFF_FRAME_TABLE], HDR_SIZE_FRAME_TABLE);
memcpy(&compression_type, &data[HDR_OFF_COMPRESSION], HDR_SIZE_COMPRESSION);
+ memcpy(&profiling_config, &data[HDR_OFF_CONFIG], HDR_SIZE_CONFIG);
reader->start_time_us = SWAP64_IF(reader->needs_swap, start_time_us);
reader->sample_interval_us = SWAP64_IF(reader->needs_swap, sample_interval_us);
@@ -101,6 +116,20 @@ reader_parse_header(BinaryReader *reader, const uint8_t *data, size_t file_size)
reader->string_table_offset = SWAP64_IF(reader->needs_swap, string_table_offset);
reader->frame_table_offset = SWAP64_IF(reader->needs_swap, frame_table_offset);
reader->compression_type = (int)SWAP32_IF(reader->needs_swap, compression_type);
+ profiling_config = SWAP32_IF(reader->needs_swap, profiling_config);
+ uint32_t profiling_mode =
+ profiling_config & PROFILING_CONFIG_MODE_MASK;
+ if (profiling_mode > PROFILING_MODE_EXCEPTION + 1) {
+ PyErr_Format(PyExc_ValueError,
+ "Invalid profiling mode in header: %u", profiling_mode);
+ return -1;
+ }
+ reader->profiling_mode = (int)profiling_mode - 1;
+ reader->capture_features =
+ profiling_config & PROFILING_CONFIG_FEATURES_KNOWN
+ ? (int)((profiling_config >> PROFILING_CONFIG_FEATURES_SHIFT) &
+ PROFILING_FEATURE_MASK)
+ : -1;
return 0;
}
@@ -125,118 +154,144 @@ reader_parse_footer(BinaryReader *reader, const uint8_t *data, size_t file_size)
return 0;
}
-#ifdef HAVE_ZSTD
-/* Maximum decompression buffer size to prevent memory exhaustion (1GB) */
-#define MAX_DECOMPRESS_SIZE (1ULL << 30)
-
static inline int
-reader_decompress_samples(BinaryReader *reader, const uint8_t *data)
+reader_parse_profile_stats(BinaryReader *reader, const uint8_t *data,
+ size_t file_size)
{
- size_t compressed_size = reader->string_table_offset - FILE_HEADER_PLACEHOLDER_SIZE;
- const uint8_t *compressed_data = data + FILE_HEADER_PLACEHOLDER_SIZE;
+ size_t minimum_size = FILE_FOOTER_SIZE + PROFILE_STATS_V1_SIZE;
+ if (file_size < minimum_size) {
+ return 0;
+ }
+
+ const uint8_t *stats_end = data + file_size - FILE_FOOTER_SIZE;
+ const uint8_t *stats_tail = stats_end - PROFILE_STATS_MAGIC_SIZE -
+ PST_SIZE_VERSION - PST_SIZE_SIZE;
+ if (memcmp(stats_tail,
+ PROFILE_STATS_MAGIC, PROFILE_STATS_MAGIC_SIZE) != 0) {
+ return 0;
+ }
+
+ uint32_t version, size;
+ memcpy(&version, stats_tail + PROFILE_STATS_MAGIC_SIZE,
+ PST_SIZE_VERSION);
+ memcpy(&size, stats_tail + PROFILE_STATS_MAGIC_SIZE + PST_SIZE_VERSION,
+ PST_SIZE_SIZE);
+ version = SWAP32_IF(reader->needs_swap, version);
+ size = SWAP32_IF(reader->needs_swap, size);
+
+ if (size < PROFILE_STATS_V1_SIZE ||
+ size > file_size - FILE_FOOTER_SIZE) {
+ PyErr_SetString(PyExc_ValueError,
+ "Invalid profiling statistics size");
+ return -1;
+ }
+ if (version != PROFILE_STATS_VERSION) {
+ return 0;
+ }
- /* Validate compressed data region */
- if (reader->string_table_offset < FILE_HEADER_PLACEHOLDER_SIZE) {
- PyErr_SetString(PyExc_ValueError, "Invalid string table offset");
+ const uint8_t *trailer = stats_end - size;
+ uint64_t duration_bits, sample_rate_bits;
+ memcpy(&duration_bits, trailer + PST_OFF_DURATION, PST_SIZE_DURATION);
+ memcpy(&sample_rate_bits, trailer + PST_OFF_SAMPLE_RATE,
+ PST_SIZE_SAMPLE_RATE);
+ duration_bits = SWAP64_IF(reader->needs_swap, duration_bits);
+ sample_rate_bits = SWAP64_IF(reader->needs_swap, sample_rate_bits);
+ memcpy(&reader->duration_sec, &duration_bits, sizeof(duration_bits));
+ memcpy(&reader->sample_rate, &sample_rate_bits, sizeof(sample_rate_bits));
+
+ if (!isfinite(reader->duration_sec) || reader->duration_sec < 0.0 ||
+ !isfinite(reader->sample_rate) || reader->sample_rate < 0.0) {
+ PyErr_SetString(PyExc_ValueError,
+ "Invalid profiling statistics values");
return -1;
}
+ reader->has_profile_stats = 1;
+
+ if (size >= PROFILE_STATS_SIZE) {
+ uint64_t error_rate_bits, missed_samples_bits;
+ uint32_t present;
+ memcpy(&error_rate_bits, trailer + PST_OFF_ERROR_RATE,
+ PST_SIZE_ERROR_RATE);
+ memcpy(&missed_samples_bits, trailer + PST_OFF_MISSED_SAMPLES,
+ PST_SIZE_MISSED_SAMPLES);
+ memcpy(&present, trailer + PST_OFF_PRESENT, PST_SIZE_PRESENT);
+ error_rate_bits = SWAP64_IF(reader->needs_swap, error_rate_bits);
+ missed_samples_bits = SWAP64_IF(reader->needs_swap,
+ missed_samples_bits);
+ present = SWAP32_IF(reader->needs_swap, present);
+ memcpy(&reader->error_rate, &error_rate_bits,
+ sizeof(error_rate_bits));
+ memcpy(&reader->missed_samples, &missed_samples_bits,
+ sizeof(missed_samples_bits));
+ if (((present & PROFILE_STATS_ERROR_RATE) &&
+ (!isfinite(reader->error_rate) || reader->error_rate < 0.0)) ||
+ ((present & PROFILE_STATS_MISSED) &&
+ !isfinite(reader->missed_samples))) {
+ PyErr_SetString(PyExc_ValueError,
+ "Invalid profiling statistics values");
+ return -1;
+ }
+ reader->profile_stats_present = present;
+ }
+ return 0;
+}
- ZSTD_DCtx *dctx = ZSTD_createDCtx();
- if (!dctx) {
- PyErr_SetString(PyExc_MemoryError, "Failed to create zstd decompression context");
+static int
+reader_decompress(BinaryReader *reader, const uint8_t *compressed_data,
+ size_t compressed_size, ByteBuffer *output,
+ size_t decoded_size)
+{
+#ifdef HAVE_ZSTD
+ /* The data must be exactly one zstd frame */
+ size_t frame_size = ZSTD_findFrameCompressedSize(compressed_data,
+ compressed_size);
+ if (ZSTD_isError(frame_size) || frame_size != compressed_size) {
+ PyErr_SetString(PyExc_ValueError, "Corrupted zstd frame header");
return -1;
}
- /* Try to get exact decompressed size from frame header for optimal allocation */
+ /* Check the decompressed size recorded in the frame header before
+ * allocating for it */
unsigned long long frame_content_size = ZSTD_getFrameContentSize(compressed_data, compressed_size);
- size_t alloc_size;
-
if (frame_content_size == ZSTD_CONTENTSIZE_ERROR) {
/* Corrupted frame header - fail early */
- ZSTD_freeDCtx(dctx);
PyErr_SetString(PyExc_ValueError, "Corrupted zstd frame header");
return -1;
- } else if (frame_content_size != ZSTD_CONTENTSIZE_UNKNOWN &&
- frame_content_size <= SIZE_MAX &&
- frame_content_size <= MAX_DECOMPRESS_SIZE) {
- alloc_size = (size_t)frame_content_size;
- } else {
- alloc_size = ZSTD_DStreamOutSize() * 4;
- if (alloc_size < MIN_DECOMPRESS_BUFFER_SIZE) {
- alloc_size = MIN_DECOMPRESS_BUFFER_SIZE;
- }
}
-
- reader->decompressed_data = PyMem_Malloc(alloc_size);
- if (!reader->decompressed_data) {
- ZSTD_freeDCtx(dctx);
- PyErr_NoMemory();
+ if (frame_content_size != decoded_size) {
+ PyErr_SetString(PyExc_ValueError,
+ "zstd frame size does not match the decoded size");
return -1;
}
- ZSTD_inBuffer input = { compressed_data, compressed_size, 0 };
- size_t total_output = 0;
- size_t last_result = 0;
-
- while (input.pos < input.size) {
- if (total_output >= alloc_size) {
- /* Check for overflow before doubling */
- if (alloc_size > SIZE_MAX / 2 || alloc_size * 2 > MAX_DECOMPRESS_SIZE) {
- PyMem_Free(reader->decompressed_data);
- reader->decompressed_data = NULL;
- ZSTD_freeDCtx(dctx);
- PyErr_SetString(PyExc_MemoryError, "Decompressed data exceeds maximum size");
- return -1;
- }
- size_t new_size = alloc_size * 2;
- uint8_t *new_buf = PyMem_Realloc(reader->decompressed_data, new_size);
- if (!new_buf) {
- PyMem_Free(reader->decompressed_data);
- reader->decompressed_data = NULL;
- ZSTD_freeDCtx(dctx);
- PyErr_NoMemory();
- return -1;
- }
- reader->decompressed_data = new_buf;
- alloc_size = new_size;
- }
-
- ZSTD_outBuffer output = {
- reader->decompressed_data + total_output,
- alloc_size - total_output,
- 0
- };
-
- last_result = ZSTD_decompressStream(dctx, &output, &input);
- if (ZSTD_isError(last_result)) {
- PyMem_Free(reader->decompressed_data);
- reader->decompressed_data = NULL;
- ZSTD_freeDCtx(dctx);
- PyErr_Format(PyExc_ValueError, "zstd decompression error: %s",
- ZSTD_getErrorName(last_result));
- return -1;
- }
-
- total_output += output.pos;
+ /* Append the decoded data to the output buffer */
+ if (buffer_reserve(output, output->size + decoded_size) < 0) {
+ return -1;
+ }
+ uint8_t *decoded = output->data + output->size;
+ size_t result = ZSTD_decompressDCtx(reader->dctx, decoded, decoded_size,
+ compressed_data, compressed_size);
+ if (ZSTD_isError(result)) {
+ PyErr_Format(PyExc_ValueError, "zstd decompression error: %s",
+ ZSTD_getErrorName(result));
+ return -1;
}
- /* Verify decompression is complete (last_result == 0 means frame is complete) */
- if (last_result != 0) {
- PyMem_Free(reader->decompressed_data);
- reader->decompressed_data = NULL;
- ZSTD_freeDCtx(dctx);
+ /* Verify decompression is complete */
+ if (result != decoded_size) {
PyErr_SetString(PyExc_ValueError, "Incomplete zstd frame: data may be truncated");
return -1;
}
- ZSTD_freeDCtx(dctx);
- reader->decompressed_size = total_output;
- reader->sample_data = reader->decompressed_data;
- reader->sample_data_size = reader->decompressed_size;
-
+ _Py_MSAN_UNPOISON(decoded, decoded_size);
+ output->size += decoded_size;
return 0;
-}
+#else
+ PyErr_SetString(PyExc_RuntimeError,
+ "File uses zstd compression but zstd support not compiled in");
+ return -1;
#endif
+}
/* Reject a table/run count whose entries cannot fit in the bytes still
* available; a malicious file could otherwise drive a huge allocation.
@@ -256,10 +311,10 @@ reader_validate_count(const char *what, uint32_t count,
}
static inline int
-reader_parse_string_table(BinaryReader *reader, const uint8_t *data, size_t file_size)
+reader_parse_string_table(BinaryReader *reader, const uint8_t *data,
+ size_t size, size_t offset)
{
- if (reader_validate_count("string", reader->strings_count,
- file_size - reader->string_table_offset,
+ if (reader_validate_count("string", reader->strings_count, size - offset,
MIN_STRING_ENTRY_SIZE) < 0) {
return -1;
}
@@ -270,15 +325,14 @@ reader_parse_string_table(BinaryReader *reader, const uint8_t *data, size_t file
return -1;
}
- size_t offset = reader->string_table_offset;
for (uint32_t i = 0; i < reader->strings_count; i++) {
size_t prev_offset = offset;
- uint32_t str_len = decode_varint_u32(data, &offset, file_size);
+ uint32_t str_len = decode_varint_u32(data, &offset, size);
if (offset == prev_offset) {
PyErr_SetString(PyExc_ValueError, "Malformed varint in string table");
return -1;
}
- if (offset > file_size || str_len > file_size - offset) {
+ if (offset > size || str_len > size - offset) {
PyErr_SetString(PyExc_ValueError, "String table overflow");
return -1;
}
@@ -294,7 +348,8 @@ reader_parse_string_table(BinaryReader *reader, const uint8_t *data, size_t file
}
static inline int
-reader_parse_frame_table(BinaryReader *reader, const uint8_t *data, size_t file_size)
+reader_parse_frame_table(BinaryReader *reader, const uint8_t *data,
+ size_t size, size_t offset)
{
/* Check for integer overflow in allocation size calculation. */
#if SIZEOF_SIZE_T < 8
@@ -304,8 +359,7 @@ reader_parse_frame_table(BinaryReader *reader, const uint8_t *data, size_t file_
}
#endif
- if (reader_validate_count("frame", reader->frames_count,
- file_size - reader->frame_table_offset,
+ if (reader_validate_count("frame", reader->frames_count, size - offset,
MIN_FRAME_ENTRY_SIZE) < 0) {
return -1;
}
@@ -317,34 +371,33 @@ reader_parse_frame_table(BinaryReader *reader, const uint8_t *data, size_t file_
return -1;
}
- size_t offset = reader->frame_table_offset;
for (uint32_t i = 0; i < reader->frames_count; i++) {
FrameEntry *frame = &reader->frames[i];
size_t prev_offset;
prev_offset = offset;
- frame->filename_idx = decode_varint_u32(data, &offset, file_size);
+ frame->filename_idx = decode_varint_u32(data, &offset, size);
if (offset == prev_offset) {
PyErr_SetString(PyExc_ValueError, "Malformed varint in frame table (filename)");
return -1;
}
prev_offset = offset;
- frame->funcname_idx = decode_varint_u32(data, &offset, file_size);
+ frame->funcname_idx = decode_varint_u32(data, &offset, size);
if (offset == prev_offset) {
PyErr_SetString(PyExc_ValueError, "Malformed varint in frame table (funcname)");
return -1;
}
prev_offset = offset;
- frame->lineno = decode_varint_i32(data, &offset, file_size);
+ frame->lineno = decode_varint_i32(data, &offset, size);
if (offset == prev_offset) {
PyErr_SetString(PyExc_ValueError, "Malformed varint in frame table (lineno)");
return -1;
}
prev_offset = offset;
- int32_t end_lineno_delta = decode_varint_i32(data, &offset, file_size);
+ int32_t end_lineno_delta = decode_varint_i32(data, &offset, size);
if (offset == prev_offset) {
PyErr_SetString(PyExc_ValueError, "Malformed varint in frame table (end_lineno_delta)");
return -1;
@@ -357,14 +410,14 @@ reader_parse_frame_table(BinaryReader *reader, const uint8_t *data, size_t file_
}
prev_offset = offset;
- frame->column = decode_varint_i32(data, &offset, file_size);
+ frame->column = decode_varint_i32(data, &offset, size);
if (offset == prev_offset) {
PyErr_SetString(PyExc_ValueError, "Malformed varint in frame table (column)");
return -1;
}
prev_offset = offset;
- int32_t end_column_delta = decode_varint_i32(data, &offset, file_size);
+ int32_t end_column_delta = decode_varint_i32(data, &offset, size);
if (offset == prev_offset) {
PyErr_SetString(PyExc_ValueError, "Malformed varint in frame table (end_column_delta)");
return -1;
@@ -377,7 +430,7 @@ reader_parse_frame_table(BinaryReader *reader, const uint8_t *data, size_t file_
}
/* Read opcode byte */
- if (offset >= file_size) {
+ if (offset >= size) {
PyErr_SetString(PyExc_ValueError, "Unexpected end of frame table (opcode)");
return -1;
}
@@ -387,6 +440,63 @@ reader_parse_frame_table(BinaryReader *reader, const uint8_t *data, size_t file_
return 0;
}
+#if USE_MMAP && defined(__linux__) && defined(MADV_DONTNEED)
+static size_t
+reader_discard_mapped_pages(BinaryReader *reader, size_t start, size_t end)
+{
+ start = _Py_SIZE_ROUND_UP(start, reader->page_size);
+ end = _Py_SIZE_ROUND_DOWN(end, reader->page_size);
+ if (start >= end) {
+ return start;
+ }
+ (void)madvise(reader->mapped_data + start, end - start, MADV_DONTNEED);
+ return end;
+}
+#else
+static inline size_t
+reader_discard_mapped_pages(BinaryReader *reader, size_t start, size_t end)
+{
+ return end;
+}
+#endif
+
+#if !USE_MMAP
+/* Checked fread with GIL release - returns 0 on success, -1 on error */
+static int
+fread_checked_allow_threads(void *data, size_t size, FILE *fp)
+{
+ size_t nread;
+ Py_BEGIN_ALLOW_THREADS
+ nread = fread(data, 1, size, fp);
+ Py_END_ALLOW_THREADS
+ if (nread != size) {
+ int err = errno;
+ if (ferror(fp) && err != 0) {
+ errno = err;
+ PyErr_SetFromErrno(PyExc_IOError);
+ }
+ else {
+ PyErr_Format(PyExc_ValueError,
+ "Unexpected end of file: read %zu of %zu bytes",
+ nread, size);
+ }
+ return -1;
+ }
+ return 0;
+}
+
+static int
+reader_read_at(BinaryReader *reader, size_t offset, uint8_t *buffer,
+ size_t size)
+{
+ if (FSEEK64(reader->fp, (file_offset_t)offset, SEEK_SET) != 0) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ return -1;
+ }
+ return fread_checked_allow_threads(buffer, size, reader->fp);
+}
+#endif
+
BinaryReader *
binary_reader_open(PyObject *path)
{
@@ -427,32 +537,19 @@ binary_reader_open(PyObject *path)
goto error;
}
- /* Map the file into memory.
- * MAP_POPULATE (Linux-only) pre-faults all pages at mmap time, which:
- * - Catches issues (e.g., file truncation) immediately rather than as SIGBUS during reads
- * - Eliminates page faults during subsequent reads for better performance
- */
-#ifdef __linux__
- reader->mapped_data = mmap(NULL, reader->mapped_size, PROT_READ,
- MAP_PRIVATE | MAP_POPULATE, fd, 0);
-#else
reader->mapped_data = mmap(NULL, reader->mapped_size, PROT_READ,
MAP_PRIVATE, fd, 0);
-#endif
if (reader->mapped_data == MAP_FAILED) {
reader->mapped_data = NULL;
PyErr_SetFromErrno(PyExc_IOError);
Py_fclose(fp);
goto error;
}
+ reader->page_size = (size_t)sysconf(_SC_PAGESIZE);
/* Hint sequential access pattern - failures are non-fatal */
(void)madvise(reader->mapped_data, reader->mapped_size, MADV_SEQUENTIAL);
- /* Pre-fetch pages into memory - failures are non-fatal.
- * Complements MAP_POPULATE on Linux, provides benefit on macOS. */
- (void)madvise(reader->mapped_data, reader->mapped_size, MADV_WILLNEED);
-
/* Use transparent huge pages for large files to reduce TLB misses.
* Only beneficial for files >= 32MB where TLB pressure matters. */
#ifdef MADV_HUGEPAGE
@@ -464,9 +561,6 @@ binary_reader_open(PyObject *path)
/* Add file descriptor-level hints for better kernel I/O scheduling */
#if defined(__linux__) && defined(POSIX_FADV_SEQUENTIAL)
(void)posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL);
- if (reader->mapped_size > (64 * 1024 * 1024)) {
- (void)posix_fadvise(fd, 0, 0, POSIX_FADV_WILLNEED);
- }
#endif
if (Py_fclose(fp) != 0) {
@@ -477,7 +571,8 @@ binary_reader_open(PyObject *path)
uint8_t *data = reader->mapped_data;
size_t file_size = reader->mapped_size;
#else
- /* Use stdio on Windows */
+ /* Use stdio on Windows. Read the header and tables now, samples during
+ * replay. */
reader->fp = Py_fopen(path, "rb");
if (!reader->fp) {
goto error;
@@ -501,43 +596,17 @@ binary_reader_open(PyObject *path)
PyErr_SetString(PyExc_ValueError, "File too small for header");
goto error;
}
- if (FSEEK64(reader->fp, 0, SEEK_SET) != 0) {
- PyErr_SetFromErrno(PyExc_IOError);
- goto error;
- }
-
- reader->file_data = PyMem_Malloc(reader->file_size);
- if (!reader->file_data) {
- PyErr_NoMemory();
- goto error;
- }
-
- size_t nread = fread(reader->file_data, 1, reader->file_size, reader->fp);
- if (nread != reader->file_size) {
- int err = errno;
- if (ferror(reader->fp) && err != 0) {
- errno = err;
- PyErr_SetFromErrno(PyExc_IOError);
- }
- else {
- PyErr_Format(PyExc_ValueError,
- "Unexpected end of file: read %zu of %zu bytes",
- nread, reader->file_size);
- }
+ uint8_t data[FILE_HEADER_PLACEHOLDER_SIZE];
+ size_t file_size = reader->file_size;
+ if (reader_read_at(reader, 0, data,
+ Py_MIN(file_size, sizeof(data))) < 0) {
goto error;
}
-
- uint8_t *data = reader->file_data;
- size_t file_size = reader->file_size;
#endif
- /* Parse header and footer */
if (reader_parse_header(reader, data, file_size) < 0) {
goto error;
}
- if (reader_parse_footer(reader, data, file_size) < 0) {
- goto error;
- }
/* Validate table offsets are within file bounds */
if (reader->string_table_offset > file_size) {
@@ -572,10 +641,11 @@ binary_reader_open(PyObject *path)
goto error;
}
- /* Handle compressed data */
if (reader->compression_type == COMPRESSION_ZSTD) {
#ifdef HAVE_ZSTD
- if (reader_decompress_samples(reader, data) < 0) {
+ reader->dctx = ZSTD_createDCtx();
+ if (!reader->dctx) {
+ PyErr_SetString(PyExc_MemoryError, "Failed to create zstd decompression context");
goto error;
}
#else
@@ -583,18 +653,46 @@ binary_reader_open(PyObject *path)
"File uses zstd compression but zstd support not compiled in");
goto error;
#endif
- } else {
- reader->sample_data = data + FILE_HEADER_PLACEHOLDER_SIZE;
- reader->sample_data_size = reader->string_table_offset - FILE_HEADER_PLACEHOLDER_SIZE;
}
+ reader->sample_data_size =
+ (size_t)reader->string_table_offset - FILE_HEADER_PLACEHOLDER_SIZE;
- /* Parse string and frame tables */
- if (reader_parse_string_table(reader, data, file_size) < 0) {
+ /* Tables, statistics and footer follow the samples. The footer is
+ * always the last bytes of the file. */
+ size_t tail_offset = Py_MIN((size_t)reader->string_table_offset,
+ file_size - FILE_FOOTER_SIZE);
+ size_t tail_size = file_size - tail_offset;
+#if USE_MMAP
+ reader->sample_data = data + FILE_HEADER_PLACEHOLDER_SIZE;
+ const uint8_t *tail = data + tail_offset;
+#else
+ reader->table_data = PyMem_Malloc(tail_size);
+ if (!reader->table_data) {
+ PyErr_NoMemory();
+ goto error;
+ }
+ if (reader_read_at(reader, tail_offset, reader->table_data,
+ tail_size) < 0) {
goto error;
}
- if (reader_parse_frame_table(reader, data, file_size) < 0) {
+ const uint8_t *tail = reader->table_data;
+#endif
+ if (reader_parse_footer(reader, tail, tail_size) < 0 ||
+ reader_parse_profile_stats(reader, tail, tail_size) < 0 ||
+ reader_parse_string_table(
+ reader, tail, tail_size,
+ (size_t)reader->string_table_offset - tail_offset) < 0 ||
+ reader_parse_frame_table(
+ reader, tail, tail_size,
+ (size_t)reader->frame_table_offset - tail_offset) < 0) {
goto error;
}
+#if USE_MMAP
+ (void)reader_discard_mapped_pages(reader, tail_offset, file_size);
+#else
+ PyMem_Free(reader->table_data);
+ reader->table_data = NULL;
+#endif
return reader;
@@ -604,7 +702,7 @@ binary_reader_open(PyObject *path)
}
/* Get or create reader thread state for stack reconstruction */
-static ReaderThreadState *
+static ThreadEntry *
reader_get_or_create_thread_state(BinaryReader *reader, uint64_t thread_id,
uint32_t interpreter_id)
{
@@ -626,192 +724,104 @@ reader_get_or_create_thread_state(BinaryReader *reader, uint64_t thread_id,
if (!reader->thread_states) {
reader->thread_state_capacity = 16;
- reader->thread_states = PyMem_Calloc(reader->thread_state_capacity, sizeof(ReaderThreadState));
+ reader->thread_states = PyMem_Calloc(reader->thread_state_capacity, sizeof(ThreadEntry));
if (!reader->thread_states) {
PyErr_NoMemory();
return NULL;
}
- } else if (reader->thread_state_count >= reader->thread_state_capacity) {
- ReaderThreadState *new_states = grow_array(reader->thread_states,
- &reader->thread_state_capacity,
- sizeof(ReaderThreadState));
- if (!new_states) {
- return NULL;
- }
- reader->thread_states = new_states;
+ }
+ else if (GROW_ARRAY(reader->thread_states, reader->thread_state_count,
+ reader->thread_state_capacity, ThreadEntry) < 0) {
+ return NULL;
}
- ReaderThreadState *ts = &reader->thread_states[reader->thread_state_count];
- memset(ts, 0, sizeof(ReaderThreadState));
+ ThreadEntry *ts = &reader->thread_states[reader->thread_state_count];
+ memset(ts, 0, sizeof(ThreadEntry));
ts->thread_id = thread_id;
ts->interpreter_id = interpreter_id;
- ts->prev_timestamp = reader->start_time_us;
- ts->current_stack_capacity = MAX_STACK_DEPTH;
- ts->current_stack = PyMem_Malloc(ts->current_stack_capacity * sizeof(uint32_t));
- if (!ts->current_stack) {
- PyErr_NoMemory();
- return NULL;
- }
- // Increment count only after successful allocation to avoid
- // leaving a half-initialized entry visible to future lookups
reader->thread_state_count++;
return ts;
}
-/* ============================================================================
- * STACK DECODING HELPERS
- * ============================================================================ */
-
-/* Validate that final_depth fits in the stack buffer.
- * Uses uint64_t to prevent overflow on 32-bit platforms. */
-static inline int
-validate_stack_depth(ReaderThreadState *ts, uint64_t final_depth)
-{
- if (final_depth > ts->current_stack_capacity) {
- PyErr_Format(PyExc_ValueError,
- "Final stack depth %llu exceeds capacity %zu",
- (unsigned long long)final_depth, ts->current_stack_capacity);
- return -1;
- }
- return 0;
-}
-
-/* Decode a full stack from sample data.
- * Updates ts->current_stack and ts->current_stack_depth.
- * Returns 0 on success, -1 on error (bounds violation). */
-static inline int
-decode_stack_full(ReaderThreadState *ts, const uint8_t *data,
- size_t *offset, size_t max_size)
+static PyObject *
+reader_get_frame_info(RemoteDebuggingState *state, BinaryReader *reader,
+ uint32_t frame_index)
{
- size_t prev_offset = *offset;
- uint32_t depth = decode_varint_u32(data, offset, max_size);
- if (*offset == prev_offset) {
- return -1;
- }
-
- /* Validate depth against capacity to prevent buffer overflow */
- if (depth > ts->current_stack_capacity) {
- PyErr_Format(PyExc_ValueError,
- "Stack depth %u exceeds capacity %zu", depth, ts->current_stack_capacity);
- return -1;
+ if (frame_index >= reader->frames_count) {
+ PyErr_Format(PyExc_ValueError, "Invalid frame index: %u", frame_index);
+ return NULL;
}
-
- ts->current_stack_depth = depth;
- for (uint32_t i = 0; i < depth; i++) {
- size_t prev_offset = *offset;
- ts->current_stack[i] = decode_varint_u32(data, offset, max_size);
- if (*offset == prev_offset) {
- return -1;
+ if (reader->frame_info_cache == NULL) {
+ size_t cache_size = Py_MIN(reader->frames_count,
+ (uint32_t)FRAME_INFO_CACHE_SIZE);
+ reader->frame_info_cache = PyMem_Calloc(
+ cache_size, sizeof(*reader->frame_info_cache));
+ if (reader->frame_info_cache == NULL) {
+ PyErr_NoMemory();
+ return NULL;
}
+ reader->frame_info_cache_size = cache_size;
}
- return 0;
-}
-
-/* Decode a suffix-encoded stack from sample data.
- * The suffix encoding shares frames from the bottom of the previous stack.
- * Returns 0 on success, -1 on error (bounds violation). */
-static inline int
-decode_stack_suffix(ReaderThreadState *ts, const uint8_t *data,
- size_t *offset, size_t max_size)
-{
- size_t prev_offset = *offset;
- uint32_t shared = decode_varint_u32(data, offset, max_size);
- if (*offset == prev_offset) {
- return -1;
- }
- prev_offset = *offset;
- uint32_t new_count = decode_varint_u32(data, offset, max_size);
- if (*offset == prev_offset) {
- return -1;
- }
-
- /* Validate shared doesn't exceed current stack depth */
- if (shared > ts->current_stack_depth) {
- PyErr_Format(PyExc_ValueError,
- "Shared count %u exceeds current stack depth %zu",
- shared, ts->current_stack_depth);
- return -1;
+ ReaderFrameCacheEntry *entry = &reader->frame_info_cache[
+ frame_index % reader->frame_info_cache_size];
+ if (entry->frame_info != NULL && entry->frame_index == frame_index) {
+ return Py_NewRef(entry->frame_info);
}
- /* Use uint64_t to prevent overflow on 32-bit platforms */
- uint64_t final_depth = (uint64_t)shared + new_count;
- if (validate_stack_depth(ts, final_depth) < 0) {
- return -1;
+ FrameEntry *frame = &reader->frames[frame_index];
+ if (frame->filename_idx >= reader->strings_count ||
+ frame->funcname_idx >= reader->strings_count) {
+ PyErr_SetString(PyExc_ValueError, "Invalid string index in frame");
+ return NULL;
}
- /* Move shared frames (from bottom of stack) to make room for new frames at the top */
- if (new_count > 0 && shared > 0) {
- /* Defensive check: ensure subtraction won't underflow.
- * This should already be guaranteed by the check above, but we add
- * this assertion as defense-in-depth against stack corruption. */
- if (ts->current_stack_depth < shared) {
- PyErr_SetString(PyExc_ValueError,
- "Internal error: stack corruption detected in suffix decoding");
- return -1;
- }
- size_t prev_shared_start = ts->current_stack_depth - shared;
- memmove(&ts->current_stack[new_count],
- &ts->current_stack[prev_shared_start],
- shared * sizeof(uint32_t));
+ PyObject *frame_info = PyStructSequence_New(state->FrameInfo_Type);
+ if (!frame_info) {
+ return NULL;
}
- for (uint32_t i = 0; i < new_count; i++) {
- size_t prev_offset = *offset;
- ts->current_stack[i] = decode_varint_u32(data, offset, max_size);
- if (*offset == prev_offset) {
- return -1;
+ /* Build location tuple with full position info */
+ PyObject *location;
+ if (frame->lineno != LOCATION_NOT_AVAILABLE) {
+ location = Py_BuildValue("(iiii)",
+ frame->lineno,
+ frame->end_lineno,
+ frame->column,
+ frame->end_column);
+ if (!location) {
+ Py_DECREF(frame_info);
+ return NULL;
}
}
- ts->current_stack_depth = final_depth;
- return 0;
-}
-
-/* Decode a pop-push encoded stack from sample data.
- * Pops frames from the top and pushes new frames.
- * Returns 0 on success, -1 on error (bounds violation). */
-static inline int
-decode_stack_pop_push(ReaderThreadState *ts, const uint8_t *data,
- size_t *offset, size_t max_size)
-{
- size_t prev_offset = *offset;
- uint32_t pop = decode_varint_u32(data, offset, max_size);
- if (*offset == prev_offset) {
- return -1;
- }
- prev_offset = *offset;
- uint32_t push = decode_varint_u32(data, offset, max_size);
- if (*offset == prev_offset) {
- return -1;
+ else {
+ location = Py_NewRef(Py_None);
}
- size_t keep = (ts->current_stack_depth > pop) ? ts->current_stack_depth - pop : 0;
- /* Use uint64_t to prevent overflow on 32-bit platforms */
- uint64_t final_depth = (uint64_t)keep + push;
- if (validate_stack_depth(ts, final_depth) < 0) {
- return -1;
+ /* Build opcode object */
+ PyObject *opcode_obj;
+ if (frame->opcode != OPCODE_NONE) {
+ opcode_obj = PyLong_FromLong(frame->opcode);
+ if (!opcode_obj) {
+ Py_DECREF(location);
+ Py_DECREF(frame_info);
+ return NULL;
+ }
}
-
- /* Move kept frames (from bottom of stack) to make room for new frames at the top.
- * Even when push == 0, we need to move kept frames to index 0 if pop > 0. */
- if (keep > 0) {
- memmove(&ts->current_stack[push],
- &ts->current_stack[pop],
- keep * sizeof(uint32_t));
+ else {
+ opcode_obj = Py_NewRef(Py_None);
}
- for (uint32_t i = 0; i < push; i++) {
- size_t prev_offset = *offset;
- ts->current_stack[i] = decode_varint_u32(data, offset, max_size);
- /* If offset didn't advance, varint decoding failed */
- if (*offset == prev_offset) {
- return -1;
- }
- }
- ts->current_stack_depth = final_depth;
- return 0;
+ PyStructSequence_SetItem(frame_info, 0, Py_NewRef(reader->strings[frame->filename_idx]));
+ PyStructSequence_SetItem(frame_info, 1, location);
+ PyStructSequence_SetItem(frame_info, 2, Py_NewRef(reader->strings[frame->funcname_idx]));
+ PyStructSequence_SetItem(frame_info, 3, opcode_obj);
+ Py_XSETREF(entry->frame_info, Py_NewRef(frame_info));
+ entry->frame_index = frame_index;
+ return frame_info;
}
-/* Build a Python list of FrameInfo objects from frame indices */
+/* Build a Python list of FrameInfo objects from frame indices. Stacks are
+ * kept outermost first, but collectors expect innermost first. */
static PyObject *
build_frame_list(RemoteDebuggingState *state, BinaryReader *reader,
const uint32_t *frame_indices, size_t stack_depth)
@@ -822,60 +832,11 @@ build_frame_list(RemoteDebuggingState *state, BinaryReader *reader,
}
for (size_t k = 0; k < stack_depth; k++) {
- uint32_t frame_idx = frame_indices[k];
- if (frame_idx >= reader->frames_count) {
- PyErr_Format(PyExc_ValueError, "Invalid frame index: %u", frame_idx);
- goto error;
- }
-
- FrameEntry *frame = &reader->frames[frame_idx];
-
- if (frame->filename_idx >= reader->strings_count ||
- frame->funcname_idx >= reader->strings_count) {
- PyErr_SetString(PyExc_ValueError, "Invalid string index in frame");
- goto error;
- }
-
- PyObject *frame_info = PyStructSequence_New(state->FrameInfo_Type);
- if (!frame_info) {
+ PyObject *frame_info = reader_get_frame_info(
+ state, reader, frame_indices[stack_depth - 1 - k]);
+ if (frame_info == NULL) {
goto error;
}
-
- /* Build location tuple with full position info */
- PyObject *location;
- if (frame->lineno != LOCATION_NOT_AVAILABLE) {
- location = Py_BuildValue("(iiii)",
- frame->lineno,
- frame->end_lineno,
- frame->column,
- frame->end_column);
- if (!location) {
- Py_DECREF(frame_info);
- goto error;
- }
- }
- else {
- location = Py_NewRef(Py_None);
- }
-
- /* Build opcode object */
- PyObject *opcode_obj;
- if (frame->opcode != OPCODE_NONE) {
- opcode_obj = PyLong_FromLong(frame->opcode);
- if (!opcode_obj) {
- Py_DECREF(location);
- Py_DECREF(frame_info);
- goto error;
- }
- }
- else {
- opcode_obj = Py_NewRef(Py_None);
- }
-
- PyStructSequence_SetItem(frame_info, 0, Py_NewRef(reader->strings[frame->filename_idx]));
- PyStructSequence_SetItem(frame_info, 1, location);
- PyStructSequence_SetItem(frame_info, 2, Py_NewRef(reader->strings[frame->funcname_idx]));
- PyStructSequence_SetItem(frame_info, 3, opcode_obj);
PyList_SET_ITEM(frame_list, k, frame_info);
}
@@ -977,21 +938,6 @@ emit_sample(RemoteDebuggingState *state, PyObject *collector,
return 0;
}
-/* Helper to trim timestamp list and emit batch. Returns 0 on success, -1 on error. */
-static int
-emit_batch(RemoteDebuggingState *state, PyObject *collector,
- uint64_t thread_id, uint32_t interpreter_id, uint8_t status,
- const uint32_t *frame_indices, size_t stack_depth,
- BinaryReader *reader, PyObject *timestamps_list, Py_ssize_t actual_size)
-{
- /* Trim list to actual size */
- if (PyList_SetSlice(timestamps_list, actual_size, PyList_GET_SIZE(timestamps_list), NULL) < 0) {
- return -1;
- }
- return emit_sample(state, collector, thread_id, interpreter_id, status,
- frame_indices, stack_depth, reader, timestamps_list);
-}
-
/* Helper to invoke progress callback, returns -1 on error */
static inline int
invoke_progress_callback(PyObject *callback, Py_ssize_t current, uint64_t total)
@@ -1007,244 +953,820 @@ invoke_progress_callback(PyObject *callback, Py_ssize_t current, uint64_t total)
return 0;
}
-Py_ssize_t
-binary_reader_replay(BinaryReader *reader, PyObject *collector, PyObject *progress_callback)
+/* ============================================================================
+ * SAMPLE BLOCKS
+ * ============================================================================ */
+
+static int
+block_error(const char *message)
{
- PyObject *collect_method;
- int has_collect = PyObject_GetOptionalAttrString(collector, "collect", &collect_method);
- if (has_collect < 0) {
- return -1;
+ PyErr_Format(PyExc_ValueError, "Invalid sample block: %s", message);
+ return -1;
+}
+
+static inline int
+block_read_varint(const ByteBuffer *column, size_t *offset, uint64_t *value)
+{
+ size_t prev_offset = *offset;
+ *value = decode_varint_u64(column->data, offset, column->size);
+ return *offset == prev_offset ? -1 : 0;
+}
+
+static int
+block_read_varint_u32(const ByteBuffer *column, size_t *offset,
+ uint32_t *value)
+{
+ size_t prev_offset = *offset;
+ *value = decode_varint_u32(column->data, offset, column->size);
+ return *offset == prev_offset ? -1 : 0;
+}
+
+static int
+reader_parse_block_header(BinaryReader *reader, const ByteBuffer *section,
+ size_t *offset, BlockHeader *header)
+{
+ /* Block magic "TBLK" */
+ if (section->size - *offset < BLOCK_MAGIC_SIZE) {
+ return block_error("truncated header");
}
- if (has_collect == 0) {
- PyErr_SetString(PyExc_TypeError, "Collector must have a collect() method");
- return -1;
+ if (memcmp(section->data + *offset, BLOCK_MAGIC, BLOCK_MAGIC_SIZE) != 0) {
+ return block_error("wrong magic");
}
- Py_DECREF(collect_method);
+ *offset += BLOCK_MAGIC_SIZE;
- /* Get module state for struct sequence types */
- PyObject *module = PyImport_ImportModule("_remote_debugging");
- if (!module) {
+ /* Sample count and base timestamp (varints) */
+ if (block_read_varint_u32(section, offset, &header->sample_count) < 0 ||
+ block_read_varint(section, offset, &header->base_timestamp) < 0) {
return -1;
}
- RemoteDebuggingState *state = RemoteDebugging_GetState(module);
- Py_DECREF(module);
- if (!state) {
- PyErr_SetString(PyExc_RuntimeError, "Failed to get module state");
- return -1;
+ /* Frame ID width and the two status flag masks (1 byte each) */
+ if (section->size - *offset < 3) {
+ return block_error("truncated header");
}
-
- size_t offset = 0;
- Py_ssize_t replayed = 0;
-
- /* Initial progress callback at 0% */
- if (invoke_progress_callback(progress_callback, 0, reader->sample_count) < 0) {
- return -1;
+ header->frame_width = section->data[(*offset)++];
+ header->common_status_flags = section->data[(*offset)++];
+ header->status_bitmap_flags = section->data[(*offset)++];
+ if (header->sample_count == 0) {
+ return block_error("no samples");
+ }
+ if (header->frame_width < 1 || header->frame_width > sizeof(uint32_t)) {
+ return block_error("frame ID width out of range");
+ }
+ if (header->common_status_flags & header->status_bitmap_flags) {
+ return block_error("common and varying status flags overlap");
}
- while (offset < reader->sample_data_size) {
- /* Read thread_id (8 bytes) + interpreter_id (4 bytes) + encoding byte */
- if (reader->sample_data_size - offset < SAMPLE_HEADER_FIXED_SIZE) {
- PyErr_Format(PyExc_ValueError,
- "Truncated sample data: %zu trailing bytes",
- reader->sample_data_size - offset);
+ size_t decoded_total = 0;
+ size_t stored_total = 0;
+ for (unsigned column = 0; column < COLUMN_COUNT; column++) {
+ ColumnDescriptor *descriptor = &header->columns[column];
+ /* Decoded size (varint) and encoding (1 byte) */
+ if (block_read_varint_u32(section, offset,
+ &descriptor->decoded_size) < 0) {
return -1;
}
+ if (*offset >= section->size) {
+ return block_error("truncated column descriptor");
+ }
+ descriptor->encoding = section->data[(*offset)++];
- /* Use memcpy to avoid strict aliasing violations, then byte-swap if needed */
- uint64_t thread_id_raw;
- uint32_t interpreter_id_raw;
- memcpy(&thread_id_raw, &reader->sample_data[offset], SMP_SIZE_THREAD_ID);
- offset += SMP_SIZE_THREAD_ID;
-
- memcpy(&interpreter_id_raw, &reader->sample_data[offset], SMP_SIZE_INTERPRETER_ID);
- offset += SMP_SIZE_INTERPRETER_ID;
+ /* Stored size: implied for raw and constant, a varint for zstd */
+ switch (descriptor->encoding) {
+ case COMPRESSION_NONE:
+ descriptor->stored_size = descriptor->decoded_size;
+ break;
+ case COLUMN_CONSTANT:
+ descriptor->stored_size = 1;
+ break;
+ case COMPRESSION_ZSTD:
+ if (reader->compression_type != COMPRESSION_ZSTD) {
+ return block_error("zstd column in an uncompressed file");
+ }
+ if (block_read_varint_u32(section, offset,
+ &descriptor->stored_size) < 0) {
+ return -1;
+ }
+ break;
+ default:
+ return block_error("unknown column encoding");
+ }
- uint64_t thread_id = SWAP64_IF(reader->needs_swap, thread_id_raw);
- uint32_t interpreter_id = SWAP32_IF(reader->needs_swap, interpreter_id_raw);
+ if (descriptor->encoding != COMPRESSION_NONE &&
+ descriptor->decoded_size == 0) {
+ return block_error("encoded column is empty");
+ }
+ if (descriptor->decoded_size > MAX_BLOCK_SIZE - decoded_total) {
+ return block_error("decoded columns exceed the block limit");
+ }
+ if (descriptor->stored_size > MAX_BLOCK_SIZE - stored_total) {
+ return block_error("stored columns exceed the block limit");
+ }
+ decoded_total += descriptor->decoded_size;
+ stored_total += descriptor->stored_size;
+ }
- /* Get or create thread state for reconstruction */
- ReaderThreadState *ts = reader_get_or_create_thread_state(reader, thread_id, interpreter_id);
- if (!ts) {
- return -1;
+ /* Each sample needs at least one byte of stream index and residual */
+ if (header->sample_count >
+ header->columns[COLUMN_SAMPLE_STREAM_IDS].decoded_size ||
+ header->sample_count >
+ header->columns[COLUMN_TIMESTAMP_RESIDUALS].decoded_size) {
+ return block_error("more samples than stored stream indices");
+ }
+ return 0;
+}
+
+/* A constant stream index or residual column that holds the same one-byte
+ * varint for every sample is read from its stored byte, not expanded. */
+static int
+constant_varint_column(const DecodedBlock *block, unsigned column,
+ uint8_t value)
+{
+ const ColumnDescriptor *descriptor = &block->header.columns[column];
+ return (column == COLUMN_SAMPLE_STREAM_IDS ||
+ column == COLUMN_TIMESTAMP_RESIDUALS) &&
+ descriptor->encoding == COLUMN_CONSTANT &&
+ descriptor->decoded_size == block->header.sample_count &&
+ value < 0x80;
+}
+
+static int
+decode_block_columns(BinaryReader *reader, const ByteBuffer *section,
+ size_t *offset, DecodedBlock *block)
+{
+ const ColumnDescriptor *descriptors = block->header.columns;
+ /* Find where each column is stored and how much of the shared buffer
+ * the expanded and decompressed columns need. The buffer is reused
+ * across blocks and reserved up front so decoded columns never move. */
+ uint8_t *stored[COLUMN_COUNT];
+ size_t buffered_total = 0;
+ for (unsigned column = 0; column < COLUMN_COUNT; column++) {
+ const ColumnDescriptor *descriptor = &descriptors[column];
+ if (descriptor->stored_size > section->size - *offset) {
+ return block_error("column extends past the sample section");
+ }
+ stored[column] = section->data + *offset;
+ *offset += descriptor->stored_size;
+ if (descriptor->encoding == COMPRESSION_ZSTD ||
+ (descriptor->encoding == COLUMN_CONSTANT &&
+ !constant_varint_column(block, column, stored[column][0]))) {
+ buffered_total += descriptor->decoded_size;
}
+ }
+ ByteBuffer *buffer = &reader->block_data;
+ if (buffer_reserve(buffer, buffered_total) < 0) {
+ return -1;
+ }
- /* Read encoding byte */
- uint8_t encoding = reader->sample_data[offset++];
-
- switch (encoding) {
- case STACK_REPEAT: {
- /* RLE repeat: [count: varint] [delta: varint, status: 1]... */
- size_t prev_offset = offset;
- uint32_t count = decode_varint_u32(reader->sample_data, &offset, reader->sample_data_size);
- /* Detect varint decode failure */
- if (offset == prev_offset) {
- PyErr_SetString(PyExc_ValueError, "Malformed varint for RLE count");
- return -1;
+ buffer->size = 0;
+ for (unsigned column = 0; column < COLUMN_COUNT; column++) {
+ const ColumnDescriptor *descriptor = &descriptors[column];
+ uint8_t *stored_data = stored[column];
+ ByteBuffer *decoded = &block->columns[column];
+ decoded->size = descriptor->decoded_size;
+ switch (descriptor->encoding) {
+ case COMPRESSION_NONE:
+ /* Raw columns point into the file data */
+ decoded->data = stored_data;
+ break;
+ case COLUMN_CONSTANT:
+ if (constant_varint_column(block, column, stored_data[0])) {
+ decoded->data = stored_data;
+ decoded->size = 1;
+ break;
}
-
- /* Reject a count larger than the remaining bytes can hold; each
- * RLE sample needs at least 2 bytes (1-byte min varint + status). */
- if (reader_validate_count("RLE", count,
- reader->sample_data_size - offset, 2) < 0) {
+ decoded->data = buffer->data + buffer->size;
+ memset(decoded->data, stored_data[0], decoded->size);
+ buffer->size += decoded->size;
+ break;
+ case COMPRESSION_ZSTD:
+ decoded->data = buffer->data + buffer->size;
+ if (reader_decompress(reader, stored_data,
+ descriptor->stored_size, buffer,
+ decoded->size) < 0) {
return -1;
}
- if ((uint64_t)count > (uint64_t)PY_SSIZE_T_MAX - (uint64_t)replayed) {
- PyErr_SetString(PyExc_OverflowError,
- "Sample count exceeds Py_ssize_t maximum");
+ break;
+ default:
+ return block_error("unknown column encoding");
+ }
+ }
+ return 0;
+}
+
+static int
+validate_block_columns(DecodedBlock *block)
+{
+ size_t stream_table_size = block->columns[COLUMN_STREAM_TABLE].size;
+ if (stream_table_size % STREAM_ENTRY_SIZE != 0) {
+ return block_error("stream table has a partial entry");
+ }
+ size_t stream_count = stream_table_size / STREAM_ENTRY_SIZE;
+ if (stream_count == 0 || stream_count > MAX_BLOCK_STREAMS) {
+ return block_error("stream count out of range");
+ }
+ block->stream_count = (uint32_t)stream_count;
+
+ size_t frame_ids_size = block->columns[COLUMN_FRAME_IDS].size;
+ if (frame_ids_size % block->header.frame_width != 0) {
+ return block_error("frame ID column has a partial value");
+ }
+ block->frame_count =
+ (uint32_t)(frame_ids_size / block->header.frame_width);
+
+ size_t plane_size = status_bitmap_size(block->header.sample_count);
+ size_t plane_count =
+ (size_t)_Py_popcount32(block->header.status_bitmap_flags);
+ const ByteBuffer *statuses = &block->columns[COLUMN_STATUS_BITMAPS];
+ if (statuses->size != plane_size * plane_count) {
+ return block_error("status bitmaps have the wrong size");
+ }
+ unsigned used_bits = block->header.sample_count % CHAR_BIT;
+ for (size_t plane = 0; used_bits && plane < plane_count; plane++) {
+ if (statuses->data[(plane + 1) * plane_size - 1] >> used_bits) {
+ return block_error("status bitmap padding is not zero");
+ }
+ }
+ return 0;
+}
+
+static int
+reserve_block_streams(BinaryReader *reader, uint32_t stream_count)
+{
+ if (stream_count <= reader->block_stream_capacity) {
+ return 0;
+ }
+ ReaderBlockStream *streams = PyMem_Realloc(
+ reader->block_streams, stream_count * sizeof(ReaderBlockStream));
+ if (streams == NULL) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ reader->block_streams = streams;
+ reader->block_stream_capacity = stream_count;
+ return 0;
+}
+
+static int
+reader_parse_stream_table(BinaryReader *reader, const DecodedBlock *block)
+{
+ const uint8_t *stream_table = block->columns[COLUMN_STREAM_TABLE].data;
+ uint64_t initial_prev_timestamp =
+ block->header.base_timestamp - reader->sample_interval_us;
+ memset(reader->block_streams, 0,
+ block->stream_count * sizeof(ReaderBlockStream));
+ for (uint32_t i = 0; i < block->stream_count; i++) {
+ /* Read thread_id (8 bytes) + interpreter_id (4 bytes) */
+ const uint8_t *entry = stream_table + (size_t)i * STREAM_ENTRY_SIZE;
+ uint64_t thread_id;
+ uint32_t interpreter_id;
+ memcpy(&thread_id, entry + STM_OFF_THREAD_ID, STM_SIZE_THREAD_ID);
+ memcpy(&interpreter_id, entry + STM_OFF_INTERPRETER_ID,
+ STM_SIZE_INTERPRETER_ID);
+ ThreadEntry *thread = reader_get_or_create_thread_state(
+ reader, SWAP64_IF(reader->needs_swap, thread_id),
+ SWAP32_IF(reader->needs_swap, interpreter_id));
+ if (thread == NULL) {
+ return -1;
+ }
+ /* Each thread may appear only once in a block. An index left over
+ * from an earlier block points at a different thread here. */
+ uint32_t previous_index = thread->block_stream_index;
+ if (previous_index < i &&
+ reader->block_streams[previous_index].thread_id ==
+ thread->thread_id &&
+ reader->block_streams[previous_index].interpreter_id ==
+ thread->interpreter_id) {
+ return block_error("stream table repeats a thread");
+ }
+ thread->block_stream_index = i;
+
+ /* Each stream's first expected timestamp is the base timestamp */
+ ReaderBlockStream *stream = &reader->block_streams[i];
+ stream->thread_id = thread->thread_id;
+ stream->interpreter_id = thread->interpreter_id;
+ stream->prev_timestamp = initial_prev_timestamp;
+ }
+ return 0;
+}
+
+static int
+decode_samples(BinaryReader *reader, DecodedBlock *block)
+{
+ size_t sample_count = block->header.sample_count;
+ if (buffer_reserve(&reader->block_stream_ids,
+ sample_count * sizeof(uint32_t)) < 0 ||
+ buffer_reserve(&reader->block_timestamps,
+ sample_count * sizeof(uint64_t)) < 0) {
+ return -1;
+ }
+ uint32_t *stream_ids = (uint32_t *)reader->block_stream_ids.data;
+ uint64_t *timestamps = (uint64_t *)reader->block_timestamps.data;
+ const ByteBuffer *stream_id_column =
+ &block->columns[COLUMN_SAMPLE_STREAM_IDS];
+ const ByteBuffer *residual_column =
+ &block->columns[COLUMN_TIMESTAMP_RESIDUALS];
+ int constant_stream_ids = constant_varint_column(
+ block, COLUMN_SAMPLE_STREAM_IDS, stream_id_column->data[0]);
+ int constant_residuals = constant_varint_column(
+ block, COLUMN_TIMESTAMP_RESIDUALS, residual_column->data[0]);
+ size_t stream_id_offset = 0;
+ size_t residual_offset = 0;
+ int64_t constant_residual = 0;
+ if (constant_residuals) {
+ constant_residual = decode_varint_i64(residual_column->data,
+ &residual_offset, 1);
+ }
+ for (uint32_t sample = 0; sample < block->header.sample_count; sample++) {
+ uint64_t stream_id;
+ if (constant_stream_ids) {
+ stream_id = stream_id_column->data[0];
+ }
+ else if (block_read_varint(stream_id_column, &stream_id_offset,
+ &stream_id) < 0) {
+ return -1;
+ }
+ if (stream_id >= block->stream_count) {
+ return block_error("sample refers to an unknown stream");
+ }
+ int64_t residual = constant_residual;
+ if (!constant_residuals) {
+ size_t prev_offset = residual_offset;
+ residual = decode_varint_i64(residual_column->data,
+ &residual_offset,
+ residual_column->size);
+ if (residual_offset == prev_offset) {
return -1;
}
+ }
- reader->stats.repeat_records++;
- reader->stats.repeat_samples += count;
-
- /* Process RLE samples, batching by status */
- PyObject *timestamps_list = NULL;
- uint8_t batch_status = 0;
- Py_ssize_t batch_idx = 0;
-
- for (uint32_t i = 0; i < count; i++) {
- size_t delta_prev_offset = offset;
- uint64_t delta = decode_varint_u64(reader->sample_data, &offset, reader->sample_data_size);
- if (offset == delta_prev_offset) {
- Py_XDECREF(timestamps_list);
- PyErr_SetString(PyExc_ValueError, "Malformed varint in RLE sample data");
- return -1;
- }
- if (offset >= reader->sample_data_size) {
- Py_XDECREF(timestamps_list);
- PyErr_SetString(PyExc_ValueError, "Unexpected end of sample data in RLE");
- return -1;
- }
- uint8_t status = reader->sample_data[offset++];
- ts->prev_timestamp += delta;
-
- /* Start new batch on first sample or status change */
- if (i == 0 || status != batch_status) {
- if (timestamps_list) {
- int rc = emit_batch(state, collector, thread_id, interpreter_id,
- batch_status, ts->current_stack, ts->current_stack_depth,
- reader, timestamps_list, batch_idx);
- Py_DECREF(timestamps_list);
- if (rc < 0) {
- return -1;
- }
- }
- timestamps_list = PyList_New(count - i);
- if (!timestamps_list) {
- return -1;
- }
- batch_status = status;
- batch_idx = 0;
- }
-
- PyObject *ts_obj = PyLong_FromUnsignedLongLong(ts->prev_timestamp);
- if (!ts_obj) {
- Py_DECREF(timestamps_list);
- return -1;
- }
- PyList_SET_ITEM(timestamps_list, batch_idx++, ts_obj);
- }
+ /* Timestamp is the expected time plus the stored residual */
+ ReaderBlockStream *stream = &reader->block_streams[stream_id];
+ stream->prev_timestamp +=
+ reader->sample_interval_us + (uint64_t)residual;
- /* Emit final batch */
- if (timestamps_list) {
- int rc = emit_batch(state, collector, thread_id, interpreter_id,
- batch_status, ts->current_stack, ts->current_stack_depth,
- reader, timestamps_list, batch_idx);
- Py_DECREF(timestamps_list);
- if (rc < 0) {
- return -1;
- }
- }
+ stream_ids[sample] = (uint32_t)stream_id;
+ timestamps[sample] = stream->prev_timestamp;
+ }
+ if (!constant_stream_ids && stream_id_offset != stream_id_column->size) {
+ return block_error("stream index column has trailing data");
+ }
+ if (residual_offset != residual_column->size) {
+ return block_error("timestamp column has trailing data");
+ }
+ block->stream_ids = stream_ids;
+ block->timestamps = timestamps;
+ return 0;
+}
- replayed += count;
- reader->stats.total_samples += count;
+static int
+decode_statuses(BinaryReader *reader, DecodedBlock *block)
+{
+ if (buffer_reserve(&reader->block_statuses,
+ block->header.sample_count) < 0) {
+ return -1;
+ }
+ /* Start from the common flags, then add each varying flag's bitmap */
+ uint8_t *statuses = reader->block_statuses.data;
+ memset(statuses, block->header.common_status_flags,
+ block->header.sample_count);
+ const uint8_t *plane = block->columns[COLUMN_STATUS_BITMAPS].data;
+ size_t plane_size = status_bitmap_size(block->header.sample_count);
+ for (unsigned bit = 0; bit < CHAR_BIT; bit++) {
+ if (!(block->header.status_bitmap_flags & (1U << bit))) {
+ continue;
+ }
+ for (uint32_t i = 0; i < block->header.sample_count; i++) {
+ statuses[i] |= ((plane[i / CHAR_BIT] >> (i % CHAR_BIT)) & 1U)
+ << bit;
+ }
+ plane += plane_size;
+ }
+ block->statuses = statuses;
+ return 0;
+}
- /* Progress callback after batch */
- if (replayed % PROGRESS_CALLBACK_INTERVAL < count) {
- if (invoke_progress_callback(progress_callback, replayed, reader->sample_count) < 0) {
- return -1;
- }
- }
- break;
+static int
+decode_frame_ids(BinaryReader *reader, DecodedBlock *block)
+{
+ size_t frame_count = block->frame_count;
+ size_t frames_size = frame_count * sizeof(uint32_t);
+ if (buffer_reserve(&reader->block_frames, frames_size) < 0) {
+ return -1;
+ }
+ uint32_t *frames = (uint32_t *)reader->block_frames.data;
+ block->frames = frames;
+ if (frame_count == 0) {
+ return 0;
+ }
+
+ /* Combine byte b of every frame index from plane b, low byte first */
+ memset(frames, 0, frames_size);
+ const uint8_t *plane = block->columns[COLUMN_FRAME_IDS].data;
+ for (unsigned byte = 0; byte < block->header.frame_width; byte++) {
+ for (size_t i = 0; i < frame_count; i++) {
+ frames[i] |= (uint32_t)plane[i] << (byte * CHAR_BIT);
+ }
+ plane += frame_count;
+ }
+ for (size_t i = 0; i < frame_count; i++) {
+ if (frames[i] >= reader->frames_count) {
+ return block_error("frame index out of range");
}
+ }
+ return 0;
+}
- case STACK_FULL:
- case STACK_SUFFIX:
- case STACK_POP_PUSH: {
- /* All three encodings share: [delta: varint] [status: 1] ... */
- size_t prev_offset = offset;
- uint64_t delta = decode_varint_u64(reader->sample_data, &offset, reader->sample_data_size);
- /* Detect varint decode failure: offset unchanged means error */
- if (offset == prev_offset) {
- PyErr_SetString(PyExc_ValueError, "Malformed varint in sample data");
- return -1;
- }
- if (offset >= reader->sample_data_size) {
- PyErr_SetString(PyExc_ValueError, "Unexpected end of sample data");
- return -1;
- }
- uint8_t status = reader->sample_data[offset++];
- ts->prev_timestamp += delta;
-
- if (encoding == STACK_FULL) {
- if (decode_stack_full(ts, reader->sample_data, &offset, reader->sample_data_size) < 0) {
- return -1;
- }
- reader->stats.full_records++;
- } else if (encoding == STACK_SUFFIX) {
- if (decode_stack_suffix(ts, reader->sample_data, &offset, reader->sample_data_size) < 0) {
- return -1;
- }
- reader->stats.suffix_records++;
- } else { /* STACK_POP_PUSH */
- if (decode_stack_pop_push(ts, reader->sample_data, &offset, reader->sample_data_size) < 0) {
- return -1;
- }
- reader->stats.pop_push_records++;
- }
- reader->stats.stack_reconstructions++;
+static int
+decode_block(BinaryReader *reader, const ByteBuffer *section,
+ size_t *offset, DecodedBlock *block)
+{
+ block->instruction_offset = 0;
+ block->frame_offset = 0;
+ if (reader_parse_block_header(reader, section, offset,
+ &block->header) < 0 ||
+ decode_block_columns(reader, section, offset, block) < 0 ||
+ validate_block_columns(block) < 0 ||
+ reserve_block_streams(reader, block->stream_count) < 0 ||
+ reader_parse_stream_table(reader, block) < 0 ||
+ decode_samples(reader, block) < 0 ||
+ decode_statuses(reader, block) < 0 ||
+ decode_frame_ids(reader, block) < 0) {
+ return -1;
+ }
+ return 0;
+}
- /* Build single-element timestamp list */
- PyObject *ts_obj = PyLong_FromUnsignedLongLong(ts->prev_timestamp);
- if (!ts_obj) {
- return -1;
- }
- PyObject *timestamps_list = PyList_New(1);
- if (!timestamps_list) {
- Py_DECREF(ts_obj);
- return -1;
- }
- PyList_SET_ITEM(timestamps_list, 0, ts_obj);
+static int
+flush_stream_batch(BinaryReader *reader, RemoteDebuggingState *state,
+ PyObject *collector, ReaderBlockStream *stream)
+{
+ if (stream->batch == NULL) {
+ return 0;
+ }
+ int result = emit_sample(state, collector, stream->thread_id,
+ stream->interpreter_id, stream->batch_status,
+ stream->current_stack,
+ stream->current_stack_depth, reader,
+ stream->batch);
+ Py_CLEAR(stream->batch);
+ return result;
+}
- if (emit_sample(state, collector, thread_id, interpreter_id, status,
- ts->current_stack, ts->current_stack_depth, reader,
- timestamps_list) < 0) {
- Py_DECREF(timestamps_list);
- return -1;
- }
- Py_DECREF(timestamps_list);
- if (replayed == PY_SSIZE_T_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "Sample count exceeds Py_ssize_t maximum");
- return -1;
- }
- replayed++;
- reader->stats.total_samples++;
+static int
+decode_stack_repeat(BinaryReader *reader, DecodedBlock *block,
+ ReaderBlockStream *stream)
+{
+ const ByteBuffer *instructions =
+ &block->columns[COLUMN_STACK_INSTRUCTIONS];
+ size_t *offset = &block->instruction_offset;
+ uint64_t count;
+ if (block_read_varint(instructions, offset, &count) < 0) {
+ return -1;
+ }
+ if (!stream->has_stack) {
+ return block_error("first stack of a stream cannot repeat");
+ }
+ if (count == 0 || count > block->header.sample_count) {
+ return block_error("repeat count out of range");
+ }
+ stream->pending_repeats = (uint32_t)(count - 1);
+ reader->stats.repeat_records++;
+ reader->stats.repeat_samples++;
+ return 0;
+}
+
+static int
+decode_stack_replace_suffix(BinaryReader *reader, DecodedBlock *block,
+ ReaderBlockStream *stream)
+{
+ const ByteBuffer *instructions =
+ &block->columns[COLUMN_STACK_INSTRUCTIONS];
+ size_t *offset = &block->instruction_offset;
+ uint64_t keep, count;
+ if (block_read_varint(instructions, offset, &keep) < 0 ||
+ block_read_varint(instructions, offset, &count) < 0) {
+ return -1;
+ }
+ if (keep > stream->current_stack_depth || count > MAX_STACK_DEPTH - keep) {
+ return block_error("stack prefix out of range");
+ }
+ if (count > block->frame_count - block->frame_offset) {
+ return block_error("stack uses more frame IDs than stored");
+ }
+ if (count > 0) {
+ memcpy(&stream->current_stack[keep],
+ &block->frames[block->frame_offset], count * sizeof(uint32_t));
+ }
+ block->frame_offset += (uint32_t)count;
+ stream->current_stack_depth = (size_t)(keep + count);
+ if (keep == 0) {
+ reader->stats.full_records++;
+ }
+ else {
+ reader->stats.suffix_records++;
+ }
+ return 0;
+}
+
+static int
+decode_stack_reuse(BinaryReader *reader, DecodedBlock *block,
+ ReaderBlockStream *stream)
+{
+ const ByteBuffer *instructions =
+ &block->columns[COLUMN_STACK_INSTRUCTIONS];
+ size_t *offset = &block->instruction_offset;
+ uint64_t start, count;
+ if (block_read_varint(instructions, offset, &start) < 0 ||
+ block_read_varint(instructions, offset, &count) < 0) {
+ return -1;
+ }
+ if (count > MAX_STACK_DEPTH) {
+ return block_error("stack is too deep");
+ }
+ if (start > block->frame_offset || count > block->frame_offset - start) {
+ return block_error("reused stack is not stored earlier");
+ }
+ if (count > 0) {
+ memcpy(stream->current_stack, &block->frames[start],
+ count * sizeof(uint32_t));
+ }
+ stream->current_stack_depth = (size_t)count;
+ reader->stats.reuse_records++;
+ return 0;
+}
+
+/* Return 1 if a new stack was decoded, 0 if the stack repeats, -1 on error. */
+static int
+decode_stack(BinaryReader *reader, RemoteDebuggingState *state,
+ PyObject *collector, DecodedBlock *block,
+ ReaderBlockStream *stream)
+{
+ /* An earlier REPEAT still covers this sample */
+ if (stream->pending_repeats > 0) {
+ stream->pending_repeats--;
+ reader->stats.repeat_samples++;
+ return 0;
+ }
+ uint64_t encoding;
+ if (block_read_varint(&block->columns[COLUMN_STACK_INSTRUCTIONS],
+ &block->instruction_offset, &encoding) < 0) {
+ return -1;
+ }
+ if (encoding == STACK_REPEAT) {
+ return decode_stack_repeat(reader, block, stream);
+ }
+
+ /* The pending batch was collected with the stack being replaced. */
+ if (flush_stream_batch(reader, state, collector, stream) < 0) {
+ return -1;
+ }
+ int result;
+ switch (encoding) {
+ case STACK_REPLACE_SUFFIX:
+ result = decode_stack_replace_suffix(reader, block, stream);
+ break;
+ case STACK_REUSE:
+ result = decode_stack_reuse(reader, block, stream);
+ break;
+ default:
+ return block_error("unknown stack instruction");
+ }
+ if (result < 0) {
+ return -1;
+ }
+ stream->has_stack = 1;
+ reader->stats.stack_reconstructions++;
+ return 1;
+}
+
+static int
+replay_sample(BinaryReader *reader, RemoteDebuggingState *state,
+ PyObject *collector, DecodedBlock *block, uint32_t sample)
+{
+ ReaderBlockStream *stream =
+ &reader->block_streams[block->stream_ids[sample]];
+ uint8_t status = block->statuses[sample];
+ int new_stack = decode_stack(reader, state, collector, block, stream);
+ if (new_stack < 0) {
+ return -1;
+ }
+
+ /* Start a new batch when the status changes or the batch is full */
+ if (stream->batch == NULL || status != stream->batch_status ||
+ PyList_GET_SIZE(stream->batch) >= MAX_RLE_BATCH_SAMPLES) {
+ if (flush_stream_batch(reader, state, collector, stream) < 0) {
+ return -1;
+ }
+ stream->batch = PyList_New(0);
+ if (stream->batch == NULL) {
+ return -1;
+ }
+ stream->batch_status = status;
+ }
+ PyObject *timestamp =
+ PyLong_FromUnsignedLongLong(block->timestamps[sample]);
+ if (timestamp == NULL) {
+ return -1;
+ }
+ int result = PyList_Append(stream->batch, timestamp);
+ Py_DECREF(timestamp);
+ if (result < 0) {
+ return -1;
+ }
+ /* Send a new stack's sample immediately so a stream's first sample is
+ * not held back behind samples from other streams. */
+ if (new_stack) {
+ return flush_stream_batch(reader, state, collector, stream);
+ }
+ return 0;
+}
+
+static int
+validate_block_consumed(BinaryReader *reader, const DecodedBlock *block)
+{
+ if (block->instruction_offset !=
+ block->columns[COLUMN_STACK_INSTRUCTIONS].size) {
+ return block_error("stack instruction column has trailing data");
+ }
+ if (block->frame_offset != block->frame_count) {
+ return block_error("frame ID column has unused values");
+ }
+ for (uint32_t i = 0; i < block->stream_count; i++) {
+ if (!reader->block_streams[i].has_stack) {
+ return block_error("stream table has an unused entry");
+ }
+ if (reader->block_streams[i].pending_repeats != 0) {
+ return block_error("repeat count extends past the block");
+ }
+ }
+ return 0;
+}
+
+static int
+replay_block(BinaryReader *reader, RemoteDebuggingState *state,
+ PyObject *collector, PyObject *progress_callback,
+ DecodedBlock *block, Py_ssize_t *replayed)
+{
+ if ((uint64_t)block->header.sample_count >
+ reader->sample_count - (uint64_t)*replayed) {
+ return block_error("more samples than the file header declares");
+ }
+ int result = 0;
+ for (uint32_t sample = 0; sample < block->header.sample_count; sample++) {
+ if (replay_sample(reader, state, collector, block, sample) < 0) {
+ result = -1;
break;
}
+ (*replayed)++;
+ reader->stats.total_samples++;
+ if (*replayed % PROGRESS_CALLBACK_INTERVAL == 0 &&
+ invoke_progress_callback(progress_callback, *replayed,
+ reader->sample_count) < 0) {
+ result = -1;
+ break;
+ }
+ }
+ if (result == 0) {
+ result = validate_block_consumed(reader, block);
+ }
- default:
- PyErr_Format(PyExc_ValueError, "Unknown stack encoding: %u", encoding);
+ /* Send the remaining batches, or drop them after an error. */
+ for (uint32_t i = 0; i < block->stream_count; i++) {
+ ReaderBlockStream *stream = &reader->block_streams[i];
+ if (result == 0 &&
+ flush_stream_batch(reader, state, collector, stream) < 0) {
+ result = -1;
+ }
+ Py_CLEAR(stream->batch);
+ }
+
+ return result;
+}
+
+/* Set section and offset to the block at sample offset pos */
+#if USE_MMAP
+static int
+reader_load_samples(BinaryReader *reader, size_t pos, ByteBuffer *section,
+ size_t *offset)
+{
+ *section = (ByteBuffer){reader->sample_data, reader->sample_data_size, 0};
+ *offset = pos;
+ return 0;
+}
+#else
+static int
+reader_load_samples(BinaryReader *reader, size_t pos, ByteBuffer *section,
+ size_t *offset)
+{
+ ByteBuffer *window = &reader->sample_window;
+ if (pos == 0) {
+ /* A new replay starts at the first block */
+ if (buffer_reserve(window, Py_MIN(SAMPLE_WINDOW_SIZE,
+ reader->sample_data_size)) < 0) {
return -1;
}
+ if (FSEEK64(reader->fp, FILE_HEADER_PLACEHOLDER_SIZE, SEEK_SET) != 0) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ return -1;
+ }
+ window->size = 0;
+ reader->sample_window_start = 0;
+ }
+
+ size_t start = reader->sample_window_start;
+ size_t end = start + window->size;
+ size_t needed = Py_MIN(MAX_STORED_BLOCK_SIZE,
+ reader->sample_data_size - pos);
+ if (end - pos < needed) {
+ /* Keep the unread bytes and refill the rest */
+ size_t kept = end - pos;
+ memmove(window->data, window->data + (pos - start), kept);
+ size_t size = Py_MIN(SAMPLE_WINDOW_SIZE - kept,
+ reader->sample_data_size - end);
+ if (fread_checked_allow_threads(window->data + kept, size,
+ reader->fp) < 0) {
+ return -1;
+ }
+ reader->sample_window_start = pos;
+ window->size = kept + size;
+ }
+ *section = (ByteBuffer){window->data, window->size, 0};
+ *offset = pos - reader->sample_window_start;
+ return 0;
+}
+#endif
- /* Progress callback */
- if (replayed % PROGRESS_CALLBACK_INTERVAL == 0) {
- if (invoke_progress_callback(progress_callback, replayed, reader->sample_count) < 0) {
- return -1;
- }
+static int
+replay_blocks(BinaryReader *reader, RemoteDebuggingState *state,
+ PyObject *collector, PyObject *progress_callback,
+ Py_ssize_t *replayed)
+{
+ size_t pos = 0;
+ size_t discarded = 0;
+ while (pos < reader->sample_data_size) {
+ ByteBuffer section;
+ size_t offset;
+ if (reader_load_samples(reader, pos, §ion, &offset) < 0) {
+ return -1;
}
+ size_t block_start = offset;
+ DecodedBlock block;
+ if (decode_block(reader, §ion, &offset, &block) < 0 ||
+ replay_block(reader, state, collector, progress_callback,
+ &block, replayed) < 0) {
+ return -1;
+ }
+ pos += offset - block_start;
+ discarded = reader_discard_mapped_pages(
+ reader, discarded, FILE_HEADER_PLACEHOLDER_SIZE + pos);
+ }
+ return 0;
+}
+
+static Py_ssize_t
+replay_all_samples(BinaryReader *reader, PyObject *collector,
+ PyObject *progress_callback)
+{
+ PyObject *collect_method;
+ int has_collect = PyObject_GetOptionalAttrString(collector, "collect", &collect_method);
+ if (has_collect < 0) {
+ return -1;
+ }
+ if (has_collect == 0) {
+ PyErr_SetString(PyExc_TypeError, "Collector must have a collect() method");
+ return -1;
+ }
+ Py_DECREF(collect_method);
+
+ /* Get module state for struct sequence types */
+ PyObject *module = PyImport_ImportModule("_remote_debugging");
+ if (!module) {
+ return -1;
+ }
+ RemoteDebuggingState *state = RemoteDebugging_GetState(module);
+ Py_DECREF(module);
+
+ if (!state) {
+ PyErr_SetString(PyExc_RuntimeError, "Failed to get module state");
+ return -1;
+ }
+ if (reader->sample_count > (uint64_t)PY_SSIZE_T_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "Sample count exceeds Py_ssize_t maximum");
+ return -1;
+ }
+
+ /* Initial progress callback at 0% */
+ if (invoke_progress_callback(progress_callback, 0, reader->sample_count) < 0) {
+ return -1;
+ }
+
+ memset(&reader->stats, 0, sizeof(reader->stats));
+ Py_ssize_t replayed = 0;
+ if (replay_blocks(reader, state, collector, progress_callback,
+ &replayed) < 0) {
+ return -1;
}
if ((uint64_t)replayed != reader->sample_count) {
@@ -1253,8 +1775,25 @@ binary_reader_replay(BinaryReader *reader, PyObject *collector, PyObject *progre
(unsigned long long)reader->sample_count, replayed);
return -1;
}
+ return replayed;
+}
- /* Final progress callback at 100% */
+Py_ssize_t
+binary_reader_replay(BinaryReader *reader, PyObject *collector, PyObject *progress_callback)
+{
+ if (reader->replaying) {
+ PyErr_SetString(PyExc_RuntimeError, "Reader is already replaying");
+ return -1;
+ }
+ reader->replaying = 1;
+ Py_ssize_t replayed = replay_all_samples(reader, collector,
+ progress_callback);
+ reader->replaying = 0;
+ if (replayed < 0) {
+ return -1;
+ }
+
+ /* Final progress callback at 100%; it may close the reader */
if (invoke_progress_callback(progress_callback, replayed, reader->sample_count) < 0) {
return -1;
}
@@ -1270,8 +1809,63 @@ binary_reader_get_info(BinaryReader *reader)
if (py_version == NULL) {
return NULL;
}
+ PyObject *duration = reader->has_profile_stats
+ ? PyFloat_FromDouble(reader->duration_sec) : Py_NewRef(Py_None);
+ if (duration == NULL) {
+ Py_DECREF(py_version);
+ return NULL;
+ }
+ PyObject *sample_rate = reader->has_profile_stats
+ ? PyFloat_FromDouble(reader->sample_rate) : Py_NewRef(Py_None);
+ if (sample_rate == NULL) {
+ Py_DECREF(py_version);
+ Py_DECREF(duration);
+ return NULL;
+ }
+ PyObject *error_rate =
+ reader->profile_stats_present & PROFILE_STATS_ERROR_RATE
+ ? PyFloat_FromDouble(reader->error_rate) : Py_NewRef(Py_None);
+ if (error_rate == NULL) {
+ Py_DECREF(py_version);
+ Py_DECREF(duration);
+ Py_DECREF(sample_rate);
+ return NULL;
+ }
+ PyObject *missed_samples =
+ reader->profile_stats_present & PROFILE_STATS_MISSED
+ ? PyFloat_FromDouble(reader->missed_samples) : Py_NewRef(Py_None);
+ if (missed_samples == NULL) {
+ Py_DECREF(py_version);
+ Py_DECREF(duration);
+ Py_DECREF(sample_rate);
+ Py_DECREF(error_rate);
+ return NULL;
+ }
+ PyObject *profiling_mode = reader->profiling_mode < 0
+ ? Py_NewRef(Py_None)
+ : PyLong_FromLong(reader->profiling_mode);
+ if (profiling_mode == NULL) {
+ Py_DECREF(py_version);
+ Py_DECREF(duration);
+ Py_DECREF(sample_rate);
+ Py_DECREF(error_rate);
+ Py_DECREF(missed_samples);
+ return NULL;
+ }
+ PyObject *capture_features = reader->capture_features < 0
+ ? Py_NewRef(Py_None)
+ : PyLong_FromLong(reader->capture_features);
+ if (capture_features == NULL) {
+ Py_DECREF(py_version);
+ Py_DECREF(profiling_mode);
+ Py_DECREF(duration);
+ Py_DECREF(sample_rate);
+ Py_DECREF(error_rate);
+ Py_DECREF(missed_samples);
+ return NULL;
+ }
return Py_BuildValue(
- "{s:I, s:N, s:K, s:K, s:K, s:I, s:I, s:I, s:i}",
+ "{s:I, s:N, s:K, s:K, s:K, s:I, s:I, s:I, s:i, s:N, s:N, s:N, s:N, s:N, s:N}",
"version", BINARY_FORMAT_VERSION,
"python_version", py_version,
"start_time_us", reader->start_time_us,
@@ -1280,7 +1874,13 @@ binary_reader_get_info(BinaryReader *reader)
"thread_count", reader->thread_count,
"string_count", reader->strings_count,
"frame_count", reader->frames_count,
- "compression_type", reader->compression_type
+ "compression_type", reader->compression_type,
+ "duration_sec", duration,
+ "sample_rate", sample_rate,
+ "error_rate", error_rate,
+ "missed_samples", missed_samples,
+ "mode", profiling_mode,
+ "capture_features", capture_features
);
}
@@ -1291,8 +1891,9 @@ binary_writer_get_stats(BinaryWriter *writer)
/* Calculate derived stats */
uint64_t total_records = s->repeat_records + s->full_records +
- s->suffix_records + s->pop_push_records;
+ s->suffix_records + s->reuse_records;
uint64_t total_samples = writer->total_samples;
+ uint64_t bytes_written = s->bytes_written + binary_writer_buffered_size(writer);
uint64_t potential_frames = s->total_frames_written + s->frames_saved;
double compression_ratio = (potential_frames > 0) ?
(double)s->frames_saved / potential_frames * 100.0 : 0.0;
@@ -1303,12 +1904,12 @@ binary_writer_get_stats(BinaryWriter *writer)
"repeat_samples", s->repeat_samples,
"full_records", s->full_records,
"suffix_records", s->suffix_records,
- "pop_push_records", s->pop_push_records,
+ "reuse_records", s->reuse_records,
"total_records", total_records,
"total_samples", total_samples,
"total_frames_written", s->total_frames_written,
"frames_saved", s->frames_saved,
- "bytes_written", s->bytes_written,
+ "bytes_written", bytes_written,
"frame_compression_pct", compression_ratio
);
}
@@ -1319,7 +1920,7 @@ binary_reader_get_stats(BinaryReader *reader)
BinaryReaderStats *s = &reader->stats;
uint64_t total_records = s->repeat_records + s->full_records +
- s->suffix_records + s->pop_push_records;
+ s->suffix_records + s->reuse_records;
return Py_BuildValue(
"{s:K, s:K, s:K, s:K, s:K, s:K, s:K, s:K}",
@@ -1327,7 +1928,7 @@ binary_reader_get_stats(BinaryReader *reader)
"repeat_samples", s->repeat_samples,
"full_records", s->full_records,
"suffix_records", s->suffix_records,
- "pop_push_records", s->pop_push_records,
+ "reuse_records", s->reuse_records,
"total_records", total_records,
"total_samples", s->total_samples,
"stack_reconstructions", s->stack_reconstructions
@@ -1355,14 +1956,28 @@ binary_reader_close(BinaryReader *reader)
Py_fclose(reader->fp);
reader->fp = NULL;
}
- if (reader->file_data) {
- PyMem_Free(reader->file_data);
- reader->file_data = NULL;
- reader->file_size = 0;
- }
+ PyMem_Free(reader->table_data);
+ reader->table_data = NULL;
+ buffer_clear(&reader->sample_window);
+ reader->file_size = 0;
#endif
- PyMem_Free(reader->decompressed_data);
+#ifdef HAVE_ZSTD
+ ZSTD_freeDCtx(reader->dctx);
+#endif
+ buffer_clear(&reader->block_data);
+ buffer_clear(&reader->block_stream_ids);
+ buffer_clear(&reader->block_timestamps);
+ buffer_clear(&reader->block_statuses);
+ buffer_clear(&reader->block_frames);
+ PyMem_Free(reader->block_streams);
+
+ if (reader->frame_info_cache != NULL) {
+ for (size_t i = 0; i < reader->frame_info_cache_size; i++) {
+ Py_XDECREF(reader->frame_info_cache[i].frame_info);
+ }
+ PyMem_Free(reader->frame_info_cache);
+ }
if (reader->strings) {
for (uint32_t i = 0; i < reader->strings_count; i++) {
@@ -1373,12 +1988,7 @@ binary_reader_close(BinaryReader *reader)
PyMem_Free(reader->frames);
- if (reader->thread_states) {
- for (size_t i = 0; i < reader->thread_state_count; i++) {
- PyMem_Free(reader->thread_states[i].current_stack);
- }
- PyMem_Free(reader->thread_states);
- }
+ PyMem_Free(reader->thread_states);
PyMem_Free(reader);
}
diff --git a/Modules/_remote_debugging/binary_io_writer.c b/Modules/_remote_debugging/binary_io_writer.c
index e2ac40d96b39bee..50bbbedd5d5355d 100644
--- a/Modules/_remote_debugging/binary_io_writer.c
+++ b/Modules/_remote_debugging/binary_io_writer.c
@@ -2,7 +2,7 @@
* Python Remote Debugging Module - Binary Writer Implementation
*
* High-performance binary file writer for profiling data with optional zstd
- * streaming compression.
+ * compression.
******************************************************************************/
#ifndef Py_BUILD_CORE_MODULE
@@ -11,27 +11,86 @@
#include "binary_io.h"
#include "_remote_debugging.h"
+#include "pycore_bitutils.h" // _Py_bit_length(), _Py_popcount32()
#include "pycore_opcode_utils.h" // MAX_REAL_OPCODE
+#include
#include
#ifdef HAVE_ZSTD
#include
#endif
+#ifdef _Py_MEMORY_SANITIZER
+# include
+#endif
+
/* ============================================================================
* CONSTANTS FOR BINARY FORMAT SIZES
* ============================================================================ */
-/* Sample header sizes */
-#define SAMPLE_HEADER_MAX_SIZE 26 /* fixed + max_varint(10) + status(1) + margin */
#define MAX_VARINT_SIZE 10 /* Maximum bytes for a varint64 */
#define MAX_VARINT_SIZE_U32 5 /* Maximum bytes for a varint32 */
-/* Frame buffer: depth varint (max 2 bytes for 256) + 256 frames * 5 bytes/varint + margin */
-#define MAX_FRAME_BUFFER_SIZE ((MAX_STACK_DEPTH * MAX_VARINT_SIZE_U32) + MAX_VARINT_SIZE_U32 + 16)
-/* RLE pending buffer (per thread): one entry is a u64 delta varint + status byte */
-#define MAX_RLE_BUF_SIZE (16 * 1024)
-#define MAX_RLE_ENTRY_SIZE (MAX_VARINT_SIZE + sizeof(uint8_t))
+#define MAX_BLOCK_HEADER_SIZE \
+ (BLOCK_MAGIC_SIZE + MAX_VARINT_SIZE_U32 + MAX_VARINT_SIZE + \
+ 3 * sizeof(uint8_t) + \
+ COLUMN_COUNT * (2 * MAX_VARINT_SIZE_U32 + sizeof(uint8_t)))
+
+#define ZSTD_MIN_SIZE 32
+#define STACK_REUSE_MIN_FRAMES 3
+
+#define MAX_SAMPLE_SIZE \
+ (STREAM_ENTRY_SIZE + 5 * MAX_VARINT_SIZE + sizeof(uint8_t) + \
+ MAX_STACK_DEPTH * sizeof(uint32_t) + sizeof(Repeat))
+#define MAX_BITMAP_PADDING (CHAR_BIT - 1)
+#define BLOCK_FLUSH_SIZE \
+ (MAX_BLOCK_SIZE - MAX_SAMPLE_SIZE - MAX_BITMAP_PADDING)
+
+static int
+buffer_append(ByteBuffer *buffer, const void *data, size_t size)
+{
+ if (buffer->size > MAX_BLOCK_SIZE ||
+ size > MAX_BLOCK_SIZE - buffer->size) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "sample block buffer exceeds the writer safety limit");
+ return -1;
+ }
+ if (buffer_reserve(buffer, buffer->size + size) < 0) {
+ return -1;
+ }
+ if (size != 0) {
+ memcpy(buffer->data + buffer->size, data, size);
+ }
+ buffer->size += size;
+ return 0;
+}
+
+static int
+buffer_append_varint(ByteBuffer *buffer, uint64_t value)
+{
+ uint8_t bytes[MAX_VARINT_SIZE];
+ size_t size = encode_varint_u64(bytes, value);
+ return buffer_append(buffer, bytes, size);
+}
+
+static int
+column_write(SampleBlock *block, unsigned column, const void *data,
+ size_t size)
+{
+ if (buffer_append(&block->columns[column], data, size) < 0) {
+ return -1;
+ }
+ block->size += size;
+ return 0;
+}
+
+static int
+column_write_varint(SampleBlock *block, unsigned column, uint64_t value)
+{
+ uint8_t bytes[MAX_VARINT_SIZE];
+ size_t size = encode_varint_u64(bytes, value);
+ return column_write(block, column, bytes, size);
+}
/* Helper macro: convert PyLong to int32, using default_val if conversion fails */
#define PYLONG_TO_INT32_OR_DEFAULT(obj, var, default_val) \
@@ -126,19 +185,6 @@ fwrite_checked_allow_threads(const void *data, size_t size, FILE *fp)
return 0;
}
-/* Forward declaration for writer_write_bytes */
-static inline int writer_write_bytes(BinaryWriter *writer, const void *data, size_t size);
-
-/* Encode and write a varint u32 - returns 0 on success, -1 on error */
-static inline int
-writer_write_varint_u32(BinaryWriter *writer, uint32_t value)
-{
- uint8_t buf[MAX_VARINT_SIZE];
- size_t len = encode_varint_u32(buf, value);
- return writer_write_bytes(writer, buf, len);
-}
-
-
/* ============================================================================
* UTILITY FUNCTIONS
* ============================================================================ */
@@ -177,9 +223,9 @@ writer_init_zstd(BinaryWriter *writer)
return -1;
}
- /* Compression level 5: better ratio for repetitive profiling data */
+ /* Compression level 3: good ratio without slowing down each block flush */
size_t result = ZSTD_CCtx_setParameter(writer->zstd.cctx,
- ZSTD_c_compressionLevel, 5);
+ ZSTD_c_compressionLevel, 3);
if (ZSTD_isError(result)) {
PyErr_Format(PyExc_RuntimeError, "Failed to set zstd compression level: %s",
ZSTD_getErrorName(result));
@@ -188,16 +234,6 @@ writer_init_zstd(BinaryWriter *writer)
return -1;
}
- /* Use large buffer (512KB) for fewer I/O syscalls */
- writer->zstd.compressed_buffer = PyMem_Malloc(COMPRESSED_BUFFER_SIZE);
- if (!writer->zstd.compressed_buffer) {
- ZSTD_freeCCtx(writer->zstd.cctx);
- writer->zstd.cctx = NULL;
- PyErr_NoMemory();
- return -1;
- }
- writer->zstd.compressed_buffer_size = COMPRESSED_BUFFER_SIZE;
-
return 0;
#else
PyErr_SetString(PyExc_RuntimeError,
@@ -206,78 +242,6 @@ writer_init_zstd(BinaryWriter *writer)
#endif
}
-static int
-writer_flush_buffer(BinaryWriter *writer)
-{
- if (writer->buffer_pos == 0) {
- return 0;
- }
-
-#ifdef HAVE_ZSTD
- if (writer->compression_type == COMPRESSION_ZSTD) {
- ZSTD_inBuffer input = { writer->write_buffer, writer->buffer_pos, 0 };
-
- while (input.pos < input.size) {
- ZSTD_outBuffer output = {
- writer->zstd.compressed_buffer,
- writer->zstd.compressed_buffer_size,
- 0
- };
-
- size_t result = ZSTD_compressStream2(
- writer->zstd.cctx, &output, &input, ZSTD_e_continue
- );
-
- if (ZSTD_isError(result)) {
- PyErr_Format(PyExc_IOError, "zstd compression error: %s",
- ZSTD_getErrorName(result));
- return -1;
- }
-
- if (output.pos > 0) {
- if (fwrite_checked_allow_threads(writer->zstd.compressed_buffer, output.pos, writer->fp) < 0) {
- return -1;
- }
- }
- }
- } else
-#endif
- {
- if (fwrite_checked_allow_threads(writer->write_buffer, writer->buffer_pos, writer->fp) < 0) {
- return -1;
- }
- }
-
- writer->buffer_pos = 0;
- return 0;
-}
-
-static inline int
-writer_write_bytes(BinaryWriter *writer, const void *data, size_t size)
-{
- const uint8_t *src = (const uint8_t *)data;
- size_t original_size = size;
-
- while (size > 0) {
- size_t space = writer->buffer_size - writer->buffer_pos;
- size_t to_copy = (size < space) ? size : space;
-
- memcpy(writer->write_buffer + writer->buffer_pos, src, to_copy);
- writer->buffer_pos += to_copy;
- src += to_copy;
- size -= to_copy;
-
- if (writer->buffer_pos == writer->buffer_size) {
- if (writer_flush_buffer(writer) < 0) {
- return -1;
- }
- }
- }
-
- writer->stats.bytes_written += original_size;
- return 0;
-}
-
/* ============================================================================
* HASH TABLE SUPPORT FUNCTIONS (using _Py_hashtable)
* ============================================================================ */
@@ -370,6 +334,7 @@ writer_intern_string(BinaryWriter *writer, PyObject *string, uint32_t *index)
}
if (writer->string_count >= UINT32_MAX) {
+ writer->state = BINARY_WRITER_LIMIT_REACHED;
PyErr_SetString(PyExc_OverflowError,
"too many strings for binary format");
return -1;
@@ -379,16 +344,23 @@ writer_intern_string(BinaryWriter *writer, PyObject *string, uint32_t *index)
(void **)&writer->string_lengths,
&writer->string_capacity,
sizeof(char *), sizeof(size_t)) < 0) {
+ if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
+ writer->state = BINARY_WRITER_LIMIT_REACHED;
+ }
return -1;
}
}
- Py_ssize_t str_len;
- const char *str_data = PyUnicode_AsUTF8AndSize(string, &str_len);
- if (!str_data) {
+ /* Frame names can contain surrogates (e.g. from undecodable filenames).
+ * Escape them to keep the string table valid UTF-8. */
+ PyObject *encoded = PyUnicode_AsEncodedString(string, "utf-8", "backslashreplace");
+ if (encoded == NULL) {
return -1;
}
+ Py_ssize_t str_len = PyBytes_GET_SIZE(encoded);
if ((uintmax_t)str_len > UINT32_MAX) {
+ Py_DECREF(encoded);
+ writer->state = BINARY_WRITER_LIMIT_REACHED;
PyErr_Format(PyExc_OverflowError,
"string length %zd exceeds binary format maximum %u",
str_len, UINT32_MAX);
@@ -397,10 +369,12 @@ writer_intern_string(BinaryWriter *writer, PyObject *string, uint32_t *index)
char *str_copy = PyMem_Malloc(str_len + 1);
if (!str_copy) {
+ Py_DECREF(encoded);
PyErr_NoMemory();
return -1;
}
- memcpy(str_copy, str_data, str_len + 1);
+ memcpy(str_copy, PyBytes_AS_STRING(encoded), str_len + 1);
+ Py_DECREF(encoded);
*index = (uint32_t)writer->string_count;
@@ -437,12 +411,16 @@ writer_intern_frame(BinaryWriter *writer, const FrameEntry *entry, uint32_t *ind
}
if (writer->frame_count >= UINT32_MAX) {
+ writer->state = BINARY_WRITER_LIMIT_REACHED;
PyErr_SetString(PyExc_OverflowError,
"too many frames for binary format");
return -1;
}
if (GROW_ARRAY(writer->frame_entries, writer->frame_count,
writer->frame_capacity, FrameEntry) < 0) {
+ if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
+ writer->state = BINARY_WRITER_LIMIT_REACHED;
+ }
return -1;
}
@@ -466,269 +444,640 @@ writer_intern_frame(BinaryWriter *writer, const FrameEntry *entry, uint32_t *ind
return 0;
}
-/* Get or create a thread entry for the given thread_id.
- * Returns pointer to ThreadEntry, or NULL on allocation failure.
- * If is_new is non-NULL, sets it to 1 if this is a new thread, 0 otherwise. */
+/* Get or create the entry for a (thread, interpreter) pair. */
static ThreadEntry *
writer_get_or_create_thread_entry(BinaryWriter *writer, uint64_t thread_id,
- uint32_t interpreter_id, int *is_new)
+ uint32_t interpreter_id)
{
/* Linear search is OK for small number of threads.
* Key is (thread_id, interpreter_id) since same thread_id can exist in different interpreters. */
for (size_t i = 0; i < writer->thread_count; i++) {
if (writer->thread_entries[i].thread_id == thread_id &&
writer->thread_entries[i].interpreter_id == interpreter_id) {
- if (is_new) {
- *is_new = 0;
- }
return &writer->thread_entries[i];
}
}
if (writer->thread_count >= UINT32_MAX) {
+ writer->state = BINARY_WRITER_LIMIT_REACHED;
PyErr_SetString(PyExc_OverflowError,
"too many threads for binary format");
return NULL;
}
- if (writer->thread_count >= writer->thread_capacity) {
- ThreadEntry *new_entries = grow_array(writer->thread_entries,
- &writer->thread_capacity,
- sizeof(ThreadEntry));
- if (!new_entries) {
- return NULL;
+ if (GROW_ARRAY(writer->thread_entries, writer->thread_count,
+ writer->thread_capacity, ThreadEntry) < 0) {
+ if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
+ writer->state = BINARY_WRITER_LIMIT_REACHED;
}
- writer->thread_entries = new_entries;
+ return NULL;
}
ThreadEntry *entry = &writer->thread_entries[writer->thread_count];
memset(entry, 0, sizeof(ThreadEntry));
entry->thread_id = thread_id;
entry->interpreter_id = interpreter_id;
- entry->prev_timestamp = writer->start_time_us;
- entry->prev_stack_capacity = MAX_STACK_DEPTH;
-
- entry->prev_stack = PyMem_Calloc(entry->prev_stack_capacity, sizeof(uint32_t));
- if (!entry->prev_stack) {
- PyErr_NoMemory();
- return NULL;
- }
+ entry->block_stream_index = UINT32_MAX;
writer->thread_count++;
- if (is_new) {
- *is_new = 1;
- }
return entry;
}
-/* Compare two stacks and return the encoding type and parameters.
- * Sets:
- * - shared_count: number of frames matching from bottom of stack
- * - pop_count: frames to remove from prev stack
- * - push_count: new frames to add
- *
- * Returns the best encoding type to use. */
static int
-compare_stacks(const uint32_t *prev_stack, size_t prev_depth,
- const uint32_t *curr_stack, size_t curr_depth,
- size_t *shared_count, size_t *pop_count, size_t *push_count)
+encode_column(BinaryWriter *writer, const ByteBuffer *decoded,
+ ColumnDescriptor *descriptor)
{
- if (prev_depth == curr_depth) {
- int identical = 1;
- for (size_t i = 0; i < prev_depth; i++) {
- if (prev_stack[i] != curr_stack[i]) {
- identical = 0;
- break;
- }
+ SampleBlock *block = writer->block;
+ const uint8_t *data = decoded->data;
+ size_t size = decoded->size;
+ uint8_t encoding = COMPRESSION_NONE;
+ if (size > 1 && memcmp(data, data + 1, size - 1) == 0) {
+ encoding = COLUMN_CONSTANT;
+ size = 1;
+ }
+#ifdef HAVE_ZSTD
+ if (encoding == COMPRESSION_NONE && size >= ZSTD_MIN_SIZE &&
+ writer->compression_type == COMPRESSION_ZSTD) {
+ size_t compress_bound = ZSTD_compressBound(size);
+ if (buffer_reserve(&block->compressed, compress_bound) < 0) {
+ return -1;
+ }
+ size_t compressed_size = ZSTD_compress2(
+ writer->zstd.cctx, block->compressed.data, compress_bound,
+ data, size);
+ if (ZSTD_isError(compressed_size)) {
+ PyErr_Format(PyExc_IOError, "zstd compression error: %s",
+ ZSTD_getErrorName(compressed_size));
+ return -1;
}
- if (identical) {
- *shared_count = prev_depth;
- *pop_count = 0;
- *push_count = 0;
- return STACK_REPEAT;
+ _Py_MSAN_UNPOISON(block->compressed.data, compressed_size);
+ uint8_t stored_size[MAX_VARINT_SIZE];
+ if (compressed_size + encode_varint_u64(stored_size, compressed_size)
+ < size) {
+ data = block->compressed.data;
+ size = compressed_size;
+ encoding = COMPRESSION_ZSTD;
}
}
+#endif
+ descriptor->decoded_size = (uint32_t)decoded->size;
+ descriptor->stored_size = (uint32_t)size;
+ descriptor->encoding = encoding;
+ if (buffer_reserve(&block->output, block->output.size + size) < 0) {
+ return -1;
+ }
+ if (size != 0) {
+ memcpy(block->output.data + block->output.size, data, size);
+ }
+ block->output.size += size;
+ return 0;
+}
- /* Find longest common suffix (frames at the bottom/outer part of stack).
- * Stacks are stored innermost-first, so suffix is at the end. */
- size_t suffix_len = 0;
- size_t min_depth = (prev_depth < curr_depth) ? prev_depth : curr_depth;
-
- for (size_t i = 0; i < min_depth; i++) {
- size_t prev_idx = prev_depth - 1 - i;
- size_t curr_idx = curr_depth - 1 - i;
- if (prev_stack[prev_idx] == curr_stack[curr_idx]) {
- suffix_len++;
- } else {
- break;
+static ByteBuffer *
+transform_statuses(SampleBlock *block, uint8_t bitmap_flags)
+{
+ size_t plane_size = status_bitmap_size(block->sample_count);
+ unsigned plane_count = (unsigned)_Py_popcount32(bitmap_flags);
+ if (buffer_reserve(&block->transformed,
+ plane_size * plane_count) < 0) {
+ return NULL;
+ }
+ const uint8_t *statuses =
+ block->columns[COLUMN_STATUS_BITMAPS].data;
+ block->transformed.size = 0;
+ for (unsigned bit = 0; bit < CHAR_BIT; bit++) {
+ if (!(bitmap_flags & (1U << bit))) {
+ continue;
+ }
+ uint8_t *plane = block->transformed.data + block->transformed.size;
+ memset(plane, 0, plane_size);
+ for (uint32_t sample = 0; sample < block->sample_count; sample++) {
+ plane[sample / CHAR_BIT] |= ((statuses[sample] >> bit) & 1U)
+ << (sample % CHAR_BIT);
}
+ block->transformed.size += plane_size;
}
+ return &block->transformed;
+}
- *shared_count = suffix_len;
- *pop_count = prev_depth - suffix_len;
- *push_count = curr_depth - suffix_len;
-
- /* Choose best encoding based on byte cost */
- /* STACK_FULL: 1 (type) + 1-2 (depth) + sum(frame varints) */
- /* STACK_SUFFIX: 1 (type) + 1-2 (shared) + 1-2 (new_count) + sum(new frame varints) */
- /* STACK_POP_PUSH: 1 (type) + 1-2 (pop) + 1-2 (push) + sum(new frame varints) */
-
- /* If no common suffix, use full stack */
- if (suffix_len == 0) {
- return STACK_FULL;
+static ByteBuffer *
+transform_frame_ids(SampleBlock *block, unsigned width)
+{
+ ByteBuffer *frames = &block->columns[COLUMN_FRAME_IDS];
+ size_t frame_count = frames->size / sizeof(uint32_t);
+ if (buffer_reserve(&block->transformed,
+ frame_count * width) < 0) {
+ return NULL;
}
-
- /* If only adding frames (suffix == prev_depth), use SUFFIX */
- if (*pop_count == 0 && *push_count > 0) {
- return STACK_SUFFIX;
+ const uint32_t *frame_ids = (const uint32_t *)frames->data;
+ for (unsigned byte = 0; frame_count && byte < width; byte++) {
+ uint8_t *plane =
+ block->transformed.data + (size_t)byte * frame_count;
+ for (uint32_t frame = 0; frame < frame_count; frame++) {
+ plane[frame] =
+ (uint8_t)(frame_ids[frame] >> (byte * CHAR_BIT));
+ }
}
+ block->transformed.size = frame_count * width;
+ return &block->transformed;
+}
- /* If popping and/or pushing, use POP_PUSH if it saves bytes */
- /* Heuristic: POP_PUSH is better when we're modifying top frames */
- if (*pop_count > 0 || *push_count > 0) {
- /* Use full stack if sharing less than half the frames */
- if (suffix_len < curr_depth / 2) {
- return STACK_FULL;
+static ByteBuffer *
+transform_stack_instructions(SampleBlock *block)
+{
+ ByteBuffer *instructions =
+ &block->columns[COLUMN_STACK_INSTRUCTIONS];
+ size_t repeat_count = block->repeats.size / sizeof(Repeat);
+ if (repeat_count == 0) {
+ return instructions;
+ }
+ const Repeat *repeats = (const Repeat *)block->repeats.data;
+ size_t copied_offset = 0;
+ block->transformed.size = 0;
+ for (size_t i = 0; i < repeat_count; i++) {
+ if (buffer_append(&block->transformed,
+ instructions->data + copied_offset,
+ repeats[i].offset - copied_offset) < 0 ||
+ buffer_append_varint(
+ &block->transformed, STACK_REPEAT) < 0 ||
+ buffer_append_varint(
+ &block->transformed, repeats[i].count) < 0) {
+ return NULL;
}
- return STACK_POP_PUSH;
+ copied_offset = repeats[i].offset;
}
+ if (buffer_append(&block->transformed,
+ instructions->data + copied_offset,
+ instructions->size - copied_offset) < 0) {
+ return NULL;
+ }
+ return &block->transformed;
+}
+
+static void
+block_reset(BinaryWriter *writer)
+{
+ SampleBlock *block = writer->block;
+ /* Only threads with a stream in this block need resetting */
+ for (uint32_t i = 0; i < block->stream_count; i++) {
+ size_t thread = block->streams[i].thread_index;
+ writer->thread_entries[thread].block_stream_index = UINT32_MAX;
+ }
+ for (unsigned column = 0; column < COLUMN_COUNT; column++) {
+ block->columns[column].size = 0;
+ }
+ block->sample_count = 0;
+ block->stream_count = 0;
+ block->repeats.size = 0;
+ block->max_frame = 0;
+ block->size = 0;
+ memset(block->cache, 0, sizeof(block->cache));
+}
- return STACK_FULL;
+static unsigned
+block_frame_width(const SampleBlock *block)
+{
+ if (block->max_frame == 0) {
+ return 1;
+ }
+ return (unsigned)(_Py_bit_length(block->max_frame) + CHAR_BIT - 1)
+ / CHAR_BIT;
}
-/* Write common sample header: thread_id(8) + interpreter_id(4) + encoding(1).
- * Returns 0 on success, -1 on failure. */
-static inline int
-write_sample_header(BinaryWriter *writer, ThreadEntry *entry, uint8_t encoding)
+static void
+block_status_flags(const SampleBlock *block, uint8_t *common_flags,
+ uint8_t *bitmap_flags)
+{
+ uint8_t common_status = UINT8_MAX;
+ uint8_t any_status = 0;
+ const uint8_t *statuses = block->columns[COLUMN_STATUS_BITMAPS].data;
+ for (uint32_t sample = 0; sample < block->sample_count; sample++) {
+ common_status &= statuses[sample];
+ any_status |= statuses[sample];
+ }
+ *common_flags = common_status;
+ *bitmap_flags = any_status ^ common_status;
+}
+
+static size_t
+write_block_header(const BlockHeader *header, uint8_t *bytes)
{
- uint8_t header[SAMPLE_HEADER_FIXED_SIZE];
- memcpy(header + SMP_OFF_THREAD_ID, &entry->thread_id, SMP_SIZE_THREAD_ID);
- memcpy(header + SMP_OFF_INTERPRETER_ID, &entry->interpreter_id, SMP_SIZE_INTERPRETER_ID);
- header[SMP_OFF_ENCODING] = encoding;
- return writer_write_bytes(writer, header, SAMPLE_HEADER_FIXED_SIZE);
+ /* Magic "TBLK", sample count and base timestamp (varints), then frame
+ * ID width and the two status flag masks (1 byte each) */
+ size_t size = BLOCK_MAGIC_SIZE;
+ memcpy(bytes, BLOCK_MAGIC, BLOCK_MAGIC_SIZE);
+ size += encode_varint_u32(bytes + size, header->sample_count);
+ size += encode_varint_u64(bytes + size, header->base_timestamp);
+ bytes[size++] = header->frame_width;
+ bytes[size++] = header->common_status_flags;
+ bytes[size++] = header->status_bitmap_flags;
+
+ /* Each column: decoded size (varint), encoding (1 byte), and the stored
+ * size (varint) for zstd only */
+ for (unsigned column = 0; column < COLUMN_COUNT; column++) {
+ const ColumnDescriptor *descriptor = &header->columns[column];
+ size += encode_varint_u32(bytes + size, descriptor->decoded_size);
+ bytes[size++] = descriptor->encoding;
+ if (descriptor->encoding == COMPRESSION_ZSTD) {
+ size += encode_varint_u32(bytes + size, descriptor->stored_size);
+ }
+ }
+ return size;
}
-/* Flush pending RLE samples for a thread.
- * Writes the RLE record to the output buffer.
- * Returns 0 on success, -1 on failure. */
static int
-flush_pending_rle(BinaryWriter *writer, ThreadEntry *entry)
+block_flush(BinaryWriter *writer)
{
- if (entry->pending_rle_samples == 0) {
+ SampleBlock *block = writer->block;
+ if (block->sample_count == 0) {
return 0;
}
+ BlockHeader header = {0};
+ header.sample_count = block->sample_count;
+ header.base_timestamp = block->base_timestamp;
+ header.frame_width = (uint8_t)block_frame_width(block);
+ block_status_flags(block, &header.common_status_flags,
+ &header.status_bitmap_flags);
- /* Write RLE record:
- * [thread_id: 8] [interpreter_id: 4] [STACK_REPEAT: 1] [count: varint]
- * [timestamp_delta_1: varint] [status_1: 1] ... [timestamp_delta_N: varint] [status_N: 1]
- */
-
- if (write_sample_header(writer, entry, STACK_REPEAT) < 0) {
+ /* Convert each column to its file form, then encode it */
+ /* Leave room for the header, which is written once its size is known */
+ if (buffer_reserve(&block->output, MAX_BLOCK_HEADER_SIZE) < 0) {
return -1;
}
-
- if (writer_write_varint_u32(writer, (uint32_t)entry->pending_rle_samples) < 0) {
+ block->output.size = MAX_BLOCK_HEADER_SIZE;
+ size_t decoded_payload_size = 0;
+ for (unsigned column = 0; column < COLUMN_COUNT; column++) {
+ ByteBuffer *decoded = &block->columns[column];
+ switch (column) {
+ case COLUMN_STATUS_BITMAPS:
+ decoded = transform_statuses(block, header.status_bitmap_flags);
+ break;
+ case COLUMN_STACK_INSTRUCTIONS:
+ decoded = transform_stack_instructions(block);
+ break;
+ case COLUMN_FRAME_IDS:
+ decoded = transform_frame_ids(block, header.frame_width);
+ break;
+ }
+ if (decoded == NULL) {
+ return -1;
+ }
+ if (decoded->size >
+ MAX_BLOCK_SIZE - decoded_payload_size) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "sample block exceeds the decoded size limit");
+ return -1;
+ }
+ decoded_payload_size += decoded->size;
+ if (encode_column(writer, decoded, &header.columns[column]) < 0) {
+ return -1;
+ }
+ }
+ /* Put the header right before the columns and write the block */
+ uint8_t header_bytes[MAX_BLOCK_HEADER_SIZE];
+ size_t header_size = write_block_header(&header, header_bytes);
+ size_t unused = MAX_BLOCK_HEADER_SIZE - header_size;
+ uint8_t *header_start = block->output.data + unused;
+ memcpy(header_start, header_bytes, header_size);
+ if (fwrite_checked_allow_threads(header_start,
+ block->output.size - unused,
+ writer->fp) < 0) {
return -1;
}
+ writer->stats.bytes_written += decoded_payload_size;
+ block_reset(writer);
+ return 0;
+}
- if (writer_write_bytes(writer, entry->pending_rle, entry->pending_rle_bytes) < 0) {
- return -1;
+/* FNV-1a over the frame indices, the same in every process */
+static Py_uhash_t
+stack_hash(const uint32_t *stack, size_t depth)
+{
+ uint64_t hash = 0xcbf29ce484222325;
+ for (size_t i = 0; i < depth; i++) {
+ hash = (hash ^ stack[i]) * 0x100000001b3;
+ }
+ /* Mix the high bits into the low bits that select the cache bucket */
+ hash ^= hash >> 33;
+ hash *= 0xff51afd7ed558ccd;
+ hash ^= hash >> 33;
+ return (Py_uhash_t)hash;
+}
+
+static size_t
+common_outer_frames(const BlockStream *stream, const uint32_t *stack,
+ size_t depth)
+{
+ size_t shared = 0;
+ while (shared < depth && shared < stream->prev_stack_depth &&
+ stack[depth - 1 - shared] ==
+ stream->prev_stack[stream->prev_stack_depth - 1 - shared]) {
+ shared++;
+ }
+ return shared;
+}
+
+static int
+cached_stack_matches(const StackCacheEntry *cached,
+ const ByteBuffer *frames, Py_uhash_t hash,
+ const uint32_t *stack, size_t depth)
+{
+ if (cached->hash != hash || cached->depth != depth) {
+ return 0;
}
+ const uint32_t *frame_ids = (const uint32_t *)frames->data;
+ for (size_t frame = 0; frame < depth; frame++) {
+ if (stack[frame] !=
+ frame_ids[cached->offset + depth - 1 - frame]) {
+ return 0;
+ }
+ }
+ return 1;
+}
- writer->stats.repeat_records++;
- writer->stats.repeat_samples += entry->pending_rle_samples;
- /* Each RLE sample saves writing the entire stack */
- writer->stats.frames_saved += entry->pending_rle_samples * entry->prev_stack_depth;
+static StackCacheEntry *
+stack_cache_lookup(StackCacheEntry *bucket, const ByteBuffer *frames,
+ Py_uhash_t hash, const uint32_t *stack, size_t depth)
+{
+ for (size_t i = 0; i < STACK_CACHE_BUCKET_SIZE; i++) {
+ if (cached_stack_matches(&bucket[i], frames, hash, stack, depth)) {
+ return &bucket[i];
+ }
+ }
+ return NULL;
+}
- entry->pending_rle_bytes = 0;
- entry->pending_rle_samples = 0;
+static void
+stack_cache_insert(StackCacheEntry *bucket, StackCacheEntry entry)
+{
+ memmove(&bucket[1], &bucket[0],
+ (STACK_CACHE_BUCKET_SIZE - 1) * sizeof(*bucket));
+ bucket[0] = entry;
+}
+static int
+write_stack_repeat(BinaryWriter *writer, BlockStream *stream, size_t depth)
+{
+ SampleBlock *block = writer->block;
+ if (stream->current_repeat == UINT32_MAX) {
+ Repeat repeat = {
+ (uint32_t)block->columns[COLUMN_STACK_INSTRUCTIONS].size, 1};
+ if (buffer_append(&block->repeats,
+ &repeat, sizeof(repeat)) < 0) {
+ return -1;
+ }
+ block->size += sizeof(repeat);
+ stream->current_repeat =
+ (uint32_t)(block->repeats.size / sizeof(repeat) - 1);
+ writer->stats.repeat_records++;
+ }
+ else {
+ Repeat *repeats = (Repeat *)block->repeats.data;
+ repeats[stream->current_repeat].count++;
+ }
+ writer->stats.repeat_samples++;
+ writer->stats.frames_saved += depth;
return 0;
}
-/* Write a single sample with the specified encoding.
- * Returns 0 on success, -1 on failure. */
static int
-write_sample_with_encoding(BinaryWriter *writer, ThreadEntry *entry,
- uint64_t timestamp_delta, uint8_t status,
- int encoding_type,
- const uint32_t *frame_indices, size_t stack_depth,
- size_t shared_count, size_t pop_count, size_t push_count)
+write_stack_reuse(BinaryWriter *writer,
+ const StackCacheEntry *cached, size_t depth)
{
- /* Header: thread_id(8) + interpreter_id(4) + encoding(1) + delta(varint) + status(1) */
- uint8_t header_buf[SAMPLE_HEADER_MAX_SIZE];
- memcpy(header_buf + SMP_OFF_THREAD_ID, &entry->thread_id, SMP_SIZE_THREAD_ID);
- memcpy(header_buf + SMP_OFF_INTERPRETER_ID, &entry->interpreter_id, SMP_SIZE_INTERPRETER_ID);
- header_buf[SMP_OFF_ENCODING] = (uint8_t)encoding_type;
- size_t varint_len = encode_varint_u64(
- header_buf + SAMPLE_HEADER_FIXED_SIZE,
- timestamp_delta);
- header_buf[SAMPLE_HEADER_FIXED_SIZE + varint_len] = status;
-
- if (writer_write_bytes(writer, header_buf,
- SAMPLE_HEADER_FIXED_SIZE + varint_len + 1) < 0) {
+ SampleBlock *block = writer->block;
+ if (column_write_varint(block, COLUMN_STACK_INSTRUCTIONS,
+ STACK_REUSE) < 0 ||
+ column_write_varint(block, COLUMN_STACK_INSTRUCTIONS,
+ cached->offset) < 0 ||
+ column_write_varint(block, COLUMN_STACK_INSTRUCTIONS, depth) < 0) {
return -1;
}
+ writer->stats.reuse_records++;
+ writer->stats.frames_saved += depth;
+ return 0;
+}
- uint8_t frame_buf[MAX_FRAME_BUFFER_SIZE];
- size_t frame_buf_pos = 0;
- size_t frames_written = 0;
+static int
+write_stack_replace_suffix(BinaryWriter *writer, StackCacheEntry *bucket,
+ Py_uhash_t hash, const uint32_t *stack,
+ size_t depth, size_t shared)
+{
+ SampleBlock *block = writer->block;
+ ByteBuffer *frames = &block->columns[COLUMN_FRAME_IDS];
+ size_t new_frames = depth - shared;
+ if (column_write_varint(block, COLUMN_STACK_INSTRUCTIONS,
+ STACK_REPLACE_SUFFIX) < 0 ||
+ column_write_varint(block, COLUMN_STACK_INSTRUCTIONS, shared) < 0 ||
+ column_write_varint(block, COLUMN_STACK_INSTRUCTIONS,
+ new_frames) < 0) {
+ return -1;
+ }
- switch (encoding_type) {
- case STACK_FULL:
- /* [depth: varint] [frame_idx: varint]... */
- frame_buf_pos += encode_varint_u32(frame_buf, (uint32_t)stack_depth);
- for (size_t i = 0; i < stack_depth; i++) {
- frame_buf_pos += encode_varint_u32(frame_buf + frame_buf_pos, frame_indices[i]);
+ /* Append the new inner frames, outermost first */
+ size_t stack_offset = frames->size / sizeof(uint32_t);
+ if (new_frames != 0) {
+ if (buffer_reserve(
+ frames, frames->size + new_frames * sizeof(uint32_t)) < 0) {
+ return -1;
}
- frames_written = stack_depth;
- writer->stats.full_records++;
- break;
-
- case STACK_SUFFIX:
- /* [shared_count: varint] [new_count: varint] [new_frame_idx: varint]... */
- frame_buf_pos += encode_varint_u32(frame_buf, (uint32_t)shared_count);
- frame_buf_pos += encode_varint_u32(frame_buf + frame_buf_pos, (uint32_t)push_count);
- /* New frames are at the top (beginning) of current stack */
- for (size_t i = 0; i < push_count; i++) {
- frame_buf_pos += encode_varint_u32(frame_buf + frame_buf_pos, frame_indices[i]);
+ uint32_t *new_frame_ids = (uint32_t *)(frames->data + frames->size);
+ for (size_t i = 0; i < new_frames; i++) {
+ uint32_t frame = stack[new_frames - 1 - i];
+ new_frame_ids[i] = frame;
+ if (frame > block->max_frame) {
+ block->max_frame = frame;
+ }
}
- frames_written = push_count;
- writer->stats.suffix_records++;
- /* Saved writing shared_count frames */
- writer->stats.frames_saved += shared_count;
- break;
-
- case STACK_POP_PUSH:
- /* [pop_count: varint] [push_count: varint] [new_frame_idx: varint]... */
- frame_buf_pos += encode_varint_u32(frame_buf, (uint32_t)pop_count);
- frame_buf_pos += encode_varint_u32(frame_buf + frame_buf_pos, (uint32_t)push_count);
- /* New frames are at the top (beginning) of current stack */
- for (size_t i = 0; i < push_count; i++) {
- frame_buf_pos += encode_varint_u32(frame_buf + frame_buf_pos, frame_indices[i]);
+ frames->size += new_frames * sizeof(uint32_t);
+ block->size += new_frames * sizeof(uint32_t);
+ }
+ /* Complete stacks are cached so later samples can REUSE them */
+ if (shared == 0) {
+ if (bucket != NULL) {
+ stack_cache_insert(bucket, (StackCacheEntry){
+ hash, (uint32_t)stack_offset, (uint32_t)depth});
}
- frames_written = push_count;
- writer->stats.pop_push_records++;
- /* Saved writing shared_count frames (stack_depth - push_count if we had written full) */
- writer->stats.frames_saved += shared_count;
- break;
-
- default:
- PyErr_SetString(PyExc_RuntimeError, "Invalid stack encoding type");
+ writer->stats.full_records++;
+ }
+ else {
+ writer->stats.suffix_records++;
+ }
+ writer->stats.total_frames_written += new_frames;
+ writer->stats.frames_saved += shared;
+ return 0;
+}
+
+static int
+write_stack(BinaryWriter *writer, BlockStream *stream, int new_stream,
+ const uint32_t *stack, size_t depth)
+{
+ SampleBlock *block = writer->block;
+ size_t shared = common_outer_frames(stream, stack, depth);
+ /* Same stack as this stream's previous sample: extend its REPEAT */
+ if (!new_stream && shared == depth &&
+ shared == stream->prev_stack_depth) {
+ return write_stack_repeat(writer, stream, depth);
+ }
+
+ /* Enough new frames to be worth looking up an earlier complete stack */
+ Py_uhash_t hash = 0;
+ StackCacheEntry *bucket = NULL;
+ StackCacheEntry *cached = NULL;
+ if (depth - shared >= STACK_REUSE_MIN_FRAMES) {
+ hash = stack_hash(stack, depth);
+ bucket = block->cache[hash % STACK_CACHE_BUCKET_COUNT];
+ cached = stack_cache_lookup(bucket, &block->columns[COLUMN_FRAME_IDS],
+ hash, stack, depth);
+ }
+
+ int result;
+ if (cached != NULL) {
+ /* Stack already stored in this block: point to its frames */
+ result = write_stack_reuse(writer, cached, depth);
+ }
+ else {
+ /* Keep the shared outer frames and write only the new inner ones */
+ result = write_stack_replace_suffix(writer, bucket, hash, stack,
+ depth, shared);
+ }
+ if (result < 0) {
return -1;
}
+ stream->current_repeat = UINT32_MAX;
+ memcpy(stream->prev_stack, stack, depth * sizeof(uint32_t));
+ stream->prev_stack_depth = depth;
+ return 0;
+}
+
+size_t
+binary_writer_buffered_size(BinaryWriter *writer)
+{
+ SampleBlock *block = writer->block;
+ if (block == NULL || block->sample_count == 0) {
+ return 0;
+ }
+ size_t size = block->columns[COLUMN_STREAM_TABLE].size
+ + block->columns[COLUMN_SAMPLE_STREAM_IDS].size
+ + block->columns[COLUMN_TIMESTAMP_RESIDUALS].size
+ + block->columns[COLUMN_STACK_INSTRUCTIONS].size;
+ const Repeat *repeats = (const Repeat *)block->repeats.data;
+ size_t repeat_count = block->repeats.size / sizeof(Repeat);
+ uint8_t bytes[MAX_VARINT_SIZE];
+ for (size_t i = 0; i < repeat_count; i++) {
+ size += encode_varint_u64(bytes, STACK_REPEAT)
+ + encode_varint_u64(bytes, repeats[i].count);
+ }
+ uint8_t common_flags, bitmap_flags;
+ block_status_flags(block, &common_flags, &bitmap_flags);
+ size += (size_t)_Py_popcount32(bitmap_flags)
+ * status_bitmap_size(block->sample_count);
+ size += block->columns[COLUMN_FRAME_IDS].size / sizeof(uint32_t)
+ * block_frame_width(block);
+ return size;
+}
- if (writer_write_bytes(writer, frame_buf, frame_buf_pos) < 0) {
+static int
+block_add_stream(BinaryWriter *writer, ThreadEntry *entry)
+{
+ SampleBlock *block = writer->block;
+ if (GROW_ARRAY(block->streams, block->stream_count,
+ block->stream_capacity, BlockStream) < 0) {
return -1;
}
+ /* Stream table entry: thread_id (8 bytes) + interpreter_id (4 bytes) */
+ uint8_t stream_entry[STREAM_ENTRY_SIZE];
+ memcpy(stream_entry + STM_OFF_THREAD_ID,
+ &entry->thread_id, sizeof(entry->thread_id));
+ memcpy(stream_entry + STM_OFF_INTERPRETER_ID,
+ &entry->interpreter_id, sizeof(entry->interpreter_id));
+ if (column_write(block, COLUMN_STREAM_TABLE,
+ stream_entry, sizeof(stream_entry)) < 0) {
+ return -1;
+ }
+ BlockStream *stream = &block->streams[block->stream_count];
+ stream->thread_index = (size_t)(entry - writer->thread_entries);
+ stream->prev_timestamp = block->base_timestamp - writer->sample_interval_us;
+ stream->current_repeat = UINT32_MAX;
+ stream->prev_stack_depth = 0;
+ entry->block_stream_index = block->stream_count++;
+ return 0;
+}
- writer->stats.total_frames_written += frames_written;
+static int
+block_add_sample(BinaryWriter *writer, ThreadEntry *entry,
+ uint64_t timestamp, uint8_t status,
+ const uint32_t *stack, size_t depth)
+{
+ static_assert(BLOCK_FLUSH_SIZE + MAX_SAMPLE_SIZE + MAX_BITMAP_PADDING ==
+ MAX_BLOCK_SIZE,
+ "block flush size needs headroom for one complete sample");
+
+ SampleBlock *block = writer->block;
+ /* Start a new block if this sample might not fit */
+ if (block->size >= BLOCK_FLUSH_SIZE ||
+ (entry->block_stream_index == UINT32_MAX &&
+ block->stream_count == MAX_BLOCK_STREAMS)) {
+ if (block_flush(writer) < 0) {
+ return -1;
+ }
+ }
+ if (block->sample_count == 0) {
+ block->base_timestamp = timestamp;
+ }
+ int new_stream = entry->block_stream_index == UINT32_MAX;
+ if (new_stream && block_add_stream(writer, entry) < 0) {
+ return -1;
+ }
+ BlockStream *stream = &block->streams[entry->block_stream_index];
+ /* Store the difference from the expected timestamp */
+ uint64_t residual =
+ timestamp - stream->prev_timestamp - writer->sample_interval_us;
+ uint8_t residual_bytes[MAX_VARINT_SIZE];
+ size_t residual_size =
+ encode_varint_i64(residual_bytes, (int64_t)residual);
+ if (column_write_varint(block, COLUMN_SAMPLE_STREAM_IDS,
+ entry->block_stream_index) < 0 ||
+ column_write(block, COLUMN_TIMESTAMP_RESIDUALS,
+ residual_bytes, residual_size) < 0 ||
+ column_write(block, COLUMN_STATUS_BITMAPS,
+ &status, sizeof(status)) < 0) {
+ return -1;
+ }
+ if (write_stack(writer, stream, new_stream, stack, depth) < 0) {
+ return -1;
+ }
+ stream->prev_timestamp = timestamp;
+ block->sample_count++;
+ writer->total_samples++;
return 0;
}
+static void
+block_destroy(SampleBlock *block)
+{
+ if (block == NULL) {
+ return;
+ }
+ for (unsigned i = 0; i < COLUMN_COUNT; i++) {
+ buffer_clear(&block->columns[i]);
+ }
+ buffer_clear(&block->repeats);
+ buffer_clear(&block->transformed);
+ buffer_clear(&block->compressed);
+ buffer_clear(&block->output);
+ PyMem_Free(block->streams);
+ PyMem_Free(block);
+}
+
BinaryWriter *
binary_writer_create(PyObject *path, uint64_t sample_interval_us, int compression_type,
- uint64_t start_time_us)
+ uint64_t start_time_us, int profiling_mode,
+ int capture_features)
{
+ if (compression_type != COMPRESSION_NONE &&
+ compression_type != COMPRESSION_ZSTD) {
+ PyErr_SetString(PyExc_ValueError, "invalid compression type");
+ return NULL;
+ }
BinaryWriter *writer = PyMem_Calloc(1, sizeof(BinaryWriter));
if (!writer) {
PyErr_NoMemory();
@@ -738,13 +1087,21 @@ binary_writer_create(PyObject *path, uint64_t sample_interval_us, int compressio
writer->start_time_us = start_time_us;
writer->sample_interval_us = sample_interval_us;
writer->compression_type = compression_type;
+ writer->profiling_mode = profiling_mode;
+ writer->capture_features = capture_features;
- writer->write_buffer = PyMem_Malloc(WRITE_BUFFER_SIZE);
- if (!writer->write_buffer) {
+ writer->block = PyMem_Calloc(1, sizeof(SampleBlock));
+ if (writer->block == NULL) {
PyErr_NoMemory();
goto error;
}
- writer->buffer_size = WRITE_BUFFER_SIZE;
+ writer->block->streams = PyMem_Malloc(
+ INITIAL_BLOCK_STREAM_CAPACITY * sizeof(BlockStream));
+ if (writer->block->streams == NULL) {
+ PyErr_NoMemory();
+ goto error;
+ }
+ writer->block->stream_capacity = INITIAL_BLOCK_STREAM_CAPACITY;
writer->string_hash = _Py_hashtable_new_full(
string_hash_func,
@@ -924,6 +1281,12 @@ static int
process_thread_sample(BinaryWriter *writer, PyObject *thread_info,
uint32_t interpreter_id, uint64_t timestamp_us)
{
+ if (writer->total_samples == UINT64_MAX) {
+ writer->state = BINARY_WRITER_LIMIT_REACHED;
+ PyErr_SetString(PyExc_OverflowError, "too many samples for binary format");
+ return -1;
+ }
+
PyObject *thread_id_obj = PyStructSequence_GET_ITEM(thread_info, 0);
PyObject *status_obj = PyStructSequence_GET_ITEM(thread_info, 1);
PyObject *frame_list = PyStructSequence_GET_ITEM(thread_info, 2);
@@ -936,74 +1299,29 @@ process_thread_sample(BinaryWriter *writer, PyObject *thread_info,
if (status_long == -1 && PyErr_Occurred()) {
return -1;
}
+ if (status_long < 0 || status_long > UINT8_MAX) {
+ writer->state = BINARY_WRITER_LIMIT_REACHED;
+ PyErr_Format(PyExc_OverflowError,
+ "thread status %ld exceeds the binary format range",
+ status_long);
+ return -1;
+ }
uint8_t status = (uint8_t)status_long;
ThreadEntry *entry = writer_get_or_create_thread_entry(
- writer, thread_id, interpreter_id, NULL);
+ writer, thread_id, interpreter_id);
if (!entry) {
return -1;
}
- /* Calculate timestamp delta */
- uint64_t delta = timestamp_us - entry->prev_timestamp;
- entry->prev_timestamp = timestamp_us;
-
/* Process frames and build current stack */
uint32_t curr_stack[MAX_STACK_DEPTH];
size_t curr_depth;
if (build_frame_stack(writer, frame_list, curr_stack, &curr_depth) < 0) {
return -1;
}
-
- /* Compare with previous stack to determine encoding */
- size_t shared_count, pop_count, push_count;
- int encoding = compare_stacks(
- entry->prev_stack, entry->prev_stack_depth,
- curr_stack, curr_depth,
- &shared_count, &pop_count, &push_count);
-
- if (encoding == STACK_REPEAT) {
- /* Buffer this sample for RLE.
- *
- * STACK_REPEAT also covers the "first sample for a fresh thread,
- * empty stack" case: a new ThreadEntry has prev_stack_depth == 0
- * and a zero-initialized prev_stack, so compare_stacks() returns
- * STACK_REPEAT against an empty curr_stack (depth 0). Buffering
- * it here is correct; the RLE flush path emits it as a normal
- * STACK_REPEAT record. */
- if (entry->pending_rle == NULL) {
- entry->pending_rle = PyMem_Malloc(MAX_RLE_BUF_SIZE);
- if (!entry->pending_rle) {
- PyErr_NoMemory();
- return -1;
- }
- }
- if (entry->pending_rle_bytes + MAX_RLE_ENTRY_SIZE > MAX_RLE_BUF_SIZE
- && flush_pending_rle(writer, entry) < 0) {
- return -1;
- }
- entry->pending_rle_bytes += encode_varint_u64(
- entry->pending_rle + entry->pending_rle_bytes, delta);
- entry->pending_rle[entry->pending_rle_bytes++] = status;
- entry->pending_rle_samples++;
- } else {
- /* Stack changed - flush any pending RLE first */
- if (flush_pending_rle(writer, entry) < 0) {
- return -1;
- }
-
- if (write_sample_with_encoding(writer, entry, delta, status, encoding,
- curr_stack, curr_depth,
- shared_count, pop_count, push_count) < 0) {
- return -1;
- }
-
- memcpy(entry->prev_stack, curr_stack, curr_depth * sizeof(uint32_t));
- entry->prev_stack_depth = curr_depth;
- }
-
- writer->total_samples++;
- return 0;
+ return block_add_sample(
+ writer, entry, timestamp_us, status, curr_stack, curr_depth);
}
int
@@ -1021,15 +1339,16 @@ binary_writer_write_sample(BinaryWriter *writer, PyObject *stack_frames, uint64_
PyObject *interp_id_obj = PyStructSequence_GET_ITEM(interp_info, 0);
PyObject *threads = PyStructSequence_GET_ITEM(interp_info, 1);
- unsigned long interp_id_long = PyLong_AsUnsignedLong(interp_id_obj);
- if (interp_id_long == (unsigned long)-1 && PyErr_Occurred()) {
+ unsigned long long interp_id_long = PyLong_AsUnsignedLongLong(interp_id_obj);
+ if (interp_id_long == (unsigned long long)-1 && PyErr_Occurred()) {
return -1;
}
/* Bounds check: interpreter_id is stored as uint32_t in binary format */
if (interp_id_long > UINT32_MAX) {
+ writer->state = BINARY_WRITER_LIMIT_REACHED;
PyErr_Format(PyExc_OverflowError,
- "interpreter_id %lu exceeds maximum value %lu",
- interp_id_long, (unsigned long)UINT32_MAX);
+ "interpreter_id %llu exceeds maximum value %u",
+ interp_id_long, UINT32_MAX);
return -1;
}
uint32_t interpreter_id = (uint32_t)interp_id_long;
@@ -1049,46 +1368,10 @@ binary_writer_write_sample(BinaryWriter *writer, PyObject *stack_frames, uint64_
int
binary_writer_finalize(BinaryWriter *writer)
{
- for (size_t i = 0; i < writer->thread_count; i++) {
- if (flush_pending_rle(writer, &writer->thread_entries[i]) < 0) {
- return -1;
- }
- }
-
- if (writer_flush_buffer(writer) < 0) {
+ if (block_flush(writer) < 0) {
return -1;
}
-#ifdef HAVE_ZSTD
- /* Finalize compression stream */
- if (writer->compression_type == COMPRESSION_ZSTD && writer->zstd.cctx) {
- ZSTD_inBuffer input = { NULL, 0, 0 };
- size_t remaining;
-
- do {
- ZSTD_outBuffer output = {
- writer->zstd.compressed_buffer,
- writer->zstd.compressed_buffer_size,
- 0
- };
-
- remaining = ZSTD_compressStream2(writer->zstd.cctx, &output, &input, ZSTD_e_end);
-
- if (ZSTD_isError(remaining)) {
- PyErr_Format(PyExc_IOError, "zstd finalization error: %s",
- ZSTD_getErrorName(remaining));
- return -1;
- }
-
- if (output.pos > 0) {
- if (fwrite_checked_allow_threads(writer->zstd.compressed_buffer, output.pos, writer->fp) < 0) {
- return -1;
- }
- }
- } while (remaining > 0);
- }
-#endif
-
/* Use 64-bit file position for >2GB files */
file_offset_t string_table_offset = FTELL64(writer->fp);
if (string_table_offset < 0) {
@@ -1146,6 +1429,30 @@ binary_writer_finalize(BinaryWriter *writer)
}
}
+ if (writer->has_profile_stats) {
+ uint8_t profile_stats[PROFILE_STATS_SIZE] = {0};
+ uint32_t version = PROFILE_STATS_VERSION;
+ uint32_t size = PROFILE_STATS_SIZE;
+ memcpy(profile_stats + PST_OFF_DURATION,
+ &writer->duration_sec, PST_SIZE_DURATION);
+ memcpy(profile_stats + PST_OFF_SAMPLE_RATE,
+ &writer->sample_rate, PST_SIZE_SAMPLE_RATE);
+ memcpy(profile_stats + PST_OFF_ERROR_RATE,
+ &writer->error_rate, PST_SIZE_ERROR_RATE);
+ memcpy(profile_stats + PST_OFF_MISSED_SAMPLES,
+ &writer->missed_samples, PST_SIZE_MISSED_SAMPLES);
+ memcpy(profile_stats + PST_OFF_PRESENT,
+ &writer->profile_stats_present, PST_SIZE_PRESENT);
+ memcpy(profile_stats + PST_OFF_MAGIC,
+ PROFILE_STATS_MAGIC, PROFILE_STATS_MAGIC_SIZE);
+ memcpy(profile_stats + PST_OFF_VERSION, &version, PST_SIZE_VERSION);
+ memcpy(profile_stats + PST_OFF_SIZE, &size, PST_SIZE_SIZE);
+ if (fwrite_checked_allow_threads(
+ profile_stats, PROFILE_STATS_SIZE, writer->fp) < 0) {
+ return -1;
+ }
+ }
+
/* Footer: string_count(4) + frame_count(4) + file_size(8) + checksum(16) */
file_offset_t footer_offset = FTELL64(writer->fp);
if (footer_offset < 0) {
@@ -1177,6 +1484,12 @@ binary_writer_finalize(BinaryWriter *writer)
uint64_t frame_table_offset_u64 = (uint64_t)frame_table_offset;
uint32_t thread_count_u32 = (uint32_t)writer->thread_count;
uint32_t compression_type_u32 = (uint32_t)writer->compression_type;
+ uint32_t profiling_config_u32 = (uint32_t)(writer->profiling_mode + 1);
+ if (writer->capture_features >= 0) {
+ profiling_config_u32 |= PROFILING_CONFIG_FEATURES_KNOWN;
+ profiling_config_u32 |= (uint32_t)writer->capture_features
+ << PROFILING_CONFIG_FEATURES_SHIFT;
+ }
uint8_t header[FILE_HEADER_SIZE] = {0};
uint32_t magic = BINARY_FORMAT_MAGIC;
@@ -1193,6 +1506,7 @@ binary_writer_finalize(BinaryWriter *writer)
memcpy(header + HDR_OFF_STR_TABLE, &string_table_offset_u64, HDR_SIZE_STR_TABLE);
memcpy(header + HDR_OFF_FRAME_TABLE, &frame_table_offset_u64, HDR_SIZE_FRAME_TABLE);
memcpy(header + HDR_OFF_COMPRESSION, &compression_type_u32, HDR_SIZE_COMPRESSION);
+ memcpy(header + HDR_OFF_CONFIG, &profiling_config_u32, HDR_SIZE_CONFIG);
if (fwrite_checked_allow_threads(header, FILE_HEADER_SIZE, writer->fp) < 0) {
return -1;
}
@@ -1207,6 +1521,41 @@ binary_writer_finalize(BinaryWriter *writer)
return 0;
}
+int
+binary_writer_set_stats(BinaryWriter *writer, double duration_sec,
+ double sample_rate, double error_rate,
+ double missed_samples, uint32_t present)
+{
+ if (!isfinite(duration_sec) || duration_sec < 0.0) {
+ PyErr_SetString(PyExc_ValueError,
+ "duration must be a finite non-negative value");
+ return -1;
+ }
+ if (!isfinite(sample_rate) || sample_rate < 0.0) {
+ PyErr_SetString(PyExc_ValueError,
+ "sample rate must be a finite non-negative value");
+ return -1;
+ }
+ if ((present & PROFILE_STATS_ERROR_RATE) &&
+ (!isfinite(error_rate) || error_rate < 0.0)) {
+ PyErr_SetString(PyExc_ValueError,
+ "error rate must be a finite non-negative value");
+ return -1;
+ }
+ if ((present & PROFILE_STATS_MISSED) && !isfinite(missed_samples)) {
+ PyErr_SetString(PyExc_ValueError,
+ "missed samples must be a finite value");
+ return -1;
+ }
+ writer->duration_sec = duration_sec;
+ writer->sample_rate = sample_rate;
+ writer->error_rate = error_rate;
+ writer->missed_samples = missed_samples;
+ writer->profile_stats_present = present;
+ writer->has_profile_stats = 1;
+ return 0;
+}
+
void
binary_writer_destroy(BinaryWriter *writer)
{
@@ -1218,13 +1567,12 @@ binary_writer_destroy(BinaryWriter *writer)
Py_fclose(writer->fp);
}
- PyMem_Free(writer->write_buffer);
+ block_destroy(writer->block);
#ifdef HAVE_ZSTD
if (writer->zstd.cctx) {
ZSTD_freeCCtx(writer->zstd.cctx);
}
- PyMem_Free(writer->zstd.compressed_buffer);
#endif
if (writer->string_hash) {
@@ -1243,13 +1591,7 @@ binary_writer_destroy(BinaryWriter *writer)
}
PyMem_Free(writer->frame_entries);
- if (writer->thread_entries) {
- for (size_t i = 0; i < writer->thread_count; i++) {
- PyMem_Free(writer->thread_entries[i].prev_stack);
- PyMem_Free(writer->thread_entries[i].pending_rle);
- }
- PyMem_Free(writer->thread_entries);
- }
+ PyMem_Free(writer->thread_entries);
PyMem_Free(writer);
}
diff --git a/Modules/_remote_debugging/clinic/module.c.h b/Modules/_remote_debugging/clinic/module.c.h
index d01f3d13e85f09f..26e4a3c2c2e84be 100644
--- a/Modules/_remote_debugging/clinic/module.c.h
+++ b/Modules/_remote_debugging/clinic/module.c.h
@@ -56,7 +56,7 @@ PyDoc_STRVAR(_remote_debugging_RemoteUnwinder___init____doc__,
static int
_remote_debugging_RemoteUnwinder___init___impl(RemoteUnwinderObject *self,
- int pid, int all_threads,
+ pid_t pid, int all_threads,
int only_active_thread,
int mode, int debug,
int skip_non_matching_threads,
@@ -99,7 +99,7 @@ _remote_debugging_RemoteUnwinder___init__(PyObject *self, PyObject *args, PyObje
PyObject * const *fastargs;
Py_ssize_t nargs = PyTuple_GET_SIZE(args);
Py_ssize_t noptargs = nargs + (kwargs ? PyDict_GET_SIZE(kwargs) : 0) - 1;
- int pid;
+ pid_t pid;
int all_threads = 0;
int only_active_thread = 0;
int mode = 0;
@@ -116,8 +116,8 @@ _remote_debugging_RemoteUnwinder___init__(PyObject *self, PyObject *args, PyObje
if (!fastargs) {
goto exit;
}
- pid = PyLong_AsInt(fastargs[0]);
- if (pid == -1 && PyErr_Occurred()) {
+ pid = PyLong_AsPid(fastargs[0]);
+ if (pid == (pid_t)(-1) && PyErr_Occurred()) {
goto exit;
}
if (!noptargs) {
@@ -288,23 +288,28 @@ PyDoc_STRVAR(_remote_debugging_RemoteUnwinder_get_all_awaited_by__doc__,
"get_all_awaited_by($self, /)\n"
"--\n"
"\n"
-"Get all tasks and their awaited_by relationships from the remote process.\n"
+"Get awaited_by relationships for tasks in the remote process.\n"
"\n"
-"This provides a tree structure showing which tasks are waiting for\n"
-"other tasks.\n"
-"\n"
-"For each task, returns:\n"
-"1. The call stack frames leading to where the task is currently\n"
-" executing\n"
-"2. The name of the task\n"
-"3. A list of tasks that this task is waiting for, with their own\n"
-" frames/names/etc\n"
-"\n"
-"Returns a list of [frames, task_name, subtasks] where:\n"
-"- frames: List of (func_name, filename, lineno) showing the call\n"
-" stack\n"
-"- task_name: String identifier for the task\n"
-"- subtasks: List of tasks being awaited by this task, in same format\n"
+"Returns:\n"
+" A list of AwaitedInfo objects, where each object contains:\n"
+"\n"
+" - thread_id (int): Identifier of the thread, or 0 for tasks in the\n"
+" interpreter\'s fallback task list.\n"
+" - awaited_by (list[TaskInfo]): Tasks registered with this thread and\n"
+" intermediate futures in their awaited_by chains.\n"
+"\n"
+"Each TaskInfo contains:\n"
+" - task_id (int): Identifier of the task.\n"
+" - task_name (str): Name of the task, or a generated name for\n"
+" a future.\n"
+" - coroutine_stack (list[CoroInfo]): Stack of coroutine frames.\n"
+" - awaited_by (list[CoroInfo]): Coroutine information for tasks or futures\n"
+" awaiting this task.\n"
+" - is_future (bool, named-only): True for a plain Future.\n"
+"\n"
+"Each CoroInfo contains:\n"
+" - call_stack (list[FrameInfo]): Call stack frames for the coroutine.\n"
+" - task_name (int): Identifier of the task or future.\n"
"\n"
"Raises:\n"
" RuntimeError: If AsyncioDebug section is not available in the\n"
@@ -313,20 +318,20 @@ PyDoc_STRVAR(_remote_debugging_RemoteUnwinder_get_all_awaited_by__doc__,
" OSError: If reading from the remote process fails\n"
"\n"
"Example output:\n"
-"[\n"
+"\n"
" [\n"
-" [(\"c5\", \"script.py\", 10), (\"c4\", \"script.py\", 14)],\n"
-" \"c2_root\",\n"
-" [\n"
-" [\n"
-" [(\"c1\", \"script.py\", 23)],\n"
-" \"sub_main_2\",\n"
-" [...]\n"
-" ],\n"
-" [...]\n"
-" ]\n"
-" ]\n"
-"]");
+" AwaitedInfo(\n"
+" thread_id=12345,\n"
+" awaited_by=[\n"
+" TaskInfo(\n"
+" task_id=1,\n"
+" task_name=\"Task-1\",\n"
+" coroutine_stack=[...],\n"
+" awaited_by=[]\n"
+" )\n"
+" ]\n"
+" )\n"
+" ]");
#define _REMOTE_DEBUGGING_REMOTEUNWINDER_GET_ALL_AWAITED_BY_METHODDEF \
{"get_all_awaited_by", (PyCFunction)_remote_debugging_RemoteUnwinder_get_all_awaited_by, METH_NOARGS, _remote_debugging_RemoteUnwinder_get_all_awaited_by__doc__},
@@ -360,16 +365,37 @@ PyDoc_STRVAR(_remote_debugging_RemoteUnwinder_get_async_stack_trace__doc__,
"all tasks that transitively depend on it (tasks waiting for the\n"
"running task, tasks waiting for those tasks, etc.).\n"
"\n"
-"Returns a list of per-thread results, where each thread result\n"
-"contains:\n"
-"- Thread ID\n"
-"- List of task information for the running task and all its waiters\n"
-"\n"
-"Each task info contains:\n"
-"- Task ID (memory address)\n"
-"- Task name\n"
-"- Call stack frames: List of (func_name, filename, lineno)\n"
-"- List of tasks waiting for this task (recursive structure)\n"
+"Returns:\n"
+" A list of AwaitedInfo objects, where each object contains:\n"
+"\n"
+" - thread_id (int): Identifier of the thread.\n"
+" - awaited_by (list[TaskInfo]): The running task and all its\n"
+" transitive waiters, including intermediate futures.\n"
+"\n"
+"Each TaskInfo contains:\n"
+" - task_id (int): Identifier of the task.\n"
+" - task_name (str): Name of the task, or a generated name for\n"
+" a future.\n"
+" - coroutine_stack (list[CoroInfo]): Stack of coroutine frames.\n"
+" - awaited_by (list[CoroInfo]): Coroutine information for\n"
+" tasks or futures awaiting this task.\n"
+" - is_future (bool, named-only): True for a plain Future.\n"
+"\n"
+"Each CoroInfo contains:\n"
+" - call_stack (list[FrameInfo]): Frames for the coroutine.\n"
+" - task_name (int): Identifier of the task or future.\n"
+"\n"
+"Each FrameInfo contains:\n"
+" - filename (str): Source code filename.\n"
+" - location (LocationInfo | None): Source location, if available.\n"
+" - funcname (str): Function name.\n"
+" - opcode (int | None): Opcode, if available.\n"
+"\n"
+"Each LocationInfo contains:\n"
+" - lineno (int): Starting line number.\n"
+" - end_lineno (int): Ending line number.\n"
+" - col_offset (int): Starting column offset.\n"
+" - end_col_offset (int): Ending column offset.\n"
"\n"
"Raises:\n"
" RuntimeError: If AsyncioDebug section is not available in the\n"
@@ -377,18 +403,30 @@ PyDoc_STRVAR(_remote_debugging_RemoteUnwinder_get_async_stack_trace__doc__,
" MemoryError: If memory allocation fails\n"
" OSError: If reading from the remote process fails\n"
"\n"
-"Example output (similar structure to get_all_awaited_by but only for\n"
-"running tasks):\n"
-"[\n"
-" (140234, [\n"
-" (4345585712, \'main_task\',\n"
-" [(\"run_server\", \"server.py\", 127), (\"main\", \"app.py\", 23)],\n"
-" [\n"
-" (4345585800, \'worker_1\', [...], [...]),\n"
-" (4345585900, \'worker_2\', [...], [...])\n"
-" ])\n"
-" ])\n"
-"]");
+"Example output:\n"
+"\n"
+" [\n"
+" AwaitedInfo(thread_id=140234, awaited_by=[\n"
+" TaskInfo(\n"
+" task_id=1,\n"
+" task_name=\"worker\",\n"
+" coroutine_stack=[\n"
+" CoroInfo(call_stack=[...], task_name=1)\n"
+" ],\n"
+" awaited_by=[\n"
+" CoroInfo(call_stack=[...], task_name=2)\n"
+" ]\n"
+" ),\n"
+" TaskInfo(\n"
+" task_id=2,\n"
+" task_name=\"main\",\n"
+" coroutine_stack=[\n"
+" CoroInfo(call_stack=[...], task_name=2)\n"
+" ],\n"
+" awaited_by=[]\n"
+" )\n"
+" ])\n"
+" ]");
#define _REMOTE_DEBUGGING_REMOTEUNWINDER_GET_ASYNC_STACK_TRACE_METHODDEF \
{"get_async_stack_trace", (PyCFunction)_remote_debugging_RemoteUnwinder_get_async_stack_trace, METH_NOARGS, _remote_debugging_RemoteUnwinder_get_async_stack_trace__doc__},
@@ -559,7 +597,7 @@ PyDoc_STRVAR(_remote_debugging_GCMonitor___init____doc__,
" target process");
static int
-_remote_debugging_GCMonitor___init___impl(GCMonitorObject *self, int pid,
+_remote_debugging_GCMonitor___init___impl(GCMonitorObject *self, pid_t pid,
int debug);
static int
@@ -597,7 +635,7 @@ _remote_debugging_GCMonitor___init__(PyObject *self, PyObject *args, PyObject *k
PyObject * const *fastargs;
Py_ssize_t nargs = PyTuple_GET_SIZE(args);
Py_ssize_t noptargs = nargs + (kwargs ? PyDict_GET_SIZE(kwargs) : 0) - 1;
- int pid;
+ pid_t pid;
int debug = 0;
fastargs = _PyArg_UnpackKeywords(_PyTuple_CAST(args)->ob_item, nargs, kwargs, NULL, &_parser,
@@ -605,8 +643,8 @@ _remote_debugging_GCMonitor___init__(PyObject *self, PyObject *args, PyObject *k
if (!fastargs) {
goto exit;
}
- pid = PyLong_AsInt(fastargs[0]);
- if (pid == -1 && PyErr_Occurred()) {
+ pid = PyLong_AsPid(fastargs[0]);
+ if (pid == (pid_t)(-1) && PyErr_Occurred()) {
goto exit;
}
if (!noptargs) {
@@ -717,7 +755,7 @@ _remote_debugging_GCMonitor_get_gc_stats(PyObject *self, PyObject *const *args,
PyDoc_STRVAR(_remote_debugging_BinaryWriter___init____doc__,
"BinaryWriter(filename, sample_interval_us, start_time_us, *,\n"
-" compression=0)\n"
+" compression=0, mode=-1, capture_features=-1)\n"
"--\n"
"\n"
"High-performance binary writer for profiling data.\n"
@@ -728,6 +766,9 @@ PyDoc_STRVAR(_remote_debugging_BinaryWriter___init____doc__,
" start_time_us: Start timestamp in microseconds (from\n"
" time.monotonic() * 1e6)\n"
" compression: 0=none, 1=zstd (default: 0)\n"
+" mode: Profiling mode, or -1 if unknown (default: -1)\n"
+" capture_features: Capture feature bit mask, or -1 if unknown\n"
+" (default: -1)\n"
"\n"
"Use as a context manager or call finalize() when done.");
@@ -736,7 +777,8 @@ _remote_debugging_BinaryWriter___init___impl(BinaryWriterObject *self,
PyObject *filename,
unsigned long long sample_interval_us,
unsigned long long start_time_us,
- int compression);
+ int compression, int mode,
+ int capture_features);
static int
_remote_debugging_BinaryWriter___init__(PyObject *self, PyObject *args, PyObject *kwargs)
@@ -744,7 +786,7 @@ _remote_debugging_BinaryWriter___init__(PyObject *self, PyObject *args, PyObject
int return_value = -1;
#if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
- #define NUM_KEYWORDS 4
+ #define NUM_KEYWORDS 6
static struct {
PyGC_Head _this_is_not_used;
PyObject_VAR_HEAD
@@ -753,7 +795,7 @@ _remote_debugging_BinaryWriter___init__(PyObject *self, PyObject *args, PyObject
} _kwtuple = {
.ob_base = PyVarObject_HEAD_INIT(&PyTuple_Type, NUM_KEYWORDS)
.ob_hash = -1,
- .ob_item = { &_Py_ID(filename), &_Py_ID(sample_interval_us), &_Py_ID(start_time_us), &_Py_ID(compression), },
+ .ob_item = { &_Py_ID(filename), &_Py_ID(sample_interval_us), &_Py_ID(start_time_us), &_Py_ID(compression), &_Py_ID(mode), &_Py_ID(capture_features), },
};
#undef NUM_KEYWORDS
#define KWTUPLE (&_kwtuple.ob_base.ob_base)
@@ -762,14 +804,14 @@ _remote_debugging_BinaryWriter___init__(PyObject *self, PyObject *args, PyObject
# define KWTUPLE NULL
#endif // !Py_BUILD_CORE
- static const char * const _keywords[] = {"filename", "sample_interval_us", "start_time_us", "compression", NULL};
+ static const char * const _keywords[] = {"filename", "sample_interval_us", "start_time_us", "compression", "mode", "capture_features", NULL};
static _PyArg_Parser _parser = {
.keywords = _keywords,
.fname = "BinaryWriter",
.kwtuple = KWTUPLE,
};
#undef KWTUPLE
- PyObject *argsbuf[4];
+ PyObject *argsbuf[6];
PyObject * const *fastargs;
Py_ssize_t nargs = PyTuple_GET_SIZE(args);
Py_ssize_t noptargs = nargs + (kwargs ? PyDict_GET_SIZE(kwargs) : 0) - 3;
@@ -777,6 +819,8 @@ _remote_debugging_BinaryWriter___init__(PyObject *self, PyObject *args, PyObject
unsigned long long sample_interval_us;
unsigned long long start_time_us;
int compression = 0;
+ int mode = -1;
+ int capture_features = -1;
fastargs = _PyArg_UnpackKeywords(_PyTuple_CAST(args)->ob_item, nargs, kwargs, NULL, &_parser,
/*minpos*/ 3, /*maxpos*/ 3, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
@@ -793,12 +837,30 @@ _remote_debugging_BinaryWriter___init__(PyObject *self, PyObject *args, PyObject
if (!noptargs) {
goto skip_optional_kwonly;
}
- compression = PyLong_AsInt(fastargs[3]);
- if (compression == -1 && PyErr_Occurred()) {
+ if (fastargs[3]) {
+ compression = PyLong_AsInt(fastargs[3]);
+ if (compression == -1 && PyErr_Occurred()) {
+ goto exit;
+ }
+ if (!--noptargs) {
+ goto skip_optional_kwonly;
+ }
+ }
+ if (fastargs[4]) {
+ mode = PyLong_AsInt(fastargs[4]);
+ if (mode == -1 && PyErr_Occurred()) {
+ goto exit;
+ }
+ if (!--noptargs) {
+ goto skip_optional_kwonly;
+ }
+ }
+ capture_features = PyLong_AsInt(fastargs[5]);
+ if (capture_features == -1 && PyErr_Occurred()) {
goto exit;
}
skip_optional_kwonly:
- return_value = _remote_debugging_BinaryWriter___init___impl((BinaryWriterObject *)self, filename, sample_interval_us, start_time_us, compression);
+ return_value = _remote_debugging_BinaryWriter___init___impl((BinaryWriterObject *)self, filename, sample_interval_us, start_time_us, compression, mode, capture_features);
exit:
return return_value;
@@ -873,6 +935,103 @@ _remote_debugging_BinaryWriter_write_sample(PyObject *self, PyObject *const *arg
return return_value;
}
+PyDoc_STRVAR(_remote_debugging_BinaryWriter_set_stats__doc__,
+"set_stats($self, /, duration_sec, sample_rate, error_rate=None,\n"
+" missed_samples=None)\n"
+"--\n"
+"\n"
+"Store measured profile statistics in the binary file.");
+
+#define _REMOTE_DEBUGGING_BINARYWRITER_SET_STATS_METHODDEF \
+ {"set_stats", _PyCFunction_CAST(_remote_debugging_BinaryWriter_set_stats), METH_FASTCALL|METH_KEYWORDS, _remote_debugging_BinaryWriter_set_stats__doc__},
+
+static PyObject *
+_remote_debugging_BinaryWriter_set_stats_impl(BinaryWriterObject *self,
+ double duration_sec,
+ double sample_rate,
+ PyObject *error_rate,
+ PyObject *missed_samples);
+
+static PyObject *
+_remote_debugging_BinaryWriter_set_stats(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
+{
+ PyObject *return_value = NULL;
+ #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
+
+ #define NUM_KEYWORDS 4
+ static struct {
+ PyGC_Head _this_is_not_used;
+ PyObject_VAR_HEAD
+ Py_hash_t ob_hash;
+ PyObject *ob_item[NUM_KEYWORDS];
+ } _kwtuple = {
+ .ob_base = PyVarObject_HEAD_INIT(&PyTuple_Type, NUM_KEYWORDS)
+ .ob_hash = -1,
+ .ob_item = { &_Py_ID(duration_sec), &_Py_ID(sample_rate), &_Py_ID(error_rate), &_Py_ID(missed_samples), },
+ };
+ #undef NUM_KEYWORDS
+ #define KWTUPLE (&_kwtuple.ob_base.ob_base)
+
+ #else // !Py_BUILD_CORE
+ # define KWTUPLE NULL
+ #endif // !Py_BUILD_CORE
+
+ static const char * const _keywords[] = {"duration_sec", "sample_rate", "error_rate", "missed_samples", NULL};
+ static _PyArg_Parser _parser = {
+ .keywords = _keywords,
+ .fname = "set_stats",
+ .kwtuple = KWTUPLE,
+ };
+ #undef KWTUPLE
+ PyObject *argsbuf[4];
+ Py_ssize_t noptargs = nargs + (kwnames ? PyTuple_GET_SIZE(kwnames) : 0) - 2;
+ double duration_sec;
+ double sample_rate;
+ PyObject *error_rate = Py_None;
+ PyObject *missed_samples = Py_None;
+
+ args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
+ /*minpos*/ 2, /*maxpos*/ 4, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
+ if (!args) {
+ goto exit;
+ }
+ if (PyFloat_CheckExact(args[0])) {
+ duration_sec = PyFloat_AS_DOUBLE(args[0]);
+ }
+ else
+ {
+ duration_sec = PyFloat_AsDouble(args[0]);
+ if (duration_sec == -1.0 && PyErr_Occurred()) {
+ goto exit;
+ }
+ }
+ if (PyFloat_CheckExact(args[1])) {
+ sample_rate = PyFloat_AS_DOUBLE(args[1]);
+ }
+ else
+ {
+ sample_rate = PyFloat_AsDouble(args[1]);
+ if (sample_rate == -1.0 && PyErr_Occurred()) {
+ goto exit;
+ }
+ }
+ if (!noptargs) {
+ goto skip_optional_pos;
+ }
+ if (args[2]) {
+ error_rate = args[2];
+ if (!--noptargs) {
+ goto skip_optional_pos;
+ }
+ }
+ missed_samples = args[3];
+skip_optional_pos:
+ return_value = _remote_debugging_BinaryWriter_set_stats_impl((BinaryWriterObject *)self, duration_sec, sample_rate, error_rate, missed_samples);
+
+exit:
+ return return_value;
+}
+
PyDoc_STRVAR(_remote_debugging_BinaryWriter_finalize__doc__,
"finalize($self, /)\n"
"--\n"
@@ -1016,7 +1175,7 @@ PyDoc_STRVAR(_remote_debugging_BinaryWriter_get_stats__doc__,
"Get encoding statistics for the writer.\n"
"\n"
"Returns a dict with encoding statistics including\n"
-"repeat/full/suffix/pop-push record counts, frames written/saved, and\n"
+"repeat/full/suffix/reuse record counts, frames written/saved, and\n"
"compression ratio.");
#define _REMOTE_DEBUGGING_BINARYWRITER_GET_STATS_METHODDEF \
@@ -1374,7 +1533,7 @@ PyDoc_STRVAR(_remote_debugging_get_child_pids__doc__,
{"get_child_pids", _PyCFunction_CAST(_remote_debugging_get_child_pids), METH_FASTCALL|METH_KEYWORDS, _remote_debugging_get_child_pids__doc__},
static PyObject *
-_remote_debugging_get_child_pids_impl(PyObject *module, int pid,
+_remote_debugging_get_child_pids_impl(PyObject *module, pid_t pid,
int recursive);
static PyObject *
@@ -1410,7 +1569,7 @@ _remote_debugging_get_child_pids(PyObject *module, PyObject *const *args, Py_ssi
#undef KWTUPLE
PyObject *argsbuf[2];
Py_ssize_t noptargs = nargs + (kwnames ? PyTuple_GET_SIZE(kwnames) : 0) - 1;
- int pid;
+ pid_t pid;
int recursive = 1;
args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
@@ -1418,8 +1577,8 @@ _remote_debugging_get_child_pids(PyObject *module, PyObject *const *args, Py_ssi
if (!args) {
goto exit;
}
- pid = PyLong_AsInt(args[0]);
- if (pid == -1 && PyErr_Occurred()) {
+ pid = PyLong_AsPid(args[0]);
+ if (pid == (pid_t)(-1) && PyErr_Occurred()) {
goto exit;
}
if (!noptargs) {
@@ -1446,7 +1605,7 @@ PyDoc_STRVAR(_remote_debugging_is_python_process__doc__,
{"is_python_process", _PyCFunction_CAST(_remote_debugging_is_python_process), METH_FASTCALL|METH_KEYWORDS, _remote_debugging_is_python_process__doc__},
static PyObject *
-_remote_debugging_is_python_process_impl(PyObject *module, int pid);
+_remote_debugging_is_python_process_impl(PyObject *module, pid_t pid);
static PyObject *
_remote_debugging_is_python_process(PyObject *module, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
@@ -1480,15 +1639,15 @@ _remote_debugging_is_python_process(PyObject *module, PyObject *const *args, Py_
};
#undef KWTUPLE
PyObject *argsbuf[1];
- int pid;
+ pid_t pid;
args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
/*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
if (!args) {
goto exit;
}
- pid = PyLong_AsInt(args[0]);
- if (pid == -1 && PyErr_Occurred()) {
+ pid = PyLong_AsPid(args[0]);
+ if (pid == (pid_t)(-1) && PyErr_Occurred()) {
goto exit;
}
return_value = _remote_debugging_is_python_process_impl(module, pid);
@@ -1527,7 +1686,7 @@ PyDoc_STRVAR(_remote_debugging_get_gc_stats__doc__,
{"get_gc_stats", _PyCFunction_CAST(_remote_debugging_get_gc_stats), METH_FASTCALL|METH_KEYWORDS, _remote_debugging_get_gc_stats__doc__},
static PyObject *
-_remote_debugging_get_gc_stats_impl(PyObject *module, int pid,
+_remote_debugging_get_gc_stats_impl(PyObject *module, pid_t pid,
int all_interpreters);
static PyObject *
@@ -1563,7 +1722,7 @@ _remote_debugging_get_gc_stats(PyObject *module, PyObject *const *args, Py_ssize
#undef KWTUPLE
PyObject *argsbuf[2];
Py_ssize_t noptargs = nargs + (kwnames ? PyTuple_GET_SIZE(kwnames) : 0) - 1;
- int pid;
+ pid_t pid;
int all_interpreters = 0;
args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
@@ -1571,8 +1730,8 @@ _remote_debugging_get_gc_stats(PyObject *module, PyObject *const *args, Py_ssize
if (!args) {
goto exit;
}
- pid = PyLong_AsInt(args[0]);
- if (pid == -1 && PyErr_Occurred()) {
+ pid = PyLong_AsPid(args[0]);
+ if (pid == (pid_t)(-1) && PyErr_Occurred()) {
goto exit;
}
if (!noptargs) {
@@ -1588,4 +1747,4 @@ _remote_debugging_get_gc_stats(PyObject *module, PyObject *const *args, Py_ssize
exit:
return return_value;
}
-/*[clinic end generated code: output=a3df14a6ab7f2998 input=a9049054013a1b77]*/
+/*[clinic end generated code: output=2be4cb3f27f6c8d8 input=a9049054013a1b77]*/
diff --git a/Modules/_remote_debugging/code_objects.c b/Modules/_remote_debugging/code_objects.c
index ab889a130ee4e7e..081aaa49fb49ffb 100644
--- a/Modules/_remote_debugging/code_objects.c
+++ b/Modules/_remote_debugging/code_objects.c
@@ -7,6 +7,8 @@
#include "_remote_debugging.h"
+#define MAX_LINETABLE_SIZE (64 * 1024)
+
/* ============================================================================
* TLBC CACHING FUNCTIONS (Py_GIL_DISABLED only)
* ============================================================================ */
@@ -30,9 +32,12 @@ get_tlbc_cache_entry(RemoteUnwinderObject *self, uintptr_t code_addr, uint32_t c
TLBCCacheEntry *entry = _Py_hashtable_get(self->tlbc_cache, key);
if (entry && entry->generation != current_generation) {
- // Entry is stale, remove it by setting to NULL
- _Py_hashtable_set(self->tlbc_cache, key, NULL);
- entry = NULL;
+ // Entry is stale, remove it from the cache and destroy it
+ TLBCCacheEntry *old = _Py_hashtable_steal(self->tlbc_cache, key);
+ if (old != NULL) {
+ tlbc_cache_entry_destroy(old);
+ }
+ return NULL;
}
return entry;
@@ -186,11 +191,7 @@ parse_linetable(const uintptr_t addrq, const char* linetable, Py_ssize_t linetab
int computed_line = firstlineno; // Running accumulator, separate from output
int val; // Temporary for varint results
uint8_t byte; // Temporary for byte reads
- const size_t MAX_LINETABLE_ENTRIES = 65536;
- size_t entry_count = 0;
-
- while (ptr < end && *ptr != '\0' && entry_count < MAX_LINETABLE_ENTRIES) {
- entry_count++;
+ while (ptr < end && *ptr != '\0') {
uint8_t first_byte = *(ptr++);
uint8_t code = (first_byte >> 3) & 15;
size_t length = (first_byte & 7) + 1;
@@ -340,11 +341,16 @@ parse_code_object(RemoteUnwinderObject *unwinder,
PyObject **result,
const CodeObjectContext *ctx)
{
+ _Py_DECLARE_STR(unknown_function, "");
+ _Py_DECLARE_STR(unknown_file, "");
+ _Py_DECLARE_STR(unreadable_frame, "");
+
void *key = (void *)ctx->code_addr;
CachedCodeMetadata *meta = NULL;
PyObject *func = NULL;
PyObject *file = NULL;
PyObject *linetable = NULL;
+ int code_metadata_incomplete = 0;
#ifdef Py_GIL_DISABLED
// In free threading builds, code object addresses might have the low bit set
@@ -368,29 +374,50 @@ parse_code_object(RemoteUnwinderObject *unwinder,
if (_Py_RemoteDebug_PagedReadRemoteMemory(
&unwinder->handle, real_address, SIZEOF_CODE_OBJ, code_object) < 0)
{
- set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to read code object");
- goto error;
+ if (_Py_RemoteDebug_IsFatalReadError()) {
+ goto error;
+ }
+ PyErr_Clear();
+ func = Py_NewRef(&_Py_STR(unreadable_frame));
+ file = Py_NewRef(_Py_LATIN1_CHR('~'));
+ goto degraded;
}
func = read_py_str(unwinder,
GET_MEMBER(uintptr_t, code_object, unwinder->debug_offsets.code_object.qualname), 1024);
if (!func) {
- set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to read function name from code object");
- goto error;
+ if (_Py_RemoteDebug_IsFatalReadError()) {
+ goto error;
+ }
+ PyErr_Clear();
+ func = Py_NewRef(&_Py_STR(unknown_function));
+ code_metadata_incomplete = 1;
}
file = read_py_str(unwinder,
GET_MEMBER(uintptr_t, code_object, unwinder->debug_offsets.code_object.filename), 1024);
if (!file) {
- set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to read filename from code object");
- goto error;
+ if (_Py_RemoteDebug_IsFatalReadError()) {
+ goto error;
+ }
+ PyErr_Clear();
+ file = Py_NewRef(&_Py_STR(unknown_file));
+ code_metadata_incomplete = 1;
+ }
+
+ if (code_metadata_incomplete) {
+ goto degraded;
}
linetable = read_py_bytes(unwinder,
- GET_MEMBER(uintptr_t, code_object, unwinder->debug_offsets.code_object.linetable), 4096);
+ GET_MEMBER(uintptr_t, code_object, unwinder->debug_offsets.code_object.linetable),
+ MAX_LINETABLE_SIZE);
if (!linetable) {
- set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to read linetable from code object");
- goto error;
+ if (_Py_RemoteDebug_IsFatalReadError()) {
+ goto error;
+ }
+ PyErr_Clear();
+ goto degraded;
}
meta = PyMem_RawMalloc(sizeof(CachedCodeMetadata));
@@ -450,6 +477,22 @@ parse_code_object(RemoteUnwinderObject *unwinder,
tlbc_entry = get_tlbc_cache_entry(unwinder, real_address, unwinder->tlbc_generation);
}
+ if (tlbc_entry && ctx->tlbc_index >= 0) {
+ uintptr_t *entries = (uintptr_t *)((char *)tlbc_entry->tlbc_array + sizeof(Py_ssize_t));
+ if (ctx->tlbc_index >= tlbc_entry->tlbc_array_size ||
+ entries[ctx->tlbc_index] == 0) {
+ TLBCCacheEntry *old = _Py_hashtable_steal(unwinder->tlbc_cache, (void *)real_address);
+ if (old != NULL) {
+ tlbc_cache_entry_destroy(old);
+ }
+ if (!cache_tlbc_array(unwinder, real_address, real_address + unwinder->debug_offsets.code_object.co_tlbc,
+ unwinder->tlbc_generation)) {
+ goto error;
+ }
+ tlbc_entry = get_tlbc_cache_entry(unwinder, real_address, unwinder->tlbc_generation);
+ }
+ }
+
// Validate tlbc_index and check TLBC cache
if (tlbc_entry) {
// Validate index bounds (also catches negative values since tlbc_index is signed)
@@ -543,6 +586,18 @@ parse_code_object(RemoteUnwinderObject *unwinder,
*result = tuple;
return 0;
+degraded: {
+ PyObject *degraded_tuple = make_frame_info(unwinder, file, Py_None,
+ func, Py_None);
+ Py_CLEAR(func);
+ Py_CLEAR(file);
+ if (!degraded_tuple) {
+ return -1;
+ }
+ *result = degraded_tuple;
+ return 0;
+}
+
error:
Py_XDECREF(func);
Py_XDECREF(file);
diff --git a/Modules/_remote_debugging/debug_offsets_validation.h b/Modules/_remote_debugging/debug_offsets_validation.h
index c0c01a0a639e196..66c35e5522a9c7d 100644
--- a/Modules/_remote_debugging/debug_offsets_validation.h
+++ b/Modules/_remote_debugging/debug_offsets_validation.h
@@ -48,6 +48,15 @@ static_assert(
PY_REMOTE_ASYNC_DEBUG_OFFSETS_TOTAL_SIZE,
"Update _remote_debugging validation for _Py_AsyncioModuleDebugOffsets");
+/* Derive unexported offsets from adjacent fields to keep the debug-offset
+ * table compatible across patch releases. */
+static_assert(offsetof(PyThreadState, exc_info) ==
+ offsetof(PyThreadState, current_exception) + sizeof(uintptr_t),
+ "exc_info must immediately follow current_exception");
+static_assert(offsetof(_PyErr_StackItem, previous_item) ==
+ offsetof(_PyErr_StackItem, exc_value) + sizeof(uintptr_t),
+ "previous_item must immediately follow exc_value");
+
/*
* This logic lives in a private header because it is shared by module.c and
* asyncio.c. Keep the helpers static inline so they stay local to those users
@@ -249,6 +258,7 @@ validate_fixed_field(
#define PY_REMOTE_DEBUG_RUNTIME_STATE_FIELDS(APPLY, buffer_size) \
APPLY(runtime_state, interpreters_head, sizeof(uintptr_t), _Alignof(uintptr_t), buffer_size)
+/* current_exception also covers the adjacent exc_info pointer. */
#define PY_REMOTE_DEBUG_THREAD_STATE_FIELDS(APPLY, buffer_size) \
APPLY(thread_state, native_thread_id, sizeof(unsigned long), _Alignof(long), buffer_size); \
APPLY(thread_state, interp, sizeof(uintptr_t), _Alignof(uintptr_t), buffer_size); \
@@ -256,7 +266,7 @@ validate_fixed_field(
APPLY(thread_state, status, FIELD_SIZE(PyThreadState, _status), _Alignof(unsigned int), buffer_size); \
APPLY(thread_state, holds_gil, sizeof(int), _Alignof(int), buffer_size); \
APPLY(thread_state, gil_requested, sizeof(int), _Alignof(int), buffer_size); \
- APPLY(thread_state, current_exception, sizeof(uintptr_t), _Alignof(uintptr_t), buffer_size); \
+ APPLY(thread_state, current_exception, 2 * sizeof(uintptr_t), _Alignof(uintptr_t), buffer_size); \
APPLY(thread_state, thread_id, sizeof(unsigned long), _Alignof(long), buffer_size); \
APPLY(thread_state, next, sizeof(uintptr_t), _Alignof(uintptr_t), buffer_size); \
APPLY(thread_state, current_frame, sizeof(uintptr_t), _Alignof(uintptr_t), buffer_size); \
@@ -351,10 +361,11 @@ _PyRemoteDebug_ValidateDebugOffsetsLayout(struct _Py_DebugOffsets *debug_offsets
PY_REMOTE_DEBUG_THREAD_STATE_FIELDS(
PY_REMOTE_DEBUG_VALIDATE_FIELD,
SIZEOF_THREAD_STATE);
+ /* exc_value also covers the adjacent previous_item pointer. */
PY_REMOTE_DEBUG_VALIDATE_FIXED_FIELD(
err_stackitem,
exc_value,
- sizeof(uintptr_t),
+ 2 * sizeof(uintptr_t),
_Alignof(uintptr_t),
sizeof(_PyErr_StackItem));
PY_REMOTE_DEBUG_VALIDATE_NESTED_FIELD(
diff --git a/Modules/_remote_debugging/frame_cache.c b/Modules/_remote_debugging/frame_cache.c
index 1b2d9a60f408b91..63d1331015a548d 100644
--- a/Modules/_remote_debugging/frame_cache.c
+++ b/Modules/_remote_debugging/frame_cache.c
@@ -318,9 +318,8 @@ frame_cache_store(
// Validate we have a complete stack before caching.
// Only cache if last_frame_visited matches base_frame_addr (the sentinel
// at the bottom of the stack). Note: we use last_frame_visited rather than
- // addrs[num_addrs-1] because the base frame is visited but not added to the
- // addrs array (it returns frame==NULL from is_frame_valid due to
- // owner==FRAME_OWNED_BY_INTERPRETER).
+ // addrs[num_addrs-1] because the base frame's address is not added to the
+ // addrs array.
if (base_frame_addr != 0 && last_frame_visited != base_frame_addr) {
// Incomplete stack - don't cache (graceful degradation)
return 0;
diff --git a/Modules/_remote_debugging/frames.c b/Modules/_remote_debugging/frames.c
index 46968acc6ff1feb..3f8d628a6314e6e 100644
--- a/Modules/_remote_debugging/frames.c
+++ b/Modules/_remote_debugging/frames.c
@@ -36,7 +36,7 @@ process_single_stack_chunk(
return -1;
}
- if (_Py_RemoteDebug_PagedReadRemoteMemory(&unwinder->handle, chunk_addr, current_size, this_chunk) < 0) {
+ if (_Py_RemoteDebug_ReadRemoteMemory(&unwinder->handle, chunk_addr, current_size, this_chunk) < 0) {
PyMem_RawFree(this_chunk);
set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to read stack chunk");
return -1;
@@ -65,7 +65,7 @@ process_single_stack_chunk(
}
this_chunk = tmp;
- if (_Py_RemoteDebug_PagedReadRemoteMemory(&unwinder->handle, chunk_addr, actual_size, this_chunk) < 0) {
+ if (_Py_RemoteDebug_ReadRemoteMemory(&unwinder->handle, chunk_addr, actual_size, this_chunk) < 0) {
PyMem_RawFree(this_chunk);
set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to reread stack chunk with correct size");
return -1;
@@ -163,6 +163,8 @@ find_frame_in_chunks(StackChunkList *chunks, uintptr_t remote_ptr)
* FRAME PARSING FUNCTIONS
* ============================================================================ */
+enum { FRAME_PARSE_INTERPRETER = 2 };
+
int
is_frame_valid(
RemoteUnwinderObject *unwinder,
@@ -170,14 +172,14 @@ is_frame_valid(
uintptr_t code_object_addr
) {
if ((void*)code_object_addr == NULL) {
- return 0;
+ return 0; // Frame being cleared
}
void* frame = (void*)frame_addr;
char owner = GET_MEMBER(char, frame, unwinder->debug_offsets.interpreter_frame.owner);
if (owner == FRAME_OWNED_BY_INTERPRETER) {
- return 0; // C frame or sentinel base frame
+ return FRAME_PARSE_INTERPRETER; // C frame or sentinel base frame
}
if (owner != FRAME_OWNED_BY_GENERATOR && owner != FRAME_OWNED_BY_THREAD) {
@@ -193,11 +195,8 @@ parse_frame_buffer(
RemoteUnwinderObject *unwinder,
PyObject** result,
const char *frame,
- uintptr_t* address_of_code_object,
uintptr_t* previous_frame
) {
- *address_of_code_object = 0;
-
*previous_frame = GET_MEMBER(uintptr_t, frame, unwinder->debug_offsets.interpreter_frame.previous);
uintptr_t code_object = GET_MEMBER_NO_TAG(uintptr_t, frame, unwinder->debug_offsets.interpreter_frame.executable);
int frame_valid = is_frame_valid(unwinder, (uintptr_t)frame, code_object);
@@ -215,8 +214,6 @@ parse_frame_buffer(
}
#endif
- *address_of_code_object = code_object;
-
CodeObjectContext code_ctx = {
.code_addr = code_object,
.instruction_pointer = instruction_pointer,
@@ -230,7 +227,6 @@ parse_frame_object(
RemoteUnwinderObject *unwinder,
PyObject** result,
uintptr_t address,
- uintptr_t* address_of_code_object,
uintptr_t* previous_frame
) {
char frame[SIZEOF_INTERP_FRAME];
@@ -247,7 +243,7 @@ parse_frame_object(
STATS_INC(unwinder, memory_reads);
STATS_ADD(unwinder, memory_bytes_read, SIZEOF_INTERP_FRAME);
- return parse_frame_buffer(unwinder, result, frame, address_of_code_object, previous_frame);
+ return parse_frame_buffer(unwinder, result, frame, previous_frame);
}
int
@@ -256,41 +252,16 @@ parse_frame_from_chunks(
PyObject **result,
uintptr_t address,
uintptr_t *previous_frame,
- uintptr_t *stackpointer,
StackChunkList *chunks
) {
- void *frame_ptr = find_frame_in_chunks(chunks, address);
- if (!frame_ptr) {
+ const char *frame = find_frame_in_chunks(chunks, address);
+ if (!frame) {
PyErr_Format(PyExc_RuntimeError, "Frame at address 0x%lx not found in stack chunks", address);
set_exception_cause(unwinder, PyExc_RuntimeError, "Frame not found in stack chunks");
return -1;
}
- char *frame = (char *)frame_ptr;
- *previous_frame = GET_MEMBER(uintptr_t, frame, unwinder->debug_offsets.interpreter_frame.previous);
- *stackpointer = GET_MEMBER(uintptr_t, frame, unwinder->debug_offsets.interpreter_frame.stackpointer);
- uintptr_t code_object = GET_MEMBER_NO_TAG(uintptr_t, frame_ptr, unwinder->debug_offsets.interpreter_frame.executable);
- int frame_valid = is_frame_valid(unwinder, (uintptr_t)frame, code_object);
- if (frame_valid != 1) {
- return frame_valid;
- }
-
- uintptr_t instruction_pointer = GET_MEMBER(uintptr_t, frame, unwinder->debug_offsets.interpreter_frame.instr_ptr);
-
- // Get tlbc_index for free threading builds
- int32_t tlbc_index = 0;
-#ifdef Py_GIL_DISABLED
- if (unwinder->debug_offsets.interpreter_frame.tlbc_index != 0) {
- tlbc_index = GET_MEMBER(int32_t, frame, unwinder->debug_offsets.interpreter_frame.tlbc_index);
- }
-#endif
-
- CodeObjectContext code_ctx = {
- .code_addr = code_object,
- .instruction_pointer = instruction_pointer,
- .tlbc_index = tlbc_index,
- };
- return parse_code_object(unwinder, result, &code_ctx);
+ return parse_frame_buffer(unwinder, result, frame, previous_frame);
}
/* ============================================================================
@@ -305,49 +276,51 @@ process_frame_chain(
uintptr_t frame_addr = ctx->frame_addr;
uintptr_t prev_frame_addr = 0;
uintptr_t last_frame_addr = 0;
- const size_t MAX_FRAMES = 1024 + 512;
size_t frame_count = 0;
- assert(MAX_FRAMES > 0 && MAX_FRAMES < 10000);
ctx->stopped_at_cached_frame = 0;
ctx->last_frame_visited = 0;
while ((void*)frame_addr != NULL) {
+ int parse_result = 0;
PyObject *frame = NULL;
uintptr_t next_frame_addr = 0;
- uintptr_t stackpointer = 0;
last_frame_addr = frame_addr;
- if (++frame_count > MAX_FRAMES) {
+ if (++frame_count > MAX_FRAME_CHAIN_DEPTH) {
PyErr_SetString(PyExc_RuntimeError, "Too many stack frames (possible infinite loop)");
set_exception_cause(unwinder, PyExc_RuntimeError, "Frame chain iteration limit exceeded");
return -1;
}
- assert(frame_count <= MAX_FRAMES);
+ assert(frame_count <= MAX_FRAME_CHAIN_DEPTH);
+
+ // The base frame is a sentinel with previous == NULL: reaching it is
+ // enough, no need to read it. Still read it when it is the GC frame
+ // so the marker gets emitted.
+ if (frame_addr == ctx->base_frame_addr
+ && !(unwinder->gc && frame_addr == ctx->gc_frame)) {
+ break;
+ }
if (ctx->chunks && ctx->chunks->count > 0) {
- if (parse_frame_from_chunks(unwinder, &frame, frame_addr, &next_frame_addr, &stackpointer, ctx->chunks) == 0) {
+ parse_result = parse_frame_from_chunks(
+ unwinder, &frame, frame_addr, &next_frame_addr, ctx->chunks);
+ if (parse_result == 0) {
goto parsed_frame;
}
PyErr_Clear();
}
- {
- uintptr_t address_of_code_object = 0;
- int parse_result;
- if (ctx->prefetch.frame && ctx->prefetch.frame_addr == frame_addr) {
- parse_result = parse_frame_buffer(
- unwinder, &frame, ctx->prefetch.frame,
- &address_of_code_object, &next_frame_addr);
- }
- else {
- parse_result = parse_frame_object(
- unwinder, &frame, frame_addr,
- &address_of_code_object, &next_frame_addr);
- }
- if (parse_result < 0) {
- set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to parse frame object in chain");
- return -1;
- }
+ if (ctx->prefetch.frame && ctx->prefetch.frame_addr == frame_addr) {
+ parse_result = parse_frame_buffer(
+ unwinder, &frame, ctx->prefetch.frame, &next_frame_addr);
+ }
+ else {
+ parse_result = parse_frame_object(
+ unwinder, &frame, frame_addr, &next_frame_addr);
+ }
+ if (parse_result < 0) {
+ set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to parse frame object in chain");
+ return -1;
}
parsed_frame:
@@ -358,19 +331,19 @@ process_frame_chain(
continue;
}
- if (frame == NULL && PyList_GET_SIZE(ctx->frame_info) == 0) {
- const char *e = "Failed to parse initial frame in chain";
- PyErr_SetString(PyExc_RuntimeError, e);
- return -1;
- }
PyObject *extra_frame = NULL;
if (unwinder->gc && frame_addr == ctx->gc_frame) {
_Py_DECLARE_STR(gc, "");
extra_frame = &_Py_STR(gc);
}
+ // A leading frame without Python code marks no transition between
+ // Python frames: it is a frame being popped or C code the thread is
+ // returning into.
else if (unwinder->native &&
frame == NULL &&
+ parse_result == FRAME_PARSE_INTERPRETER &&
next_frame_addr &&
+ PyList_GET_SIZE(ctx->frame_info) > 0 &&
!(unwinder->gc && next_frame_addr == ctx->gc_frame))
{
_Py_DECLARE_STR(native, "");
@@ -463,7 +436,7 @@ clear_last_profiled_frames(RemoteUnwinderObject *unwinder)
uintptr_t tstate_addr;
if (_Py_RemoteDebug_PagedReadRemoteMemory(
&unwinder->handle,
- current_interp + unwinder->debug_offsets.interpreter_state.threads_head,
+ current_interp + (uintptr_t)unwinder->debug_offsets.interpreter_state.threads_head,
sizeof(void*),
&tstate_addr) < 0) {
// Non-fatal: just skip clearing
@@ -484,7 +457,7 @@ clear_last_profiled_frames(RemoteUnwinderObject *unwinder)
// Move to next thread
if (_Py_RemoteDebug_PagedReadRemoteMemory(
&unwinder->handle,
- tstate_addr + unwinder->debug_offsets.thread_state.next,
+ tstate_addr + (uintptr_t)unwinder->debug_offsets.thread_state.next,
sizeof(void*),
&tstate_addr) < 0) {
PyErr_Clear();
@@ -495,7 +468,7 @@ clear_last_profiled_frames(RemoteUnwinderObject *unwinder)
// Move to next interpreter
if (_Py_RemoteDebug_PagedReadRemoteMemory(
&unwinder->handle,
- current_interp + unwinder->debug_offsets.interpreter_state.next,
+ current_interp + (uintptr_t)unwinder->debug_offsets.interpreter_state.next,
sizeof(void*),
¤t_interp) < 0) {
PyErr_Clear();
@@ -541,17 +514,16 @@ try_full_cache_hit(
}
PyObject *current_frame = NULL;
- uintptr_t code_object_addr = 0;
uintptr_t previous_frame = 0;
int parse_result;
if (ctx->prefetch.frame && ctx->prefetch.frame_addr == ctx->frame_addr) {
parse_result = parse_frame_buffer(unwinder, ¤t_frame,
ctx->prefetch.frame,
- &code_object_addr, &previous_frame);
+ &previous_frame);
}
else {
parse_result = parse_frame_object(unwinder, ¤t_frame, ctx->frame_addr,
- &code_object_addr, &previous_frame);
+ &previous_frame);
}
if (parse_result < 0) {
return -1;
diff --git a/Modules/_remote_debugging/gc_stats.c b/Modules/_remote_debugging/gc_stats.c
index d5d05edb8ecf5ee..4dc77803a0a9f3c 100644
--- a/Modules/_remote_debugging/gc_stats.c
+++ b/Modules/_remote_debugging/gc_stats.c
@@ -88,8 +88,8 @@ get_gc_stats_from_interpreter_state(RuntimeOffsets *offsets,
uintptr_t gc_stats_addr = 0;
uintptr_t gc_stats_pointer_address = interpreter_state_addr
- + offsets->debug_offsets.interpreter_state.gc
- + offsets->debug_offsets.gc.generation_stats;
+ + (uintptr_t)offsets->debug_offsets.interpreter_state.gc
+ + (uintptr_t)offsets->debug_offsets.gc.generation_stats;
if (_Py_RemoteDebug_ReadRemoteMemory(&offsets->handle,
gc_stats_pointer_address,
sizeof(gc_stats_addr),
@@ -103,12 +103,42 @@ get_gc_stats_from_interpreter_state(RuntimeOffsets *offsets,
}
struct gc_stats stats;
- if (_Py_RemoteDebug_ReadRemoteMemory(&offsets->handle,
- gc_stats_addr,
- sizeof(stats),
- &stats) < 0) {
- set_exception_cause(offsets, PyExc_RuntimeError, "Failed to read GC state");
- return -1;
+ uintptr_t sequence_address = gc_stats_addr
+ + offsetof(struct gc_stats, update_seq);
+ /* A short GC update may finish before a second attempt. */
+ for (int attempt = 0; attempt < 2; attempt++) {
+ uint32_t before;
+ if (_Py_RemoteDebug_ReadRemoteMemory(&offsets->handle,
+ sequence_address,
+ sizeof(before), &before) < 0) {
+ set_exception_cause(offsets, PyExc_RuntimeError,
+ "Failed to read GC update sequence");
+ return -1;
+ }
+ if (_Py_RemoteDebug_ReadRemoteMemory(&offsets->handle,
+ gc_stats_addr,
+ sizeof(stats),
+ &stats) < 0) {
+ set_exception_cause(offsets, PyExc_RuntimeError, "Failed to read GC state");
+ return -1;
+ }
+
+ uint32_t after;
+ if (_Py_RemoteDebug_ReadRemoteMemory(&offsets->handle,
+ sequence_address,
+ sizeof(after), &after) < 0) {
+ set_exception_cause(offsets, PyExc_RuntimeError,
+ "Failed to read GC update sequence");
+ return -1;
+ }
+ if (before == after && before == stats.update_seq && !(after & 1)) {
+ break;
+ }
+ if (attempt == 1) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "GC stats changed while being read; retry later");
+ return -1;
+ }
}
if (read_gc_stats(&stats, iid, ctx->result,
diff --git a/Modules/_remote_debugging/module.c b/Modules/_remote_debugging/module.c
index adafee97a94ada7..d9d7b61633a106c 100644
--- a/Modules/_remote_debugging/module.c
+++ b/Modules/_remote_debugging/module.c
@@ -34,12 +34,13 @@ static PyStructSequence_Field TaskInfo_fields[] = {
{"task_name", "Task name"},
{"coroutine_stack", "Coroutine call stack"},
{"awaited_by", "Tasks awaiting this task"},
+ {"is_future", "Whether this node is a plain Future rather than a Task"},
{NULL}
};
PyStructSequence_Desc TaskInfo_desc = {
"_remote_debugging.TaskInfo",
- "Information about an asyncio task",
+ "Information about an asyncio task or future",
TaskInfo_fields,
4
};
@@ -281,7 +282,7 @@ class _remote_debugging.RemoteUnwinder "RemoteUnwinderObject *" "&RemoteUnwinder
/*[clinic input]
@permit_long_summary
_remote_debugging.RemoteUnwinder.__init__
- pid: int
+ pid: pid_t
*
all_threads: bool = False
only_active_thread: bool = False
@@ -334,14 +335,14 @@ other runtime data.
static int
_remote_debugging_RemoteUnwinder___init___impl(RemoteUnwinderObject *self,
- int pid, int all_threads,
+ pid_t pid, int all_threads,
int only_active_thread,
int mode, int debug,
int skip_non_matching_threads,
int native, int gc,
int opcodes, int cache_frames,
int stats)
-/*[clinic end generated code: output=0031f743f4b9ad52 input=9d25ae328d62626d]*/
+/*[clinic end generated code: output=acfe554c8a92cf6b input=3b5a5ad153709125]*/
{
// Validate that all_threads and only_active_thread are not both True
if (all_threads && only_active_thread) {
@@ -384,12 +385,6 @@ _remote_debugging_RemoteUnwinder___init___impl(RemoteUnwinderObject *self,
return -1;
}
- self->runtime_start_address = _Py_RemoteDebug_GetPyRuntimeAddress(&self->handle);
- if (self->runtime_start_address == 0) {
- set_exception_cause(self, PyExc_RuntimeError, "Failed to get Python runtime address");
- return -1;
- }
-
if (_Py_RemoteDebug_ReadDebugOffsets(&self->handle,
&self->runtime_start_address,
&self->debug_offsets) < 0)
@@ -404,20 +399,8 @@ _remote_debugging_RemoteUnwinder___init___impl(RemoteUnwinderObject *self,
return -1;
}
- // Try to read async debug offsets, but don't fail if they're not available
- self->async_debug_offsets_available = 1;
- int async_debug_result = read_async_debug(self);
- if (async_debug_result == PY_REMOTE_DEBUG_INVALID_ASYNC_DEBUG_OFFSETS) {
- return -1;
- }
- if (async_debug_result < 0) {
- if (_Py_RemoteDebug_HasPermissionError()) {
- return -1;
- }
- PyErr_Clear();
- memset(&self->async_debug_offsets, 0, sizeof(self->async_debug_offsets));
- self->async_debug_offsets_available = 0;
- }
+ self->async_debug_offsets_available = 0;
+ memset(&self->async_debug_offsets, 0, sizeof(self->async_debug_offsets));
if (populate_initial_state_data(all_threads, self, self->runtime_start_address,
&self->interpreter_addr ,&self->tstate_addr) < 0)
@@ -450,22 +433,12 @@ _remote_debugging_RemoteUnwinder___init___impl(RemoteUnwinderObject *self,
NULL
);
if (self->tlbc_cache == NULL) {
- _Py_hashtable_destroy(self->code_object_cache);
PyErr_NoMemory();
set_exception_cause(self, PyExc_MemoryError, "Failed to create TLBC cache");
return -1;
}
#endif
-#if defined(__APPLE__)
- self->thread_id_offset = 0;
- self->thread_id_offset_initialized = 0;
-#endif
-
-#ifdef MS_WINDOWS
- self->win_process_buffer = NULL;
- self->win_process_buffer_size = 0;
-#endif
#ifdef __linux__
self->thread_tids = NULL;
self->thread_tids_capacity = 0;
@@ -823,6 +796,9 @@ _remote_debugging_RemoteUnwinder_get_stack_trace_impl(RemoteUnwinderObject *self
goto exit;
}
// Thread was skipped due to mode filtering, continue to next thread
+ if (self->tstate_addr || self->only_active_thread) {
+ break;
+ }
continue;
}
// This was an actual error
@@ -904,27 +880,32 @@ _remote_debugging_RemoteUnwinder_get_stack_trace_impl(RemoteUnwinderObject *self
}
/*[clinic input]
-@permit_long_summary
+@permit_long_docstring_body
@critical_section
_remote_debugging.RemoteUnwinder.get_all_awaited_by
-Get all tasks and their awaited_by relationships from the remote process.
+Get awaited_by relationships for tasks in the remote process.
-This provides a tree structure showing which tasks are waiting for
-other tasks.
-
-For each task, returns:
-1. The call stack frames leading to where the task is currently
- executing
-2. The name of the task
-3. A list of tasks that this task is waiting for, with their own
- frames/names/etc
-
-Returns a list of [frames, task_name, subtasks] where:
-- frames: List of (func_name, filename, lineno) showing the call
- stack
-- task_name: String identifier for the task
-- subtasks: List of tasks being awaited by this task, in same format
+Returns:
+ A list of AwaitedInfo objects, where each object contains:
+
+ - thread_id (int): Identifier of the thread, or 0 for tasks in the
+ interpreter's fallback task list.
+ - awaited_by (list[TaskInfo]): Tasks registered with this thread and
+ intermediate futures in their awaited_by chains.
+
+Each TaskInfo contains:
+ - task_id (int): Identifier of the task.
+ - task_name (str): Name of the task, or a generated name for
+ a future.
+ - coroutine_stack (list[CoroInfo]): Stack of coroutine frames.
+ - awaited_by (list[CoroInfo]): Coroutine information for tasks or futures
+ awaiting this task.
+ - is_future (bool, named-only): True for a plain Future.
+
+Each CoroInfo contains:
+ - call_stack (list[FrameInfo]): Call stack frames for the coroutine.
+ - task_name (int): Identifier of the task or future.
Raises:
RuntimeError: If AsyncioDebug section is not available in the
@@ -933,29 +914,25 @@ Returns a list of [frames, task_name, subtasks] where:
OSError: If reading from the remote process fails
Example output:
-[
- # Task c2_root waiting for two subtasks
+
[
- # Call stack of c2_root
- [("c5", "script.py", 10), ("c4", "script.py", 14)],
- "c2_root",
- [
- # First subtask (sub_main_2) and what it's waiting for
- [
- [("c1", "script.py", 23)],
- "sub_main_2",
- [...]
- ],
- # Second subtask and its waiters
- [...]
- ]
+ AwaitedInfo(
+ thread_id=12345,
+ awaited_by=[
+ TaskInfo(
+ task_id=1,
+ task_name="Task-1",
+ coroutine_stack=[...],
+ awaited_by=[]
+ )
+ ]
+ )
]
-]
[clinic start generated code]*/
static PyObject *
_remote_debugging_RemoteUnwinder_get_all_awaited_by_impl(RemoteUnwinderObject *self)
-/*[clinic end generated code: output=6a49cd345e8aec53 input=c22bfee0612e0b69]*/
+/*[clinic end generated code: output=6a49cd345e8aec53 input=17fcd3d7bb835624]*/
{
if (ensure_async_debug_offsets(self) < 0) {
return NULL;
@@ -1013,16 +990,37 @@ For each thread with a running task, returns the running task plus
all tasks that transitively depend on it (tasks waiting for the
running task, tasks waiting for those tasks, etc.).
-Returns a list of per-thread results, where each thread result
-contains:
-- Thread ID
-- List of task information for the running task and all its waiters
-
-Each task info contains:
-- Task ID (memory address)
-- Task name
-- Call stack frames: List of (func_name, filename, lineno)
-- List of tasks waiting for this task (recursive structure)
+Returns:
+ A list of AwaitedInfo objects, where each object contains:
+
+ - thread_id (int): Identifier of the thread.
+ - awaited_by (list[TaskInfo]): The running task and all its
+ transitive waiters, including intermediate futures.
+
+Each TaskInfo contains:
+ - task_id (int): Identifier of the task.
+ - task_name (str): Name of the task, or a generated name for
+ a future.
+ - coroutine_stack (list[CoroInfo]): Stack of coroutine frames.
+ - awaited_by (list[CoroInfo]): Coroutine information for
+ tasks or futures awaiting this task.
+ - is_future (bool, named-only): True for a plain Future.
+
+Each CoroInfo contains:
+ - call_stack (list[FrameInfo]): Frames for the coroutine.
+ - task_name (int): Identifier of the task or future.
+
+Each FrameInfo contains:
+ - filename (str): Source code filename.
+ - location (LocationInfo | None): Source location, if available.
+ - funcname (str): Function name.
+ - opcode (int | None): Opcode, if available.
+
+Each LocationInfo contains:
+ - lineno (int): Starting line number.
+ - end_lineno (int): Ending line number.
+ - col_offset (int): Starting column offset.
+ - end_col_offset (int): Ending column offset.
Raises:
RuntimeError: If AsyncioDebug section is not available in the
@@ -1030,27 +1028,36 @@ Each task info contains:
MemoryError: If memory allocation fails
OSError: If reading from the remote process fails
-Example output (similar structure to get_all_awaited_by but only for
-running tasks):
-[
- # Thread 140234 results
- (140234, [
- # Running task and its complete waiter dependency graph
- (4345585712, 'main_task',
- [("run_server", "server.py", 127), ("main", "app.py", 23)],
- [
- # Tasks waiting for main_task
- (4345585800, 'worker_1', [...], [...]),
- (4345585900, 'worker_2', [...], [...])
- ])
- ])
-]
+Example output:
+
+ [
+ AwaitedInfo(thread_id=140234, awaited_by=[
+ TaskInfo(
+ task_id=1,
+ task_name="worker",
+ coroutine_stack=[
+ CoroInfo(call_stack=[...], task_name=1)
+ ],
+ awaited_by=[
+ CoroInfo(call_stack=[...], task_name=2)
+ ]
+ ),
+ TaskInfo(
+ task_id=2,
+ task_name="main",
+ coroutine_stack=[
+ CoroInfo(call_stack=[...], task_name=2)
+ ],
+ awaited_by=[]
+ )
+ ])
+ ]
[clinic start generated code]*/
static PyObject *
_remote_debugging_RemoteUnwinder_get_async_stack_trace_impl(RemoteUnwinderObject *self)
-/*[clinic end generated code: output=6433d52b55e87bbe input=bc802e4221c99399]*/
+/*[clinic end generated code: output=6433d52b55e87bbe input=a95958816358476a]*/
{
if (ensure_async_debug_offsets(self) < 0) {
return NULL;
@@ -1324,11 +1331,6 @@ RemoteUnwinder_dealloc(PyObject *op)
if (self->code_object_cache) {
_Py_hashtable_destroy(self->code_object_cache);
}
-#ifdef MS_WINDOWS
- if (self->win_process_buffer != NULL) {
- PyMem_Free(self->win_process_buffer);
- }
-#endif
#ifdef Py_GIL_DISABLED
if (self->tlbc_cache) {
@@ -1376,18 +1378,13 @@ cleanup_runtime_offsets(RuntimeOffsets *offsets)
}
static int
-init_runtime_offsets(RuntimeOffsets *offsets, int pid, int debug)
+init_runtime_offsets(RuntimeOffsets *offsets, pid_t pid, int debug)
{
offsets->debug = debug;
if (_Py_RemoteDebug_InitProcHandle(&offsets->handle, pid) < 0) {
set_exception_cause(offsets, PyExc_RuntimeError, "Failed to initialize process handle");
return -1;
}
- offsets->runtime_start_address = _Py_RemoteDebug_GetPyRuntimeAddress(&offsets->handle);
- if (offsets->runtime_start_address == 0) {
- set_exception_cause(offsets, PyExc_RuntimeError, "Failed to get Python runtime address");
- goto error;
- }
if (_Py_RemoteDebug_ReadDebugOffsets(&offsets->handle,
&offsets->runtime_start_address,
&offsets->debug_offsets) < 0)
@@ -1414,7 +1411,7 @@ class _remote_debugging.GCMonitor "GCMonitorObject *" "&GCMonitor_Type"
/*[clinic input]
@permit_long_summary
_remote_debugging.GCMonitor.__init__
- pid: int
+ pid: pid_t
*
debug: bool = False
@@ -1437,9 +1434,9 @@ a running Python process.
[clinic start generated code]*/
static int
-_remote_debugging_GCMonitor___init___impl(GCMonitorObject *self, int pid,
+_remote_debugging_GCMonitor___init___impl(GCMonitorObject *self, pid_t pid,
int debug)
-/*[clinic end generated code: output=2cdf351c2f6335db input=03da0b2d3282ae1b]*/
+/*[clinic end generated code: output=03b4c92bef0673ad input=dcc6ee2ec5a16fa1]*/
{
return init_runtime_offsets(&self->offsets, pid, debug);
}
@@ -1717,6 +1714,8 @@ _remote_debugging.BinaryWriter.__init__
start_time_us: unsigned_long_long
*
compression: int = 0
+ mode: int = -1
+ capture_features: int = -1
High-performance binary writer for profiling data.
@@ -1726,6 +1725,9 @@ High-performance binary writer for profiling data.
start_time_us: Start timestamp in microseconds (from
time.monotonic() * 1e6)
compression: 0=none, 1=zstd (default: 0)
+ mode: Profiling mode, or -1 if unknown (default: -1)
+ capture_features: Capture feature bit mask, or -1 if unknown
+ (default: -1)
Use as a context manager or call finalize() when done.
[clinic start generated code]*/
@@ -1735,14 +1737,26 @@ _remote_debugging_BinaryWriter___init___impl(BinaryWriterObject *self,
PyObject *filename,
unsigned long long sample_interval_us,
unsigned long long start_time_us,
- int compression)
-/*[clinic end generated code: output=00446656ea2e5986 input=2e3f298c69fc7666]*/
+ int compression, int mode,
+ int capture_features)
+/*[clinic end generated code: output=3c1c9576795658ce input=98add735b20403ad]*/
{
+ if (mode < -1 || mode > PROFILING_MODE_EXCEPTION) {
+ PyErr_SetString(PyExc_ValueError, "invalid profiling mode");
+ return -1;
+ }
+ if (capture_features < -1 ||
+ capture_features > (int)PROFILING_FEATURE_MASK) {
+ PyErr_SetString(PyExc_ValueError, "invalid capture features");
+ return -1;
+ }
if (self->writer) {
binary_writer_destroy(self->writer);
}
- self->writer = binary_writer_create(filename, sample_interval_us, compression, start_time_us);
+ self->writer = binary_writer_create(
+ filename, sample_interval_us, compression, start_time_us, mode,
+ capture_features);
if (!self->writer) {
return -1;
}
@@ -1774,23 +1788,83 @@ _remote_debugging_BinaryWriter_write_sample_impl(BinaryWriterObject *self,
return NULL;
}
+ if (self->writer->state == BINARY_WRITER_BROKEN) {
+ PyErr_SetString(PyExc_ValueError, "Writer is broken");
+ return NULL;
+ }
+ self->writer->state = BINARY_WRITER_OPEN;
if (binary_writer_write_sample(self->writer, stack_frames, timestamp_us) < 0) {
+ if (self->writer->state != BINARY_WRITER_LIMIT_REACHED) {
+ self->writer->state = BINARY_WRITER_BROKEN;
+ }
return NULL;
}
Py_RETURN_NONE;
}
+/*[clinic input]
+_remote_debugging.BinaryWriter.set_stats
+ duration_sec: double
+ sample_rate: double
+ error_rate: object = None
+ missed_samples: object = None
+
+Store measured profile statistics in the binary file.
+[clinic start generated code]*/
+
+static PyObject *
+_remote_debugging_BinaryWriter_set_stats_impl(BinaryWriterObject *self,
+ double duration_sec,
+ double sample_rate,
+ PyObject *error_rate,
+ PyObject *missed_samples)
+/*[clinic end generated code: output=28ab1bdd7c631a97 input=1646e7182f4c2259]*/
+{
+ if (!self->writer) {
+ PyErr_SetString(PyExc_ValueError, "Writer is closed");
+ return NULL;
+ }
+ uint32_t present = 0;
+ double error_rate_value = 0.0;
+ double missed_samples_value = 0.0;
+ if (error_rate != Py_None) {
+ error_rate_value = PyFloat_AsDouble(error_rate);
+ if (error_rate_value == -1.0 && PyErr_Occurred()) {
+ return NULL;
+ }
+ present |= PROFILE_STATS_ERROR_RATE;
+ }
+ if (missed_samples != Py_None) {
+ missed_samples_value = PyFloat_AsDouble(missed_samples);
+ if (missed_samples_value == -1.0 && PyErr_Occurred()) {
+ return NULL;
+ }
+ present |= PROFILE_STATS_MISSED;
+ }
+ if (binary_writer_set_stats(self->writer, duration_sec, sample_rate,
+ error_rate_value, missed_samples_value,
+ present) < 0) {
+ return NULL;
+ }
+ Py_RETURN_NONE;
+}
+
/* Finalize the writer, cache total_samples, and destroy it.
*
* The cache assignment must happen AFTER binary_writer_finalize(): finalize
- * flushes pending RLE records and updates the file header before the writer is
- * destroyed. Caching before finalize would preserve a count for a file that
+ * flushes the open sample block and updates the file header before the writer
+ * is destroyed. Caching before finalize would preserve a count for a file that
* might still fail to finish. */
static int
binary_writer_finalize_and_cache(BinaryWriterObject *self)
{
+ if (self->writer->state == BINARY_WRITER_BROKEN) {
+ PyErr_SetString(PyExc_ValueError, "Writer is broken");
+ return -1;
+ }
if (binary_writer_finalize(self->writer) < 0) {
+ self->writer->state = BINARY_WRITER_BROKEN;
return -1;
}
self->cached_total_samples = self->writer->total_samples;
@@ -1871,8 +1945,7 @@ _remote_debugging_BinaryWriter___exit___impl(BinaryWriterObject *self,
/*[clinic end generated code: output=61831f47c72a53c6 input=12334ce1009af37f]*/
{
if (self->writer) {
- /* Only finalize on normal exit (no exception) */
- if (exc_type == Py_None) {
+ if (self->writer->state != BINARY_WRITER_BROKEN) {
if (binary_writer_finalize_and_cache(self) < 0) {
if (self->writer) {
binary_writer_destroy(self->writer);
@@ -1895,13 +1968,13 @@ _remote_debugging.BinaryWriter.get_stats
Get encoding statistics for the writer.
Returns a dict with encoding statistics including
-repeat/full/suffix/pop-push record counts, frames written/saved, and
+repeat/full/suffix/reuse record counts, frames written/saved, and
compression ratio.
[clinic start generated code]*/
static PyObject *
_remote_debugging_BinaryWriter_get_stats_impl(BinaryWriterObject *self)
-/*[clinic end generated code: output=06522cd52544df89 input=a8bb8c8682ccd34b]*/
+/*[clinic end generated code: output=06522cd52544df89 input=09c317b6289ae311]*/
{
if (!self->writer) {
PyErr_SetString(PyExc_ValueError, "Writer is closed");
@@ -1921,13 +1994,23 @@ BinaryWriter_get_total_samples(PyObject *op, void *closure)
return PyLong_FromUnsignedLongLong(self->writer->total_samples);
}
+static PyObject *
+BinaryWriter_get_limit_reached(PyObject *op, void *closure)
+{
+ BinaryWriter *writer = BinaryWriter_CAST(op)->writer;
+ return PyBool_FromLong(writer && writer->state == BINARY_WRITER_LIMIT_REACHED);
+}
+
static PyGetSetDef BinaryWriter_getset[] = {
{"total_samples", BinaryWriter_get_total_samples, NULL, "Total samples written", NULL},
+ {"limit_reached", BinaryWriter_get_limit_reached, NULL,
+ "A format limit was reached; the collected samples can still be finalized", NULL},
{NULL}
};
static PyMethodDef BinaryWriter_methods[] = {
_REMOTE_DEBUGGING_BINARYWRITER_WRITE_SAMPLE_METHODDEF
+ _REMOTE_DEBUGGING_BINARYWRITER_SET_STATS_METHODDEF
_REMOTE_DEBUGGING_BINARYWRITER_FINALIZE_METHODDEF
_REMOTE_DEBUGGING_BINARYWRITER_CLOSE_METHODDEF
_REMOTE_DEBUGGING_BINARYWRITER___ENTER___METHODDEF
@@ -1972,6 +2055,22 @@ static PyType_Spec BinaryWriter_spec = {
#define BinaryReader_CAST(op) ((BinaryReaderObject *)(op))
+static int
+binary_reader_close_checked(BinaryReaderObject *self)
+{
+ if (self->reader && self->reader->replaying) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "Cannot close or reinitialize the reader "
+ "while it is replaying");
+ return -1;
+ }
+ if (self->reader) {
+ binary_reader_close(self->reader);
+ self->reader = NULL;
+ }
+ return 0;
+}
+
/*[clinic input]
class _remote_debugging.BinaryReader "BinaryReaderObject *" "&PyBinaryReader_Type"
[clinic start generated code]*/
@@ -1994,10 +2093,9 @@ _remote_debugging_BinaryReader___init___impl(BinaryReaderObject *self,
PyObject *filename)
/*[clinic end generated code: output=f04b33ee5c5e6dbf input=9d7cbe8b4f1a97c9]*/
{
- if (self->reader) {
- binary_reader_close(self->reader);
+ if (binary_reader_close_checked(self) < 0) {
+ return -1;
}
-
self->reader = binary_reader_open(filename);
if (!self->reader) {
return -1;
@@ -2091,9 +2189,8 @@ static PyObject *
_remote_debugging_BinaryReader_close_impl(BinaryReaderObject *self)
/*[clinic end generated code: output=ad0238cf5240b4f8 input=b919a66c737712d5]*/
{
- if (self->reader) {
- binary_reader_close(self->reader);
- self->reader = NULL;
+ if (binary_reader_close_checked(self) < 0) {
+ return NULL;
}
Py_RETURN_NONE;
}
@@ -2128,9 +2225,8 @@ _remote_debugging_BinaryReader___exit___impl(BinaryReaderObject *self,
PyObject *exc_tb)
/*[clinic end generated code: output=2acdd36cfdc14e4a input=87284243d7935835]*/
{
- if (self->reader) {
- binary_reader_close(self->reader);
- self->reader = NULL;
+ if (binary_reader_close_checked(self) < 0) {
+ return NULL;
}
Py_RETURN_FALSE;
}
@@ -2226,7 +2322,7 @@ _remote_debugging_zstd_available_impl(PyObject *module)
/*[clinic input]
_remote_debugging.get_child_pids
- pid: int
+ pid: pid_t
Process ID of the parent process
*
recursive: bool = True
@@ -2248,24 +2344,24 @@ list is returned.
[clinic start generated code]*/
static PyObject *
-_remote_debugging_get_child_pids_impl(PyObject *module, int pid,
+_remote_debugging_get_child_pids_impl(PyObject *module, pid_t pid,
int recursive)
-/*[clinic end generated code: output=1ae2289c6b953e4b input=c6437b52e2fdd880]*/
+/*[clinic end generated code: output=fa3dfd1b02eed29b input=3325d95e9f39d75d]*/
{
- return enumerate_child_pids((pid_t)pid, recursive);
+ return enumerate_child_pids(pid, recursive);
}
/*[clinic input]
_remote_debugging.is_python_process
- pid: int
+ pid: pid_t
Check if a process is a Python process.
[clinic start generated code]*/
static PyObject *
-_remote_debugging_is_python_process_impl(PyObject *module, int pid)
-/*[clinic end generated code: output=22947dc8afcac362 input=13488e28c7295d84]*/
+_remote_debugging_is_python_process_impl(PyObject *module, pid_t pid)
+/*[clinic end generated code: output=63541478c889e536 input=ff998fef4aeef433]*/
{
proc_handle_t handle;
@@ -2288,7 +2384,7 @@ _remote_debugging_is_python_process_impl(PyObject *module, int pid)
/*[clinic input]
_remote_debugging.get_gc_stats
- pid: int
+ pid: pid_t
*
all_interpreters: bool = False
If True, return GC statistics from all interpreters.
@@ -2314,9 +2410,9 @@ Get garbage collector statistics from external Python process.
[clinic start generated code]*/
static PyObject *
-_remote_debugging_get_gc_stats_impl(PyObject *module, int pid,
+_remote_debugging_get_gc_stats_impl(PyObject *module, pid_t pid,
int all_interpreters)
-/*[clinic end generated code: output=d9dce5f7add149bb input=a2a08a45a8f0b119]*/
+/*[clinic end generated code: output=dd33199ccb6a56e9 input=41399e77788aa369]*/
{
RuntimeOffsets offsets;
if (init_runtime_offsets(&offsets, pid, /*debug=*/1) < 0) {
diff --git a/Modules/_remote_debugging/object_reading.c b/Modules/_remote_debugging/object_reading.c
index 1cea96a2151fcc6..ed1f07c9143e0fc 100644
--- a/Modules/_remote_debugging/object_reading.c
+++ b/Modules/_remote_debugging/object_reading.c
@@ -6,6 +6,7 @@
******************************************************************************/
#include "_remote_debugging.h"
+#include "internal/pycore_unicodeobject.h" // _Py_MAX_UNICODE
#include
/* ============================================================================
@@ -25,7 +26,6 @@ read_##type_name(RemoteUnwinderObject *unwinder, uintptr_t address, c_type *resu
}
DEFINE_MEMORY_READER(ptr, uintptr_t, "Failed to read pointer from remote memory")
-DEFINE_MEMORY_READER(Py_ssize_t, Py_ssize_t, "Failed to read Py_ssize_t from remote memory")
DEFINE_MEMORY_READER(char, char, "Failed to read char from remote memory")
int
@@ -64,12 +64,16 @@ read_py_str(
}
Py_ssize_t len = GET_MEMBER(Py_ssize_t, unicode_obj, unwinder->debug_offsets.unicode_object.length);
- if (len < 0 || len > max_len) {
+ if (len < 0) {
PyErr_Format(PyExc_RuntimeError,
"Invalid string length (%zd) at 0x%lx", len, address);
set_exception_cause(unwinder, PyExc_RuntimeError, "Invalid string length in remote Unicode object");
return NULL;
}
+ if (len > max_len) {
+ // gh-157788: a long name must not fail the whole read
+ len = max_len;
+ }
// Inspect state to pick the right data offset and character width.
// We rely on the remote process sharing this Python version's
@@ -88,23 +92,15 @@ read_py_str(
}
int kind = (int)state.kind;
- Py_UCS4 max_char;
- switch (kind) {
- case PyUnicode_1BYTE_KIND:
- max_char = state.ascii ? 0x7F : 0xFF;
- break;
- case PyUnicode_2BYTE_KIND:
- max_char = 0xFFFF;
- break;
- case PyUnicode_4BYTE_KIND:
- max_char = 0x10FFFF;
- break;
- default:
- PyErr_Format(PyExc_RuntimeError,
- "Invalid Unicode kind %d at 0x%lx", kind, address);
- set_exception_cause(unwinder, PyExc_RuntimeError,
- "Invalid kind in remote Unicode object");
- return NULL;
+ if (kind != PyUnicode_1BYTE_KIND
+ && kind != PyUnicode_2BYTE_KIND
+ && kind != PyUnicode_4BYTE_KIND)
+ {
+ PyErr_Format(PyExc_RuntimeError,
+ "Invalid Unicode kind %d at 0x%lx", kind, address);
+ set_exception_cause(unwinder, PyExc_RuntimeError,
+ "Invalid kind in remote Unicode object");
+ return NULL;
}
size_t header_size = state.ascii
@@ -124,16 +120,16 @@ read_py_str(
return NULL;
}
- PyObject *result = PyUnicode_New(len, max_char);
- if (result == NULL) {
- set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to allocate PyUnicode for remote string");
- return NULL;
- }
if (nbytes == 0) {
- return result;
+ return Py_GetConstant(Py_CONSTANT_EMPTY_STR);
}
- void *data = PyUnicode_DATA(result);
+ char *data = PyMem_Malloc(nbytes);
+ if (data == NULL) {
+ PyErr_NoMemory();
+ set_exception_cause(unwinder, PyExc_MemoryError, "Failed to allocate buffer for remote string");
+ return NULL;
+ }
// Reuse data already present in the header read; only round-trip for
// whatever spills past it.
@@ -150,14 +146,36 @@ read_py_str(
&unwinder->handle,
address + header_size + inline_bytes,
nbytes - inline_bytes,
- (char *)data + inline_bytes);
+ data + inline_bytes);
if (res < 0) {
- Py_DECREF(result);
+ PyMem_Free(data);
set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to read string data from remote memory");
return NULL;
}
}
+ if (kind == PyUnicode_4BYTE_KIND) {
+ Py_UCS4 *ucs4 = (Py_UCS4 *)data;
+ for (Py_ssize_t i = 0; i < len; i++) {
+ Py_UCS4 ch = ucs4[i];
+ if (ch > _Py_MAX_UNICODE) {
+ PyMem_Free(data);
+ PyErr_Format(PyExc_RuntimeError,
+ "character U+%x is not in range [U+0000; U+%x]",
+ ch, _Py_MAX_UNICODE);
+ set_exception_cause(unwinder, PyExc_RuntimeError,
+ "Unicode string contains invalid character");
+ return NULL;
+ }
+ }
+ }
+
+ PyObject *result = PyUnicode_FromKindAndData(kind, data, len);
+ PyMem_Free(data);
+ if (result == NULL) {
+ set_exception_cause(unwinder, PyExc_RuntimeError, "Invalid character data in remote Unicode object");
+ return NULL;
+ }
return result;
}
@@ -167,9 +185,6 @@ read_py_bytes(
uintptr_t address,
Py_ssize_t max_len
) {
- PyObject *result = NULL;
- char *buf = NULL;
-
// Read the entire PyBytesObject at once
char bytes_obj[SIZEOF_BYTES_OBJ];
int res = _Py_RemoteDebug_PagedReadRemoteMemory(
@@ -180,7 +195,7 @@ read_py_bytes(
);
if (res < 0) {
set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to read PyBytesObject");
- goto err;
+ return NULL;
}
Py_ssize_t len = GET_MEMBER(Py_ssize_t, bytes_obj, unwinder->debug_offsets.bytes_object.ob_size);
@@ -191,36 +206,26 @@ read_py_bytes(
return NULL;
}
- buf = (char *)PyMem_RawMalloc(len+1);
- if (buf == NULL) {
- PyErr_NoMemory();
+ PyBytesWriter *writer = PyBytesWriter_Create(len);
+ if (writer == NULL) {
set_exception_cause(unwinder, PyExc_MemoryError, "Failed to allocate buffer for bytes reading");
return NULL;
}
size_t offset = (size_t)unwinder->debug_offsets.bytes_object.ob_sval;
- res = _Py_RemoteDebug_PagedReadRemoteMemory(&unwinder->handle, address + offset, len, buf);
+ res = _Py_RemoteDebug_PagedReadRemoteMemory(&unwinder->handle, address + offset,
+ len, PyBytesWriter_GetData(writer));
if (res < 0) {
+ PyBytesWriter_Discard(writer);
set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to read bytes data from remote memory");
- goto err;
+ return NULL;
}
- buf[len] = '\0';
- result = PyBytes_FromStringAndSize(buf, len);
+ PyObject *result = PyBytesWriter_Finish(writer);
if (result == NULL) {
set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to create PyBytes from remote bytes data");
- goto err;
}
-
- PyMem_RawFree(buf);
- assert(result != NULL);
return result;
-
-err:
- if (buf != NULL) {
- PyMem_RawFree(buf);
- }
- return NULL;
}
long
@@ -261,7 +266,7 @@ read_py_long(
}
// Calculate how many digits fit inline in our local buffer
- Py_ssize_t ob_digit_offset = unwinder->debug_offsets.long_object.ob_digit;
+ Py_ssize_t ob_digit_offset = (Py_ssize_t)unwinder->debug_offsets.long_object.ob_digit;
Py_ssize_t inline_digits_space = SIZEOF_LONG_OBJ - ob_digit_offset;
Py_ssize_t max_inline_digits = inline_digits_space / (Py_ssize_t)sizeof(digit);
diff --git a/Modules/_remote_debugging/subprocess.c b/Modules/_remote_debugging/subprocess.c
index cdad75e318be914..eeb9693cef9222e 100644
--- a/Modules/_remote_debugging/subprocess.c
+++ b/Modules/_remote_debugging/subprocess.c
@@ -6,6 +6,7 @@
******************************************************************************/
#include "_remote_debugging.h"
+#include "pycore_fileutils.h" // _Py_strerror()
#ifndef MS_WINDOWS
#include
@@ -96,7 +97,7 @@ pid_array_contains(pid_array_t *arr, pid_t pid)
/* Find child PIDs using BFS traversal of the pid->ppid mapping.
* all_pids and ppids must have the same count (parallel arrays).
* Returns 0 on success, -1 on error. */
-static int
+UNUSED static int
find_children_bfs(pid_t target_pid, int recursive,
pid_t *all_pids, pid_t *ppids, size_t pid_count,
pid_array_t *result)
@@ -229,9 +230,13 @@ get_child_pids_platform(pid_t target_pid, int recursive, pid_array_t *result)
if (entry == NULL) {
if (errno != 0) {
int err = errno;
- _set_debug_oserror_from_errno_with_filename(err, "/proc",
- "Failed to read process directory '/proc': %s",
- strerror(err));
+ PyObject *message = _Py_strerror(err);
+ if (message != NULL) {
+ _set_debug_oserror_from_errno_with_filename(err, "/proc",
+ "Failed to read process directory '/proc': %S",
+ message);
+ Py_DECREF(message);
+ }
goto done;
}
break;
@@ -259,9 +264,13 @@ get_child_pids_platform(pid_t target_pid, int recursive, pid_array_t *result)
if (closedir(proc_dir) != 0) {
int err = errno;
proc_dir = NULL;
- _set_debug_oserror_from_errno_with_filename(err, "/proc",
- "Failed to close process directory '/proc': %s",
- strerror(err));
+ PyObject *message = _Py_strerror(err);
+ if (message != NULL) {
+ _set_debug_oserror_from_errno_with_filename(err, "/proc",
+ "Failed to close process directory '/proc': %S",
+ message);
+ Py_DECREF(message);
+ }
goto done;
}
proc_dir = NULL;
@@ -307,6 +316,7 @@ get_child_pids_platform(pid_t target_pid, int recursive, pid_array_t *result)
PyErr_SetString(PyExc_OSError, "Failed to get process count");
goto done;
}
+ n_pids /= sizeof(pid_t);
/* Allocate buffer for PIDs (add some slack for new processes) */
int buffer_size = n_pids + 64;
@@ -322,6 +332,7 @@ get_child_pids_platform(pid_t target_pid, int recursive, pid_array_t *result)
PyErr_SetString(PyExc_OSError, "Failed to list PIDs");
goto done;
}
+ actual /= sizeof(pid_t);
/* Build pid -> ppid mapping */
ppids = (pid_t *)PyMem_Malloc(actual * sizeof(pid_t));
diff --git a/Modules/_remote_debugging/threads.c b/Modules/_remote_debugging/threads.c
index 04c70cc96d6bd1e..66c40d875ab3b31 100644
--- a/Modules/_remote_debugging/threads.c
+++ b/Modules/_remote_debugging/threads.c
@@ -6,6 +6,7 @@
******************************************************************************/
#include "_remote_debugging.h"
+#include "pycore_fileutils.h" // _Py_strerror()
#ifndef MS_WINDOWS
#include
@@ -17,6 +18,17 @@
#include