repo
stringclasses
1 value
instance_id
stringlengths
20
22
problem_statement
stringlengths
126
60.8k
merge_commit
stringlengths
40
40
base_commit
stringlengths
40
40
python/cpython
python__cpython-130308
# datetime subclass repr varies by implementation In [pypy/pypy#3980](https://foss.heptapod.net/pypy/pypy/-/issues/3980#note_309077), I reported an issue I'd encountered where the repr of a `datetime.datetime` subclass shows a different repr depending on which implementation (C or Python) of the datetime module is used: ```py import sys import importlib c_impl = importlib.import_module('_datetime') sys.modules['_datetime'] = None py_impl = importlib.import_module('datetime') assert repr(py_impl.datetime(2000,1,1)) == repr(c_impl.datetime(2000,1,1)) class Fake(py_impl.datetime): pass fpy = Fake(2000,1,1) class Fake(c_impl.datetime): pass fc = Fake(2000,1,1) assert repr(fpy) == repr(fc), f'{fpy!r} != {fc!r}' ``` Emits as output: ``` Traceback (most recent call last): File "/Users/jaraco/draft/dt.py", line 18, in <module> assert repr(fpy) == repr(fc), f'{fpy!r} != {fc!r}' AssertionError: __main__.Fake(2000, 1, 1, 0, 0) != Fake(2000, 1, 1, 0, 0) ``` This inconsistency wreaks havoc on doctests when using a library like [freezegun](https://github.com/spulec/freezegun). Is there a way for these two implementations to share a common repr? <!-- gh-linked-prs --> ### Linked PRs * gh-130308 <!-- /gh-linked-prs -->
81a9b53fee79c4581bc1e2acae1c98ee0b692c7d
9f81f828c797f842d1df0a5cbda898bc0df8075a
python/cpython
python__cpython-107757
# The lltrace feature can trigger infinite recursion via `__repr__` When turning on the low-level interpreter tracing feature (`lltrace` in ceval.c) it is quite easy to hit infinite recursion in `dump_stack()`, when an item on the stack being printed has a `__repr__` method implemented in Python. (This is especially annoying when hardcoding`lltrace = 1`, since it will never get through the importlib bootstrap -- for some reason the `__repr__` for module objects is (re-)implemented in Python.) While I suppose we could fix this by adding some kind of protection against recursive calls to `dump_stack()`, I think it's better to just avoid calling into Python at all by writing most objects in the form `<type at address>` (with exceptions for ints etc.). CC @sweeneyde, author of `dump_stack()` in gh-91463. (I don't want to just remove it -- it actually saved my bacon today.) <!-- gh-linked-prs --> ### Linked PRs * gh-107757 <!-- /gh-linked-prs -->
328d925244511b2134d5ac926e307e4486ff4500
2df58dcd500dbedc61d0630374f9e94c522fe523
python/cpython
python__cpython-107756
# Signature of slice is documented incorrectly # Documentation https://docs.python.org/3/library/functions.html#slice currently shows: class slice(start, stop, step=1) This was changed from `slice(start, stop[, step])` in https://github.com/python/cpython/pull/96579. That default for `step` is incorrect. It's correct in a range, but in a slice it actually defaults to `None`: >>> slice(1,2).step is None True Most code handle `step=1` and `step=None` the same way when receiving a slice, but user defined types implementing `__getitem__`/`__setitem__`/`__delitem__` aren't obliged to, and the correct default should be documented. <!-- gh-linked-prs --> ### Linked PRs * gh-107756 * gh-108955 * gh-108956 <!-- /gh-linked-prs -->
9bf350b0662fcf1a8b43b9293e6c8ecf3c711561
3f89b257639dd817a32079da2ae2c4436b8e82eb
python/cpython
python__cpython-107736
# Add C API tests for PySys_GetObject() and PySys_SetObject() `PySys_GetObject()` will be changed in #106672, so we need tests. <!-- gh-linked-prs --> ### Linked PRs * gh-107736 * gh-107740 * gh-107741 * gh-107743 <!-- /gh-linked-prs -->
bea5f93196d213d6fbf4ba8984caf4c3cd1da882
430632d6f710c99879c5d1736f3b40ea09b11c4d
python/cpython
python__cpython-107734
# importlib.resources.as_file docs should mention it can provide whole directories # Documentation As [pointed](https://discuss.python.org/t/importlib-resources-access-whole-directories-as-resources/15618/3?u=smheidrich) [out](https://discuss.python.org/t/importlib-resources-access-whole-directories-as-resources/15618/5?u=smheidrich) in a thread on the Ideas forum, `importlib.resources` gained support for extracting/returning whole directories as resources via its `as_file()` function in Python 3.12. But [the docs](https://docs.python.org/3.13/library/importlib.resources.html#importlib.resources.as_file) make no mention of this and in fact heavily suggest the opposite (emphasis mine): > `importlib.resources.as_file(traversable)` >Given a [Traversable](https://docs.python.org/3.13/library/importlib.resources.abc.html#importlib.resources.abc.Traversable) object representing **a file**, typically from [importlib.resources.files()](https://docs.python.org/3.13/library/importlib.resources.html#importlib.resources.files), return a context manager for use in a [with](https://docs.python.org/3.13/reference/compound_stmts.html#with) statement. [...] > >Exiting the context manager cleans up any temporary **file** created when the resource was extracted from e.g. a zip file. > >Use as_file when the Traversable methods (read_text, etc) are insufficient and **an actual file** on the file system is required. This should probably be changed to reflect the fact that it can now handle directories as well, not just individual files. Especially important because being able to extract/return whole directories was a feature that `importlib.resources` lacked for quite a while compared to its now-deprecated predecessor [`pkg_resources`](https://setuptools.pypa.io/en/latest/pkg_resources.html#resource-extraction), so not pointing out that this works now can make people remain hesitant to make the switch. PR incoming. <!-- gh-linked-prs --> ### Linked PRs * gh-107734 * gh-109058 <!-- /gh-linked-prs -->
9f0c0a46f00d687e921990ee83894b2f4ce8a6e7
f9bd6e49ae58e0ba2934f29dd0f3299ba844cc8d
python/cpython
python__cpython-107725
# The callback signature for `PY_THROW` is inconsistent with the other exception handling callbacks The callbacks for `RAISE`, `RERAISE`, `EXCEPTION_HANDLED`, `PY_UNWIND` and `STOP_ITERATION` all take the exception as their third argument. `PY_THROW` is the odd one out, but it should be consistent with the others. `PY_THROW` is a rare event, so this got overlooked. We should fix it before the next release of 3.12. Fortunately it is very easy to fix. <!-- gh-linked-prs --> ### Linked PRs * gh-107725 * gh-107802 <!-- /gh-linked-prs -->
52fbcf61b5a70993c2d32332ff0ad9f369d968d3
2fb484e62518d15fc9a19565c2ab096bd741219a
python/cpython
python__cpython-107716
# DocTestFinder.find fails if module contains class objects with special characters <!-- New to Python? The issue tracker isn't the right place to get help. Consider instead: - reading the Python tutorial: https://docs.python.org/3/tutorial/ - posting at https://discuss.python.org/c/users/7 - emailing https://mail.python.org/mailman/listinfo/python-list --> # Bug report ## Checklist <!-- Bugs in third-party projects (e.g. `requests`) do not belong in the CPython issue tracker --> - [X] I am confident this is a bug in CPython, not a bug in a third-party project - [X] I have searched the CPython issue tracker, and am confident this bug has not been reported before ## A clear and concise description of the bug <!-- Include a minimal, reproducible example if possible. (https://stackoverflow.com/help/minimal-reproducible-example) Put any code blocks inside triple backticks: ```py your code here ``` --> Doctests initialization may fail with `re.error` in case a module contains (dynamically generated) class objects with special characters in their name. This is caused by the regular expression compiled in `doctest.DocTestFinder._find_lineno` failing to escape the class name before embedding it. If compilation does succeed, then invalid matches may result from interpreting the class name as a search pattern. # Your environment <!-- Include all relevant details about the environment you experienced the bug in --> - CPython versions tested on: 3.9.2 - Operating system and architecture: Debian linux amd64 <!-- You can freely edit this form. Remove any lines you believe are unnecessary. --> <!-- gh-linked-prs --> ### Linked PRs * gh-107716 * gh-107726 * gh-107727 <!-- /gh-linked-prs -->
85793278793708ad6b7132a54ac9fb4b2c5bcac1
ed64204716035db58c7e11b78182596aa2d97176
python/cpython
python__cpython-107714
# Reduce usage of mocks in `test_clinic.py` # Feature or enhancement We should reduce usage of mock objects in `test_clinic.py`, such as `FakeClinic`, `FakeConvertersDict`, `FakeConverterFactory` and `FakeConverter`. # Pitch There doesn't seem to be a strong reason to use mock objects like these in `test_clinic.py`, since the "real" objects in `clinic.py` are easy and cheap to construct. Removing the mock objects from `test_clinic.py` will reduce the maintenance burden, as it reduces the risk that the mock objects drift apart from the real implementation, and reduces the risk that the mock objects will have subtle behaviour differences to the real implementation. <!-- gh-linked-prs --> ### Linked PRs * gh-107714 <!-- /gh-linked-prs -->
c399b5e1a56f7c659fc92edc20bc4bf522bdeffd
8c9af6b9a0d6fc9cb237e96588d8dcab727e32b8
python/cpython
python__cpython-107711
# Optimize `logging.getHandlerNames()` Right now this function is not optimal. Source: ```python def getHandlerNames(): """ Return all known handler names as an immutable set. """ result = set(_handlers.keys()) return frozenset(result) ``` Why? `_handlers.keys()` already returns `set`-like thing, so there's no need to use extra `set()` It can be simplified to: ```python def getHandlerNames(): """ Return all known handler names as an immutable set. """ return frozenset(_handlers.keys()) ``` This simple benchmark (with only two handlers) gives a noticable improvement: ```python import logging # create logger logger = logging.getLogger('simple_example') logger.setLevel(logging.DEBUG) # create formatter formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # create two handlers ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) ch.setFormatter(formatter) logger.addHandler(ch) fl = logging.FileHandler('./log.txt') fl.setLevel(logging.DEBUG) fl.setFormatter(formatter) logger.addHandler(fl) ``` Before: ``` (.venv) ~/Desktop/cpython main ✗ » pyperf timeit --setup 'import ex; l = ex.logging' 'l.getHandlerNames()' ..................... Mean +- std dev: 2.13 us +- 0.02 us ``` After: ``` (.venv) ~/Desktop/cpython main ✗ » pyperf timeit --setup 'import ex; l = ex.logging' 'l.getHandlerNames()' ..................... Mean +- std dev: 2.04 us +- 0.02 us ``` So, I think we should make this change :) PR is incoming. <!-- gh-linked-prs --> ### Linked PRs * gh-107711 <!-- /gh-linked-prs -->
8fcee6b2795a504f1bd39118759e5ce44183f689
c399b5e1a56f7c659fc92edc20bc4bf522bdeffd
python/cpython
python__cpython-110507
# test_tkinter leaks files in the C locale ``` $ LC_ALL=C ./python -m test -vuall test_tkinter -m 'test_write' ... Warning -- files was modified by test_tkinter Warning -- Before: [] Warning -- After: ['@test_1061191_tmp\udce6'] Warning -- files was modified by test_tkinter Warning -- Before: [] Warning -- After: ['@test_1061191_tmp\udce6'] test_tkinter failed (env changed) ... ``` Since it is only a warning and occurs only in the C locale, it was unnoticed. In the C locale Tcl uses Latin1 to encode filenames, while Python uses UTF-8. <!-- gh-linked-prs --> ### Linked PRs * gh-110507 * gh-110857 * gh-110858 <!-- /gh-linked-prs -->
ca0f3d858d069231ce7c5b382790a774f385b467
38bd2c520a2df7904e32093da2166eec2c039802
python/cpython
python__cpython-107984
# Argument Clinic: add support for deprecating keyword use of parameters See https://github.com/python/cpython/issues/95065#issuecomment-1193187512 by Serhiy. Quoting: > Turn positional-or-keyword parameters into positional-only parameters. A directive which means "the preceding positional-or-keyword parameters will be positional-only parameters in future". In #95151, Argument Clinic learned how to deprecate positional use of parameters. In this issue, we propose to teach Argument Clinic how to deprecate keyword use of parameters. Suggesting to use a similar syntax as the one introduced in #95151 ``` func a: object / [from X.Y] ``` Meaning `a` will be positional-only from Python version X.Y. We can reuse parts of the code introduced in #95151 to implement this feature. <!-- gh-linked-prs --> ### Linked PRs * gh-107984 <!-- /gh-linked-prs -->
2f311437cd51afaa68fd671bb99ff515cf7b029a
eb953d6e4484339067837020f77eecac61f8d4f8
python/cpython
python__cpython-108260
# EnumType is not documented as new in 3.11 # Documentation In python 3.10 and earlier Enum's metaclass was called `EnumMeta`. https://docs.python.org/3.10/library/enum.html#enum-classes In python 3.11 this was renamed EnumType (https://docs.python.org/3.11/whatsnew/3.11.html#enum). However the fact that `EnumType` was introduced in Python 3.11 is not mentioned. https://docs.python.org/3.10/library/enum.html#enum-classes Nor is the fact that `EnumMeta `still exists as an alias. This would be useful to document. <!-- gh-linked-prs --> ### Linked PRs * gh-108260 * gh-108300 * gh-108301 <!-- /gh-linked-prs -->
e8ef0bdd8c613a722bf7965bf1da912882141a52
6541fe4ad7b96ab96ee5c596b60814a93346dd27
python/cpython
python__cpython-107697
# ctypes: Add docstring for `ctypes.Array` # Documentation The [`Array` class](https://docs.python.org/3.13/library/ctypes.html#ctypes.Array) from the `ctypes` module doesn't have a proper docstring: ```python from ctypes import Array help(Array) >>> Help on class Array in module _ctypes: >>> >>> class Array(_CData) >>> | XXX to be provided # !! >>> | ``` Though the class is documented in the [docs](https://docs.python.org/3.13/library/ctypes.html#ctypes.Array) so we could just reuse that description. Feel free to pick up this issue :) If you're new to the C internals, here's a small guide to help you get started: `ctypes.Array` is a class implemented in C defined in `Modules/_ctypes/_ctypes.c`. Here is the current docstring definition: https://github.com/python/cpython/blob/71a7c96ffeb0d7fef06be3e57468896e030967a5/Modules/_ctypes/_ctypes.c#L4816-L4818 To update the docstring, we could simply change the argument of `PyDoc_STR(...)` but if the docstring is longer it's better to use [PyDoc_STRVAR](https://docs.python.org/3/c-api/intro.html#c.PyDoc_STRVAR) to create a separate variable with the new docstring: ```c PyDoc_STRVAR(array_doc, "Abstract base class for arrays.\n" "\n" "The recommended way to create ..."); ``` then you substitute it back instead of `PyDoc_STR`: ```diff Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - PyDoc_STR("XXX to be provided"), /* tp_doc */ + array_doc, /* tp_doc */ (traverseproc)PyCData_traverse, ``` To test that it worked, rebuild python and check the docstring ;) <!-- gh-linked-prs --> ### Linked PRs * gh-107697 * gh-108882 <!-- /gh-linked-prs -->
0f2fb6efb4d5d8ca43a0e779b89a8e805880e09a
4890bfe1f906202ef521ffd327cae36e1afa0873
python/cpython
python__cpython-107688
# Tcl and Tk versions can be desynchronized For a long time Tcl and Tk versions were synchronized. But in future they can be desynchronized again, for example Tcl 9.0/Tk 8.7. Tests currently use Tcl and Tk versions interchangeably. They should be updated to test the correct version. <!-- gh-linked-prs --> ### Linked PRs * gh-107688 <!-- /gh-linked-prs -->
3c8e8f3ceeae08fc43d885f5a4c65a3ee4b1a2c8
6925c578a0e3cbb00858e64da813a7ffe79623c4
python/cpython
python__cpython-107679
# ``re`` documentation contains outdated and unclear Unicode information I was reading the [``re``](https://docs.python.org/3/library/re.html) documentation recently, and I noticed that the information around the Unicode, ASCII, and Locale flags and how matching is affected was unclear in parts and inconsistent within the documentation. This provides an opportunity to review that documentation and be more explicit. I plan to use more admonitions, bring lists of flags into bullets, ensure consistency when referring to str or bytes patterns, and be more explicit about flags that are discouraged or redundant. A <!-- gh-linked-prs --> ### Linked PRs * gh-107679 * gh-113965 * gh-113966 <!-- /gh-linked-prs -->
c9b8a22f3404d59e2c4950715f8c29413a349b8e
b4d4aa9e8d61476267951c72321fadffc2d82227
python/cpython
python__cpython-107663
# anext is after any # Documentation In the list of builtin functions: https://docs.python.org/3/library/functions.html "anext" is after "any", yet in the documentation itself, on the same page, "anext" is before "any", in the correct alphabetical order. Is this just a typo or there is a reason for it? Thank you. ![anext](https://github.com/python/cpython/assets/89370810/9d27bad8-e83f-4bba-884c-1ec8544acced) <!-- gh-linked-prs --> ### Linked PRs * gh-107663 * gh-107664 * gh-107665 <!-- /gh-linked-prs -->
9ebc6ecbc336d7b17cd158d1a4522f832df3e6e2
41178e41995992bbe417f94bce158de93f9e3188
python/cpython
python__cpython-107660
# ctypes: Add docstrings for `ctypes.pointer` and `ctypes.POINTER` `ctypes.pointer` and `ctypes.POINTER` from the `ctypes` module are currently lacking docstrings. I suggest we add those. Luckily, these functions are already documented in the [docs](https://docs.python.org/3/library/ctypes.html#ctypes.pointer) so it should just be a matter of reusing the description from the docs. It has also been recommended that we convert both functions to Argument Clinic when adding the docstrings. <!-- gh-linked-prs --> ### Linked PRs * gh-107660 * gh-107739 * gh-107769 * gh-108163 * gh-108164 <!-- /gh-linked-prs -->
de72677f8a27083b2072b83b3737f891b660bb5c
7a250fdc16bb6f1fe0a6b0df8bb502870405b5d6
python/cpython
python__cpython-107653
# Set up CIFuzz to run fuzz targets continuously # Feature or enhancement OSS-Fuzz offers [CIFuzz](https://google.github.io/oss-fuzz/getting-started/continuous-integration/), a collection of GitHub actions that can be used for running fuzz targets based on [the existing OSS-Fuzz configuration](https://github.com/google/oss-fuzz/tree/master/projects/cpython3) similarly to running unit tests in CI. # Pitch CPython has been tested by OSS-Fuzz for a few years. The tool has helped discover multiple issues like #91466, #102509, and #106057. However, there is a tendency to leave [builds](https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=60831) or [individual tests](https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=51574) broken for a while. The issues are usually caused by changes in CPython code, and current testing performed in GitHub actions and Buildbot misses some cases like compiling CPython with memory sanitizer. CIFuzz can help identify issues when they are created, and passing tests can be made a requirement for a successful status of a pull request. This can help prevent new issues of this kind from being merged in the main branch. <!-- gh-linked-prs --> ### Linked PRs * gh-107653 <!-- /gh-linked-prs -->
ea7b53ff67764a2abf1f27d4c95d032d2dbb02f9
326c6c4e07137b43c49b74bd5528619360080469
python/cpython
python__cpython-107648
# TraceRefs build triggers assertion errors In a `--with-trace-refs --with-pydebug` build of 3.12 and main, even a simple test like `test_int` triggers an assertion error in the refchain handling. I expect it's caused by @ericsnowcurrently's PR #107567. ``` cpython-tracerefs % ../../cpython/configure -C --with-trace-refs --with-pydebug [...] cpython-tracerefs % make [...] cpython-tracerefs % ./python -m test test_int 0:00:00 load avg: 2.79 Run tests sequentially 0:00:00 load avg: 2.79 [1/1] test_int == Tests result: SUCCESS == 1 test OK. Total duration: 477 ms Tests result: SUCCESS ../../cpython/Objects/object.c:2234: _Py_ForgetReference: Assertion failed: invalid object chain Enable tracemalloc to get the memory block allocation traceback object address : 0x7ff86d998050 object refcount : 0 object type : 0x55fbc49aba60 object type name: dict object repr : <refcnt 0 at 0x7ff86d998050> Fatal Python error: _PyObject_AssertFailed: _PyObject_AssertFailed Python runtime state: finalizing (tstate=0x000055fbc4b27e88) Current thread 0x00007ff86daec740 (most recent call first): <no Python frame> Aborted ``` <!-- gh-linked-prs --> ### Linked PRs * gh-107648 * gh-107733 * gh-107737 * gh-107750 <!-- /gh-linked-prs -->
7cf9ce24409efb70efde08e350a4170dc98008a1
6c92d76abc730ca7a77da3c7a8627192f7ac3add
python/cpython
python__cpython-107651
# ConfigParser AttributeError: 'NoneType' object has no attribute 'append' <!-- New to Python? The issue tracker isn't the right place to get help. Consider instead: - reading the Python tutorial: https://docs.python.org/3/tutorial/ - posting at https://discuss.python.org/c/users/7 - emailing https://mail.python.org/mailman/listinfo/python-list --> # Bug report ## Checklist <!-- Bugs in third-party projects (e.g. `requests`) do not belong in the CPython issue tracker --> - [x] I am confident this is a bug in CPython, not a bug in a third-party project - [x] I have searched the CPython issue tracker, and am confident this bug has not been reported before ## A clear and concise description of the bug <!-- Include a minimal, reproducible example if possible. (https://stackoverflow.com/help/minimal-reproducible-example) Put any code blocks inside triple backticks: --> When trying to parse an INI with an indented key that follows a no-value key, an AttributeError is raised ```py import configparser lines = [ '[SECT]\n', 'KEY1\n', ' KEY2 = VAL2\n', # note the Space before the key! ] conf = configparser.ConfigParser( comment_prefixes ="", allow_no_value =True, strict =False, delimiters =( '=', ), interpolation =None, ) conf.read_file( lines, "test" ) print( conf.__dict__[ '_sections' ] ) ``` ``` File "C:\Python311\Lib\configparser.py", line 1076, in _read cursect[optname].append(value) ^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'append' ``` The reason is that ConfigParser assumes the second key is a continuation line and therefore further assumes that ``cursect[optname]`` is initialized in the following check: ```py if (cursect is not None and optname and cur_indent_level > indent_level): cursect[optname].append(value) ``` Suggested fix: add a check for ``cursect[optname] is not None``: ```py if (cursect is not None and optname and cursect[optname] is not None and cur_indent_level > indent_level): cursect[optname].append(value) ``` With this check added, the print will output: ```py {'SECT': {'key1': None, 'key2': 'VAL2'}} ``` If the suggested fix is not acceptable, please consider to add a check and maybe raise a ``ParsingError``, but making an assumption about ``cursect[optname]`` and let it raise an AttributeError is just not a good thing, IMHO. # Your environment <!-- Include all relevant details about the environment you experienced the bug in --> - CPython versions tested on: 3.7, 3.9, 3.11.2 (Python 3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934 64 bit (AMD64)] on win32) - Operating system and architecture: Windows 10 Pro, 64 bit <!-- You can freely edit this form. Remove any lines you believe are unnecessary. --> <!-- gh-linked-prs --> ### Linked PRs * gh-107651 <!-- /gh-linked-prs -->
e800265aa1f3451855a2fc14fbafc4d89392e35c
27858e2a17924dfac9a10efc17caee1f5126ea19
python/cpython
python__cpython-107934
# Inconsistent behavior for duplicate inputs to `asyncio.as_completed` versus `asyncio.gather()` <!-- New to Python? The issue tracker isn't the right place to get help. Consider instead: - reading the Python tutorial: https://docs.python.org/3/tutorial/ - posting at https://discuss.python.org/c/users/7 - emailing https://mail.python.org/mailman/listinfo/python-list --> # Bug report ## Checklist <!-- Bugs in third-party projects (e.g. `requests`) do not belong in the CPython issue tracker --> - [x] I am confident this is a bug in CPython, not a bug in a third-party project - [x] I have searched the CPython issue tracker, and am confident this bug has not been reported before ## A clear and concise description of the bug The provided code displays varying behavior. The asserts below illustrate the disparity between the current and expected outcomes. While the assert using `asyncio.gather` functions correctly as intended, the one utilizing `asyncio.as_completed` shows inconsistency between the first and second call. If the behavior is considered to be correct as intended, it would be helpful to have a brief explanation, possibly in the [`functools.cache`](https://docs.python.org/3/library/functools.html#functools.cache) documentation, clarifying the reasons behind this decision. ```py import asyncio from functools import cache @cache async def foo(): await asyncio.sleep(1) return 1 async def main(): # assert await asyncio.gather(foo(), foo(), foo()) == [1, 1, 1], 'The result is as expected, if this line is uncommented' # When the above statement is uncommented, the following assert passes for [1], but the expected result is [1, 1, 1] assert [await result for result in asyncio.as_completed([foo(), foo(), foo()])] == [1] info = foo.cache_info() assert info.hits == 2 and info.misses == 1, 'The result is as expected, but the outcome of the previous statement is inconsistent' # RuntimeError: cannot reuse already awaited coroutine # The expected result is [1, 1, 1] or [1] if the behavior above is justified assert [await result for result in asyncio.as_completed([foo(), foo(), foo()])] == [1, 1, 1] asyncio.run(main()) ``` # Your environment - CPython versions tested on: Output from `sys.version` = 3.11.4 - Operating system and architecture: Output from `sys.platform` = `darwin` and `platform.architecture()` = `64bit` <!-- gh-linked-prs --> ### Linked PRs * gh-107934 * gh-108161 * gh-108162 <!-- /gh-linked-prs -->
1a713eac47b26899044752f02cbfcb4d628dda2a
b1e5d2c601bbd3d435b60deef4818f3622bdfca3
python/cpython
python__cpython-107615
# Normalise Argument Clinic error messages Argument Clinic is pretty good at disallowing weird corner cases and producing error messages (there are 130 `fail(..)`s sprinkled around clinic.py!). Unfortunately, many of the error messages do not wrap the line or token in question, nor the function/module/class name in question in quotes. Also, some error messages contain line breaks in unexpected places. Some examples: <details> <summary>Error message with unexpected line break</summary> Clinic input: ```c /*[clinic input] function a: int = 0 b: int [clinic start generated code]*/ ``` ```console $ python3.12 Tools/clinic/clinic.py test.c Error in file 'test.c' on line 4: Can't have a parameter without a default ('b') after a parameter with a default! ``` </details> <details> Clinic input: ```c /*[clinic input] function b: int * [clinic start generated code]*/ ``` Error message: ```console $ python3.12 Tools/clinic/clinic.py test.c Error in file 'test.c' on line 5: Function function specifies '*' without any parameters afterwards. ``` </details> Suggesting to normalise Argument Clinic error messages, using the following guidelines: - always wrap the offending line, token, or name in quotes - no line break; the entire error message should be on one line <!-- gh-linked-prs --> ### Linked PRs * gh-107615 <!-- /gh-linked-prs -->
ac7605ed197e8b2336d44c8ac8aeae6faa90a768
2ba7c7f7b151ff56cf12bf3cab286981bb646c90
python/cpython
python__cpython-107610
# Argument Clinic duplicate module check is malfunctioning The following code is silently accepted by Argument Clinic: ```c /*[clinic input] module m module m [clinic start generated code]*/ ``` The duplicate `module m` should have been caught by Argument Clinic, but the guard is faulty: https://github.com/python/cpython/blob/9e6590b0978876de14587f528a09632b8879c369/Tools/clinic/clinic.py#L4481-L4482 The check should be against `.modules`, not `.classes`: ```diff diff --git a/Tools/clinic/clinic.py b/Tools/clinic/clinic.py index 1bcdb6b1c3..dc4a7f9318 100755 --- a/Tools/clinic/clinic.py +++ b/Tools/clinic/clinic.py @@ -4478,7 +4478,7 @@ def directive_module(self, name: str) -> None: if cls: fail("Can't nest a module inside a class!") - if name in module.classes: + if name in module.modules: fail("Already defined module " + repr(name) + "!") m = Module(name, module) ``` See also the `Module` class: https://github.com/python/cpython/blob/9e6590b0978876de14587f528a09632b8879c369/Tools/clinic/clinic.py#L2384-L2392 <!-- gh-linked-prs --> ### Linked PRs * gh-107610 * gh-107612 <!-- /gh-linked-prs -->
a443c310ac87f214164cb1e3f8af3f799668c867
e52e87c349feeee77445205829bfc8db9fe4b80e
python/cpython
python__cpython-107858
# Update comment about utf-8 BOM being ignored [EDIT: I opened this because I saw a redundancy in a paragraph in Reference / 2. Lexical analysis / 2.1 Line structure / 2.1.4 [Encoding declarations](https://docs.python.org/3/reference/lexical_analysis.html#encoding-declarations). I neglected to explain the problem and instead jumped to what I now think is the wrong solution. See my explanation and better fix in https://github.com/python/cpython/issues/107607#issuecomment-1675967835. I leave the original post so the ensuing discussion makes sense.] I believe "if the first bytes of the file are the UTF-8 byte-order mark (b'\xef\xbb\xbf'), the declared file encoding is UTF-8" in [Encoding declarations](https://docs.python.org/3/reference/lexical_analysis.html#encoding-declarations) should end with "UTF-8-sig" or "[UTF_8_sig](https://docs.python.org/3/library/codecs.html#module-encodings.utf_8_sig)". (Not sure which.) Easy issue once fix verified. <!-- gh-linked-prs --> ### Linked PRs * gh-107858 * gh-117015 * gh-117016 <!-- /gh-linked-prs -->
7f64ae30ddc22577ce4101ce0b6601b3548b036f
2c82592ab463f1f38237919a12145f34eaadda23
python/cpython
python__cpython-108486
# Argument Clinic includes internal headers in generated output unconditionally It seems like Argument Clinic generates code that define `Py_BUILD_CORE` and includes internal headers unconditionally; for example, a file with a `METH_O` function will have no need for those: <details> ```c /*[clinic input] preserve [clinic start generated code]*/ #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE) # include "pycore_gc.h" // PyGC_Head # include "pycore_runtime.h" // _Py_ID() #endif PyDoc_STRVAR(func__doc__, "func($module, a, /)\n" "--\n" "\n"); #define FUNC_METHODDEF \ {"func", (PyCFunction)func, METH_O, func__doc__}, /*[clinic end generated code: output=851b6645c29cfa0d input=a9049054013a1b77]*/ ``` </details> OTOH, a `METH_KEYWORDS` function needs those: <details> ```c /*[clinic input] preserve [clinic start generated code]*/ #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE) # include "pycore_gc.h" // PyGC_Head # include "pycore_runtime.h" // _Py_ID() #endif PyDoc_STRVAR(func__doc__, "func($module, /, a, b)\n" "--\n" "\n"); #define FUNC_METHODDEF \ {"func", _PyCFunction_CAST(func), METH_FASTCALL|METH_KEYWORDS, func__doc__}, static PyObject * func_impl(PyObject *module, PyObject *a, PyObject *b); static PyObject * func(PyObject *module, 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 2 static struct { PyGC_Head _this_is_not_used; PyObject_VAR_HEAD PyObject *ob_item[NUM_KEYWORDS]; } _kwtuple = { .ob_base = PyVarObject_HEAD_INIT(&PyTuple_Type, NUM_KEYWORDS) .ob_item = { &_Py_ID(a), &_Py_ID(b), }, }; #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[] = {"a", "b", NULL}; static _PyArg_Parser _parser = { .keywords = _keywords, .fname = "func", .kwtuple = KWTUPLE, }; #undef KWTUPLE PyObject *argsbuf[2]; PyObject *a; PyObject *b; args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser, 2, 2, 0, argsbuf); if (!args) { goto exit; } a = args[0]; b = args[1]; return_value = func_impl(module, a, b); exit: return return_value; } /*[clinic end generated code: output=e790cd95ffc517a0 input=a9049054013a1b77]*/ ``` </details> Argument Clinic should check if those defines/includes are needed before generating the output. <!-- gh-linked-prs --> ### Linked PRs * gh-108486 * gh-108581 * gh-108715 * gh-108726 <!-- /gh-linked-prs -->
73d33c1a3078c5f2588c89d61e1a17a1b2a26c34
1dd951097728d735d46a602fc43285d35b7b32cb
python/cpython
python__cpython-107601
# ctypes docs: Update `ArgumentError` error messages # Documentation Now that #107456 has been merged, we should also update the examples in the docs which still show the old message: https://github.com/python/cpython/blob/58ef74186795c56e3ec86e8c8f351a1d7826638a/Doc/library/ctypes.rst?plain=1#L445-L447 <!-- gh-linked-prs --> ### Linked PRs * gh-107601 <!-- /gh-linked-prs -->
09a8cc79846ce0870e51fa8e7c449e153832fe4b
19f32b24b2e1680ff9929bb64d681397b259c6fb
python/cpython
python__cpython-107597
# Specialize `str[int]` According to our [stats](https://github.com/faster-cpython/benchmarking-public/blob/main/results/bm-20230729-3.13.0a0-5113ed7/bm-20230729-azure-x86_64-python-main-3.13.0a0-5113ed7-pystats.md), `BINARY_SUBSCR` has a 90% failure rate, and over half of those are due to `str[int]`. This seems like an easy one to specialize. <!-- gh-linked-prs --> ### Linked PRs * gh-107597 <!-- /gh-linked-prs -->
ea72c6fe3b6db5f4e8ce3d3405c0ea65dc002faf
aab6f7173a3b825599629dd6fa5cb7e477421595
python/cpython
python__cpython-107584
# Odd types.get_original_bases() behavior for classes with generic bases but no type arguments <!-- New to Python? The issue tracker isn't the right place to get help. Consider instead: - reading the Python tutorial: https://docs.python.org/3/tutorial/ - posting at https://discuss.python.org/c/users/7 - emailing https://mail.python.org/mailman/listinfo/python-list --> # Bug report ## Checklist <!-- Bugs in third-party projects (e.g. `requests`) do not belong in the CPython issue tracker --> - [x] I am confident this is a bug in CPython, not a bug in a third-party project - [x] I have searched the CPython issue tracker, and am confident this bug has not been reported before ## A clear and concise description of the bug <!-- Include a minimal, reproducible example if possible. (https://stackoverflow.com/help/minimal-reproducible-example) Put any code blocks inside triple backticks: ```py your code here ``` --> (I originally posted about this on python-list a little over a week ago, but didn't get any replies.) I was playing around with 3.12.0b4 recently and noticed an odd (to me, at least) behavior with `types.get_original_bases()`. ```python >>> T = typing.TypeVar("T") >>> class FirstBase(typing.Generic[T]): ... pass ... >>> class SecondBase(typing.Generic[T]): ... pass ... >>> class First(FirstBase[int]): ... pass ... >>> class Second(SecondBase[int]): ... pass ... >>> class Example(First, Second): ... pass ... >>> types.get_original_bases(Example) (__main__.FirstBase[int],) >>> Example.__bases__ (<class '__main__.First'>, <class '__main__.Second'>) >>> types.get_original_bases(First) (__main__.FirstBase[int],) ``` In summary, `types.get_original_bases(Example)` is returning the original base types for `First`, rather than its own. I believe this happens because `__orig_bases__` is only set when one or more of a generic type's bases are not types. In this case both bases are types, so `Example` doesn't get its own `__orig_bases__`. Then when `types.get_original_bases()` tries to get `__orig_bases__` on `Example`, it searches the MRO and finds `__orig_bases__` on `First`. The same thing also happens if all the bases are &ldquo;bare&rdquo; generic types. ```python >>> class First(typing.Generic[T]): ... pass ... >>> class Second(typing.Generic[T]): ... pass ... >>> class Example(First, Second): ... pass ... >>> types.get_original_bases(Example) (typing.Generic[~T],) ``` I'm not entirely clear if this is a bug, or an intended (but unfortunate) behavior. I would personally expect `types.get_original_bases()` to check if the type has its *own* `__orig_bases__` attribute, and to fall back to `__bases__` otherwise. For example, the way it works currently makes it unnecessarily difficult to write a function that recurses down a type's inheritance tree inspecting the original bases&mdash;I currently have to work around this behavior via hacks like checking `"__orig_bases__" in cls.__dict__` or `any(types.get_original_bases(cls) == types.get_original_bases(base) for base in cls.__bases__)`. (Unless I'm missing some simpler solution.) Is this something that could (should?) be addressed before 3.12 lands? # Your environment <!-- Include all relevant details about the environment you experienced the bug in --> ```console % docker run -it --rm python:3.12-rc Python 3.12.0b4 (main, Jul 28 2023, 03:58:56) [GCC 12.2.0] on linux ``` <!-- You can freely edit this form. Remove any lines you believe are unnecessary. --> <!-- gh-linked-prs --> ### Linked PRs * gh-107584 * gh-107592 <!-- /gh-linked-prs -->
ed4a978449c856372d1a7cd389f91cafe2581c87
77e09192b5f1caf14cd5f92ccb53a4592e83e8bc
python/cpython
python__cpython-107896
# Update CI, Windows, and macOS installer builds to OpenSSL 3.0.10 3.0.10 released 2023-08-01. None of the changes *appear* to be critical to Python usage but ... <!-- gh-linked-prs --> ### Linked PRs * gh-107896 * gh-107897 * gh-108118 * gh-108119 * gh-108120 * gh-108121 * gh-108122 * gh-108123 * gh-108124 * gh-108928 * gh-108930 * gh-108932 <!-- /gh-linked-prs -->
ed25f097160b5cbb0c9a1f9a746d2f1bbc96515a
dd4442c8f597af1ec3eaf20f7ad89c4ac7e2dbc9
python/cpython
python__cpython-107594
# Multiple tests fail due to expired certificates if system date is set further than year 2037ish To test the readiness of Yocto stack for Y2038 we run qemu virtual machines with RTC set to some day in 2040. This causes many of python's tests to fail on both 32 bit and 64 bit systems: the reason is that test certificate expiry dates are set to 2037 or so by Lib/test/make_ssl_certs.py: ``` startdate = "20180829142316Z" enddate = "20371028142316Z" ``` I would propose to set the expiry date to far enough in the future that it won't have to be tweaked in our lifetimes: this way real Y2038 issues in python (or in things it depends on) can be exposed and fixed (it's well possible there are none, but that needs confirmation too). Failures seen: 6 tests failed: test_asyncio test_httplib test_imaplib test_poplib test_ssl test_urllib2_localnet If there's agreement on this, I can prepare the patch. <!-- gh-linked-prs --> ### Linked PRs * gh-107594 * gh-125104 <!-- /gh-linked-prs -->
53930cbe47529c4de9177538c98ffdb354b9854e
21c04e1a972bd1b6285e0ea41fa107d635bbe43a
python/cpython
python__cpython-107560
# Argument Clinic: param docstrings are not checked for non-ascii chars Also, the warning message is a little bit strange: _"Non-ascii character appear in docstring"_ Suggesting to change the warning message to _"Non-ascii characters are not allowed in docstrings: {offending char!r}"_, and move the check from `docstring_for_c_string()` to `docstring_append()`. The former is only called for function docstrings; the latter is called both for function and parameter docstrings. <!-- gh-linked-prs --> ### Linked PRs * gh-107560 <!-- /gh-linked-prs -->
9ff7b4af137b8028b04b52addf003c4b0607113b
439466a02b145b522a8969267264743706336501
python/cpython
python__cpython-107546
# misleading `setsockopt` error message # Bug report Running the following code works: ```py import socket with socket.socket() as s: s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2) ``` But if someone accidently passes a big value like so: ```py import socket with socket.socket() as s: s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2 ** 31) ``` He will get the follwing misleading error message: `TypeError: a bytes-like object is required, not 'int'` # Your environment - CPython versions tested on: 3.13.0a0 - Operating system and architecture: x64 Ubuntu 20.04 LTS and Win10 x64 22H2 <!-- gh-linked-prs --> ### Linked PRs * gh-107546 * gh-137411 <!-- /gh-linked-prs -->
a50822ff94ae0625f0b46480857fb141531c0688
7f416c867445dd94d11ee9df5f1a2d9d6eb8d883
python/cpython
python__cpython-108259
# json.dump(..., default=something) takes a unary function but is documented binary # Documentation ## TLDR The following documentation at https://docs.python.org/3.13/library/json.html suggests that `default` should be a member method but light testing shows that it should be unary. ## Documentation in Question *default(o)* Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a [TypeError](https://docs.python.org/3.13/library/exceptions.html#TypeError)). For example, to support arbitrary iterators, you could implement [default()](https://docs.python.org/3.13/library/json.html#json.JSONEncoder.default) like this: ``` def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) # Let the base class default method raise the TypeError return json.JSONEncoder.default(self, o) ``` ## Light testing The current documentation suggests the following pattern that never gets to `TypeError("binary")`: ``` import json def binary(a, b): raise TypeError("binary") # UNEXPECTED: TypeError: binary() missing 1 required positional argument: 'b' json.dumps({"sample": object()}, default=binary) ``` A unary function behaves like I expect, namely entering `unary(...)`: ``` import json def unary(a): raise TypeError("unary") # EXPECTED: TypeError: unary json.dumps({"sample": object()}, default=unary) ``` <!-- gh-linked-prs --> ### Linked PRs * gh-108259 <!-- /gh-linked-prs -->
ac31f714c3e55a7951a9f3f9c823740c20c5d595
891236f48263e2d4c650b7a127fc9bffb8327807
python/cpython
python__cpython-132273
# Inverted enum.Flag # Bug report ## Checklist - [X] I am confident this is a bug in CPython, not a bug in a third-party project - [X] I have searched the CPython issue tracker, and am confident this bug has not been reported before ## A clear and concise description of the bug Adding **inverted** option to enum.Flag brakes logic of enum. I assume it caused by ambiguous implementation of `bitwise NOT` in Flag which processes ~value option different inside class scope and outside class scope unlike `bitwise OR` ```py import enum class X(enum.Flag): a = enum.auto() b = enum.auto() c = a | b assert list(X) == [X.a, X.b] assert ~X.a == X.b assert list(~X.a) == [X.b] class Y(enum.Flag): a = enum.auto() b = enum.auto() c = a | b d = ~a # this line brakes the code assert list(Y) == [Y.a, Y.b] assert ~Y.a == Y.b # AssertionError assert list(~Y.a) == [Y.b] # ValueError: -2 is not a positive integer ``` Traceback: ``` bash Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/opt/homebrew/Cellar/python@3.11/3.11.4_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/enum.py", line 1482, in __iter__ yield from self._iter_member_(self._value_) File "/opt/homebrew/Cellar/python@3.11/3.11.4_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/enum.py", line 1359, in _iter_member_by_value_ for val in _iter_bits_lsb(value & cls._flag_mask_): File "/opt/homebrew/Cellar/python@3.11/3.11.4_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/enum.py", line 122, in _iter_bits_lsb raise ValueError('%r is not a positive integer' % original) ValueError: -2 is not a positive integer ``` # Your environment - CPython versions tested on: Clang 14.0.3 (clang-1403.0.22.14.1) - Operating system and architecture: 22.5.0 Darwin Kernel Version 22.5.0: Thu Jun 8 22:22:20 PDT 2023; root:xnu-8796.121.3~7/RELEASE_ARM64_T6000 arm64 <!-- gh-linked-prs --> ### Linked PRs * gh-132273 <!-- /gh-linked-prs -->
49365bd110a254a6a304d2f880482bfeb2e4490d
56c6f04b8862c20ff6eddc4400f170ad91e55f66
python/cpython
python__cpython-107542
# Help text of builtin functions – missing signatures I don't understand the deep details here but I think something went wrong in commit https://github.com/python/cpython/commit/bdfb6943861431a79e63f0da2e6b3fe163c12bc7 when some of the builtin functions where transferred to argument clinic. The problem I see is in the help texts of those functions. Here are a few examples of `help(<function>)`: ### iter Python 3.11.4 ``` Help on built-in function iter in module builtins: iter(...) iter(iterable) -> iterator iter(callable, sentinel) -> iterator Get an iterator from an object. In the first form, the argument must supply its own iterator, or be a sequence. In the second form, the callable is called until it returns the sentinel. ``` Python 3.12.0b4 ``` Help on built-in function iter in module builtins: iter(...) Get an iterator from an object. In the first form, the argument must supply its own iterator, or be a sequence. In the second form, the callable is called until it returns the sentinel. ``` As you can see, the help in 3.12 is talking about two forms but there are no signatures so it doesn't make sense. ### next Python 3.11.4 ``` Help on built-in function next in module builtins: next(...) next(iterator[, default]) Return the next item from the iterator. If default is given and the iterator is exhausted, it is returned instead of raising StopIteration. ``` Python 3.12.0b4 ``` Help on built-in function next in module builtins: next(...) Return the next item from the iterator. If default is given and the iterator is exhausted, it is returned instead of raising StopIteration. ``` Again, the help text talks about `iterator` and `default` but missing signature means that the reader might not know what those are. ### getattr Python 3.11.4 ``` Help on built-in function getattr in module builtins: getattr(...) getattr(object, name[, default]) -> value Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case. ``` Python 3.12.0b4 ``` Help on built-in function getattr in module builtins: getattr(...) Get a named attribute from an object. getattr(x, 'y') is equivalent to x.y When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case. ``` Again, a similar case here. <!-- gh-linked-prs --> ### Linked PRs * gh-107542 * gh-108187 * gh-130371 <!-- /gh-linked-prs -->
db6dc6ce41f42ec2cb4fdfbc0a099114f42e888f
05ef4ca94c694bc50e6fd221fe648d05d227f3a4
python/cpython
python__cpython-109900
# Move the Argument Clinic docs to the devguide See [topic on Discourse](https://discuss.python.org/t/where-should-the-argument-clinic-docs-live/30160?u=erlendaasland) and python/devguide#1148 Quoting from the linked topic: > Currently, the Argument Clinic docs live in the How-To section of docs.python.org: > > https://docs.python.org/3/howto/clinic.html. > > The devguide does not mention Argument Clinic at all (except in the experts section). > > The clinic docs's primary audience are core developers and contributors, which is also the primary audience of the devguide. I'd like to suggest we move the clinic docs from docs.python.org to devguide.python.org. So far, I've only received encouraging reactions, both on Discourse and on the core dev Discord. TODO: - [x] Filter out Doc/howto/clinic.rst - [x] Add the filtered out branch to the devguide: python/devguide#1160 - [x] Replace the clinic.rst contents with a link to the devguide and a short text about why the change was made <!-- gh-linked-prs --> ### Linked PRs * gh-109900 * gh-110760 * gh-110761 <!-- /gh-linked-prs -->
d1f7fae424d51b0374c8204599583c4a26c1a992
f83fa0b9eb1c11a4ef53275d77c603b97335eb23
python/cpython
python__cpython-107508
# Replace the "goals of Argument Clinic" with a link to PEP 436 The [Argument Clinic howto](https://docs.python.org/3/howto/clinic.html) starts with six paragraphs about the goals of Argument Clinic, mostly repeating the motivation and rationale of PEP-436. Here's a quick run-through of the paragraphs: 1. AC should take over arg parsing in CPython. 2. Hand-written arg parsing code is a chore; AC must be easy to use. 3. AC must generate correct and hopefully fast code; also an outdated section about the possibility of generating tailor made code for various cases. 4. AC should support all of CPython's "strange parsing behaviours". 5. AC should provide introspection signatures for builtins. 6. The last paragraph repeats information present in the tutorial. Suggesting to remove the whole "The goals of Argument Clinic", and instead provide a short summary (one or two sentences) and link to PEP-436. <!-- gh-linked-prs --> ### Linked PRs * gh-107508 * gh-107516 * gh-107517 <!-- /gh-linked-prs -->
abb71c6a8f73482c910ffdf050a86089a48e0e60
dfb55d9d7f9349582a2077f87e95c8f9d5e2ebd4
python/cpython
python__cpython-107569
# Ref leaks on `test_import` ``` ./python -m test -R : test_import 0:00:00 load avg: 0.27 Run tests sequentially 0:00:00 load avg: 0.27 [1/1] test_import beginning 9 repetitions 123456789 ......... test_import leaked [60, 60, 60, 60] references, sum=240 test_import leaked [48, 48, 48, 48] memory blocks, sum=192 test_import failed (reference leak) == Tests result: FAILURE == 1 test failed: test_import Total duration: 14.8 sec Tests result: FAILURE ``` tested on heads/main:a24e25d74b This result is also seen in many build bots, <details><summary>such as</summary> <p> https://buildbot.python.org/all/#/builders/562/builds/838 https://buildbot.python.org/all/#/builders/123/builds/802 https://buildbot.python.org/all/#/builders/562/builds/838 https://buildbot.python.org/all/#/builders/384/builds/829 </p> </details> <!-- gh-linked-prs --> ### Linked PRs * gh-107569 * gh-107571 <!-- /gh-linked-prs -->
017f047183fa33743f7e36c5c360f5c670032be3
bcdd3072316181b49d94567bb648825a07ca9ae1
python/cpython
python__cpython-107469
# Restructure Argument Clinic CLI Suggesting to ...: - [x] make the clinic tool a well-behaved command-line citizen; write to `stderr`, not `stdout`, on error (partly depends on #107468) - [x] put the whole CLI in `main`, making it easier to mock the tool in the test suite (currently we use subprocesses, which is slow, and requires several lines of boiler-plate test setup code) - [x] ~~Introduce CLIError and use it for usage errors~~ Used `ArgumentParser.error` instead. <!-- gh-linked-prs --> ### Linked PRs * gh-107469 <!-- /gh-linked-prs -->
49f238e78c36532bcbca7f9cd172703eb4df319b
557b05c7a5334de5da3dc94c108c0121f10b9191
python/cpython
python__cpython-107640
# Add `pathlib.Path.from_uri()` classmethod # Feature or enhancement Add `pathlib.Path.from_uri()` classmethod that creates a path objects from a 'file' URI, like `file:///c:/windows`. This method should accept [RFC 8089](https://datatracker.ietf.org/doc/html/rfc8089) `file:` URIs, including variant forms. # Pitch The proposed method is the counterpart of `pathlib.Path.as_uri()`. As we continue to open up pathlib for subclassing, user subclasses of path classes will begin to appear with their own `as_uri()` methods returning URIs like `s3://`, `ftp://`. These subclasses will likely also support parsing URIs to create paths. However, there is currently no defined interface for doing this in pathlib, and users will be tempted to accept URIs in initialisers, which produces a confusing interface. If pathlib instead defines a `from_uri()` classmethod, there is one clear and obvious method that subclasses may override. # Previous discussion See https://discuss.python.org/t/make-pathlib-extensible/3428/136 and subsequent posts <!-- gh-linked-prs --> ### Linked PRs * gh-107640 <!-- /gh-linked-prs -->
15de493395c3251b8b82063bbe22a379792b9404
06faa9a39bd93c5e7999d52b52043ecdd0774dac
python/cpython
python__cpython-107462
# ctypes: Add a testcase for nested `_as_parameter_` lookup A `ctypes` function can be called with custom objects if they define the `_as_parameter_` attribute: ```python from ctypes import * printf = CDLL('libc.so.6').printf class MyString: _as_parameter_ = b"abc" printf(b"String: %s\n", MyString()) # String: abc ``` The attribute is evaluated recursively so nested objects also work: ```python from ctypes import * printf = CDLL('libc.so.6').printf class Foo: _as_parameter_ = b"abc" class MyString: _as_parameter_ = Foo() printf(b"String: %s\n", MyString()) # String: abc ``` There is currently no test for this nested case so I think we should add one. <!-- gh-linked-prs --> ### Linked PRs * gh-107462 * gh-114858 * gh-114859 <!-- /gh-linked-prs -->
0bf42dae7e73febc76ea96fd58af6b765a12b8a7
59ae215387d69119f0e77b2776e8214ca4bb8a5e
python/cpython
python__cpython-107577
# test_tools are leaked ```python ./python -m test -R 3:3 test_tools Running Debug|x64 interpreter... 0:00:00 Run tests sequentially 0:00:00 [1/1] test_tools beginning 6 repetitions 123456 .C:\Users\KIRILL-1\CLionProjects\cpython\Modules\_decimal\libmpdec\context.c:57: warning: mpd_setminalloc: ignoring request to set MPD_MINALLOC a second time .C:\Users\KIRILL-1\CLionProjects\cpython\Modules\_decimal\libmpdec\context.c:57: warning: mpd_setminalloc: ignoring request to set MPD_MINALLOC a second time .C:\Users\KIRILL-1\CLionProjects\cpython\Modules\_decimal\libmpdec\context.c:57: warning: mpd_setminalloc: ignoring request to set MPD_MINALLOC a second time .C:\Users\KIRILL-1\CLionProjects\cpython\Modules\_decimal\libmpdec\context.c:57: warning: mpd_setminalloc: ignoring request to set MPD_MINALLOC a second time .C:\Users\KIRILL-1\CLionProjects\cpython\Modules\_decimal\libmpdec\context.c:57: warning: mpd_setminalloc: ignoring request to set MPD_MINALLOC a second time . test_tools leaked [1960, 1956, 1960] references, sum=5876 test_tools leaked [1075, 1073, 1075] memory blocks, sum=3223 test_tools failed (reference leak) in 46.3 sec == Tests result: FAILURE == 1 test failed: test_tools Total duration: 46.3 sec Tests result: FAILURE ``` Tried on current main <!-- gh-linked-prs --> ### Linked PRs * gh-107577 <!-- /gh-linked-prs -->
46366ca0486d07fe94c70d00771482c8ef1546fc
62a3a15119cf16d216a2cc7dc10d97143017ef62
python/cpython
python__cpython-108900
# Bytecode documentation issues for Python 3.12 As part of adding support for Python 3.12 to https://github.com/MatthieuDartiailh/bytecode I have identified a number of documentation issues both in the `dis`module documentation in the bytecode section of the `What's new in 3.12`. Opening a separate issue for each point would just clutter the issue tracker so I will try to summarize all my findings here. Issue in `dis` documentation ================== - [ ] COMPARE_OP oparg now uses the 4 lower bits as a cache. As a consequence: - [ ] the statement `The operation name can be found in cmp_op[opname]` is not true anymore. - [ ] the meaning of the cache is not documented but it can be != 0 even for a freshly compiled bytecode and as a consequence the difference is visible in `dis.dis` output - [ ] `MIN_INSTRUMENTED_OPCODE` is not documented but needed to determine what are the "normal" opcodes - [ ] `LOAD_SUPER_ATTR` description could use a code block to describe its stack effect IMO - [ ] `POP_JUMP_IF_NOT_NONE` and `POP_JUMP_IF_NONE` are still described as pseudo-instructions even though there are not anymore in 3.12 - [ ] `CALL_INSTRINSIC_2` stack manipulation description looks wrong. The description reads `Passes STACK[-2], STACK[-1] as the arguments and sets STACK[-1] to the result`, but the implementation pops 2 values from the stack - [ ] `END_SEND` is not documented - [ ] how to account for the presence of `CACHE` instructions following jumping instructions is not described (FOR_ITER and SEND for the time being) Issue in What's new ============= - [ ] `BINARY_SLICE` is not mentioned - [ ] `STORE_SLICE` is not mentioned - [ ] `CLEANUP_THROW` is not mentioned - [ ] `RETURN_CONST` is not mentioned - [ ] `LOAD_FAST_CHECK` is not mentioned - [ ] `END_SEND` is not mentioned - [ ] `CALL_INSTRINSIC_1/2` are not mentioned - [ ] `FOR_ITER` new behavior is not mentioned - [ ] The fact that `POP_JUMP_IF_*` family of instructions are now real instructions is not mentioned - [ ] `YIELD_VALUE` need for an argument is not mentioned - [ ] The addition of `dis.hasexc` is not mentioned <!-- gh-linked-prs --> ### Linked PRs * gh-108900 * gh-110985 <!-- /gh-linked-prs -->
198aa67d4ceb5298c3c60f7a77524f5ba084c121
24e4ec7766fd471deb5b7e5087f0e7dba8576cfb
python/cpython
python__cpython-107456
# ctypes: Improve error messages when converting to an incompatible type This code produces an error with a somewhat unhelpful message: ```python from ctypes import * printf = CDLL('libc.so.6').printf printf.argtypes = [c_char_p, c_char_p] printf(b"Value %s\n", 10) # call with an incompatible argument ``` ```python Traceback (most recent call last): File "/home/tomas/dev/cpython/error.py", line 5, in <module> printf(b"Value: %s\n", 10) ctypes.ArgumentError: argument 2: TypeError: wrong type ``` The source code itself suggests providing a better message: https://github.com/python/cpython/blob/3979150a0d406707f6d253d7c15fb32c1e005a77/Modules/_ctypes/_ctypes.c#L1795-L1797 I suggest making the message more helpful by including the expected argument type and the type that was actually provided e.g. ```diff - TypeError: wrong type + TypeError: 'int' object cannot be interpreted as ctypes.c_char_p ``` The same improvement can be applied to `c_wchar_p` and `c_void_p`. <!-- gh-linked-prs --> ### Linked PRs * gh-107456 <!-- /gh-linked-prs -->
62a3a15119cf16d216a2cc7dc10d97143017ef62
1cd479c6d371605e9689c88ae1789dbcbceb2da0
python/cpython
python__cpython-107486
# ``errno`` documentation missing several constants The [``errno`` documentation](https://docs.python.org/3/library/errno.html) doesn't have: * errno.ECANCELED * errno.EOWNERDEAD * errno.ENOTRECOVERABLE * errno.ENOTSUP Reference: [errno(3) man page](https://linux.die.net/man/3/errno) <!-- gh-linked-prs --> ### Linked PRs * gh-107486 * gh-108365 * gh-108529 * gh-108530 <!-- /gh-linked-prs -->
1ac64237e6ce965064451ed57ae37271aeb9fbd3
6cb48f049501c9f8c5be107e52f8eb359b5ac533
python/cpython
python__cpython-110754
# string length overflows to negative when executing # Bug report ## Checklist - [x] I am confident this is a bug in CPython, not a bug in a third-party project - [x] I have searched the CPython issue tracker, and am confident this bug has not been reported before ## A clear and concise description of the bug The following code causes an error to be raised in all tested versions of Python. ```py exec(f"if True:\n {' ' * 2**31}print('hello world')") ``` Which error is raised varies by version, and as such the specific error message is listed with its corresponding version in the below section. Some (hopefully) helpful information: - I have confirmed that the creation of the string is not causing a problem (by creating it separately, storing it in a variable, and *then* `exec`'ing it), the problem occurs when attempting to `exec` it. - I have confirmed that the issue is does not occur solely because of the large string. (The same issue does not occur when I use a value of, for example, `2**33`). ### NOTE: I believe that this error will also occur when running real file rather than building a string and using `exec`, but I have not yet confirmed that. # Your environment I tested this in three environments, with as many versions of Python as I could conveniently use. ### Arch GNU/Linux * Operating system and architecture: - Operating system: `Arch GNU/Linux` - CPU: Intel(R) Core(TM) i7-4980HQ CPU @ 2.80GHz 2.80 GHz * CPython versions: - `Python 3.10.10 (main, Mar 5 2023, 22:56:53) [GCC 12.2.1 20230201]` * `IndentationError: unindent does not match any outer indentation level` - `Python 3.11.3 (main, Jun 5 2023, 09:32:32) [GCC 13.1.1 20230429]` * `SystemError: Negative size passed to PyUnicode_New` ### Microsoft Windows 10 * Operating system and architecture: - Operating system: `Microsoft Windows 10 (version 22H2 build 19045.3208)` inside a VirtualBox virtual machine - CPU: Intel(R) Core(TM) i7-4980HQ CPU @ 2.80GHz 2.80 GHz * CPython versions: - `Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 16:30:00) [MSC v.1900 64 bit (AMD64)]` * `IndentationError: None` - `Python 3.8.10 (tags/v3.8.10:3d8993a, May 3 2021, 11:48:03) [MSC v.1928 64 bit (AMD64)]` * `IndentationError: None` - `Python 3.9.13 (tags/v3.9.13:6de2ca5, May 17 2022, 16:36:42) [MSC v.1929 64 bit (AMD64)]` * `IndentationError: unindent does not match any outer indentation level` - `Python 3.10.11 (tags/v3.10.11:7d4cc5a, Apr 5 2023, 00:38:17) [MSC v.1929 64 bit (AMD64)]` * `IndentationError: unindent does not match any outer indentation level` - `Python 3.11.4 (tags/v3.11.4:d2340ef, Jun 7 2023, 05:45:37) [MSC v.1934 64 bit (AMD64)]` * `SystemError: Negative size passed to PyUnicode_New` ### Ubuntu GNU/Linux * Operating system and architecture: - Operating system: `Ubuntu 22.04 GNU/Linux` inside a VirtualBox virtual machine - CPU: Intel(R) Core(TM) i7-4980HQ CPU @ 2.80GHz 2.80 GHz * CPython versions: - `Python 3.7.17 (default, Jun 6 2023, 20:10:09) [GCC 11.3.0]` * `IndentationError: None` - `Python 3.8.17 (default, Jun 6 2023, 20:10:50) [GCC 11.3.0]` * `IndentationError: None` - `Python 3.9.17 (main, Jun 6 2023, 20:11:21) [GCC 11.3.0]` * `IndentationError: unindent does not match any outer indentation level` - `Python 3.10.6 (main, May 29 2023, 11:10:38) [GCC 11.3.0]` * `IndentationError: unindent does not match any outer indentation level` - `Python 3.11.4 (main, Jun 7 2023, 12:45:48) [GCC 11.3.0]` * `SystemError: Negative size passed to PyUnicode_New` ### Should any further information be required about the environments that I used, please ask. # What I believe causes the problem I suspect very strongly that the error occurs as a result of an integer overflow. (A value larger than `2**31 - 1` will overflow and become negative when using 2's complement with 32 bit signed integers). # Possible solution I think that this can be fixed by using a 64 bit integer to hold the length of the string while 64 bit platforms. This, while still leaving the error *theoretically* possible, would in practice avoid the error entirely because one would encounter a `MemoryError` first. <!-- gh-linked-prs --> ### Linked PRs * gh-110754 * gh-110762 * gh-110763 * gh-110768 * gh-110801 * gh-110808 * gh-110809 * gh-110810 * gh-110832 * gh-110871 * gh-110931 * gh-110939 * gh-110940 <!-- /gh-linked-prs -->
fb7843ee895ac7f6eeb58f356b1a320eea081cfc
3d180347ae73119bb51500efeeafdcd62bcc6f78
python/cpython
python__cpython-107451
# test_inspect fails with `--forever` argument Traceback: ```python ...many lines... test_unwrap_several (test.test_inspect.TestUnwrap.test_unwrap_several) ... ok ====================================================================== ERROR: test_class_with_method_from_other_module (test.test_inspect.TestBuggyCases.test_class_with_method_from_other_module) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\KIRILL-1\CLionProjects\cpython\Lib\test\test_inspect.py", line 992, in test_class_with_method_from_other_module self.assertIn("correct", inspect.getsource(inspect_actual.A)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\KIRILL-1\CLionProjects\cpython\Lib\inspect.py", line 1317, in getsource lines, lnum = getsourcelines(object) ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\KIRILL-1\CLionProjects\cpython\Lib\inspect.py", line 1299, in getsourcelines lines, lnum = findsource(object) ^^^^^^^^^^^^^^^^^^ File "C:\Users\KIRILL-1\CLionProjects\cpython\Lib\inspect.py", line 1134, in findsource raise OSError('could not get source code') OSError: could not get source code ---------------------------------------------------------------------- Ran 286 tests in 2.392s FAILED (errors=1) test test_inspect failed test_inspect failed (1 error) == Tests result: FAILURE == 1 test OK. 1 test failed: test_inspect Total duration: 7.2 sec Tests result: FAILURE ``` Triend on current main. <!-- gh-linked-prs --> ### Linked PRs * gh-107451 <!-- /gh-linked-prs -->
14fbd4e6b16dcbcbff448b047f7e2faa27bbedba
ed4a978449c856372d1a7cd389f91cafe2581c87
python/cpython
python__cpython-107443
# ctypes `_as_parameter_` does not mention all possible types # Documentation The `_as_parameter_` attribute can be used when one wants to pass a custom object a `ctypes` function. The [documentation](https://docs.python.org/3/library/ctypes.html?highlight=ctypes#calling-functions-with-your-own-custom-data-types) says: > it must be one of integer, string, or bytes However, one can also use a `ctypes` instance or another object which itself has the `_as_parameter_` attribute. The documentation should be updated to include these two additional possibilities. <!-- gh-linked-prs --> ### Linked PRs * gh-107443 * gh-107707 * gh-107718 <!-- /gh-linked-prs -->
6925c578a0e3cbb00858e64da813a7ffe79623c4
a6675b1a597c67be972598ac8562883fabe48099
python/cpython
python__cpython-107433
# multiprocessing manager classes DictProxy and ListProxy don't support typing in 3.11.4 # Bug report `DictProxy` and `ListProxy` classes from `multiprocessing.managers` do not support generic annotations. Minimal reproducible example for `DictProxy`: ```py from multiprocessing.managers import DictProxy from multiprocessing import Manager d: DictProxy[str, float] = Manager().dict() ``` Error: ```error Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: type 'DictProxy' is not subscriptable ``` Similar for `ListProxy` Side note: https://github.com/python/cpython/issues/99509 appears to still be an issue as well # Your environment Python 3.11.4 (tags/v3.11.4:d2340ef, Jun 7 2023, 05:45:37) [MSC v.1934 64 bit (AMD64)] on win32 <!-- gh-linked-prs --> ### Linked PRs * gh-107433 <!-- /gh-linked-prs -->
ae8116cfa944dccad13638f6875b33b98d285b63
06c47a305d8f7f4f56a1113d9eb2eddcc175f2ed
python/cpython
python__cpython-107429
# The description of UNPACK_SEQUENCE should be fixed. # Documentation The current description of UNPACK_SEQUENCE is as follows: ````` STACK.extend(STACK.pop()[:count:-1]) ````` It will not extend the stack since the count is a positive value. It should be fixed into ````` STACK.extend(STACK.pop()[:-count-1:-1]) ````` <!-- gh-linked-prs --> ### Linked PRs * gh-107429 * gh-107459 <!-- /gh-linked-prs -->
a24e25d74bb5d30775a61853d34e0bb5a7e12c64
3979150a0d406707f6d253d7c15fb32c1e005a77
python/cpython
python__cpython-107613
# Use True/False instead of 1/0 in OrderedDict popitem example # Documentation https://docs.python.org/3.12/library/collections.html#ordereddict-examples-and-recipes The documentation implements a `TimeBoundedLRU` and a `MultiHitLRUCache` with `OrderedDict`. Both implementations contain `self.cache.popitem(0)` where `self.cache` is an `OrderedDict` instance. However, method `popitem()` actually takes a boolean argument indicating whether to pop from the left end or the right end of the `OrderedDict` instance. Though `0` means `False`, using `0` will mislead readers into passing an *arbitrary* integer as an index to this method to pop the corresponding item from the OrderedDict. Changing `0` to `False` improves clarity, and avoids complaints from a type checker. `self.requests.popitem(0)` in the implementation of `MultiHitLRUCache` has the same issue. In addition, `self.requests.pop(args, None)` in the implementation of `MultiHitLRUCache` should be changed to `self.requests.pop(args)` since the statements preceding it have already guaranteed that `self.requests` has key args. This change will reduce readers' work to think about when `self.requests` would not have key args. <!-- gh-linked-prs --> ### Linked PRs * gh-107613 <!-- /gh-linked-prs -->
23a6db98f21cba3af69a921f01613bd5f602bf6d
50bbc56009ae7303d2482f28eb62f2603664b58f
python/cpython
python__cpython-107410
# `reprlib.recursive_repr` is not setting `.__wrapped__` attribute # Bug report There is no way to get original actual `__repr__` function after applying `@recursive_repr` decorator ```py import reprlib class X: @reprlib.recursive_repr() def __repr__(self) -> str: return f'X({self.__dict__})' # how to get initial X.__repr__ back? # this doesn't work: X.__repr__.__wrapped__ # AttributeError: 'function' object has no attribute '__wrapped__' # this is awful: X.__repr__.__closure__[2].cell_contents ``` # Your environment - CPython versions tested on: 3.11, 3.13.0a0 <!-- gh-linked-prs --> ### Linked PRs * gh-107410 <!-- /gh-linked-prs -->
4845b9712f2c187743344eca43fa1fb896bddfd6
0f2fb6efb4d5d8ca43a0e779b89a8e805880e09a
python/cpython
python__cpython-107407
# better `struct.Struct` repr # Feature or enhancement Add better `struct.Struct` repr # Pitch ```py >>> import struct >>> struct.Struct('i') <_struct.Struct at 0x00223FC2C7290> ``` Hmm, what is the format of this struct? It is not clear from repr. Something like this would be better: ```py >>> import struct >>> struct.Struct('i') Struct('i') ``` <!-- gh-linked-prs --> ### Linked PRs * gh-107407 <!-- /gh-linked-prs -->
e407cea1938b80b1d469f148a4ea65587820e3eb
8ba47146111d714c7b61825d43b52311d9be366d
python/cpython
python__cpython-107485
# tarfiles: `AttributeError: '_Stream' object has no attribute 'exception'` while trying to open tgz file # Bug report If a tar file appears to be a `tar.gz` file, it can fail in this block of `tarfile.py` ``` while c < size: # Skip underlying buffer to avoid unaligned double buffering. if self.buf: buf = self.buf self.buf = b"" else: buf = self.fileobj.read(self.bufsize) if not buf: break try: buf = self.cmp.decompress(buf) except self.exception as e: raise ReadError("invalid compressed data") from e t.append(buf) c += len(buf) ``` at: ``` buf = self.cmp.decompress(buf) ``` before `self.exception` is set. Because around: ``` if comptype == "gz": try: import zlib except ImportError: raise CompressionError("zlib module is not available") from None self.zlib = zlib self.crc = zlib.crc32(b"") if mode == "r": self._init_read_gz() self.exception = zlib.error else: self._init_write_gz() ``` This: `self._init_read_gz()` is called before `self.exception = zlib.error` Stack trace: ``` _read, tarfile.py:548 read, tarfile.py:526 _init_read_gz, tarfile.py:491 __init__, tarfile.py:375 open, tarfile.py:1827 <module>, test.py:2 ``` In my case, `buf = self.cmp.decompress(buf)` failed to execute but that's a separate issue that may or may not be a bug # Your environment <!-- Include as many relevant details as possible about the environment you experienced the bug in --> - CPython versions tested on: 3.11.4 - Operating system and architecture: Windows 10 21H2 <!-- gh-linked-prs --> ### Linked PRs * gh-107485 * gh-108207 * gh-108208 <!-- /gh-linked-prs -->
37135d25e269ede92bc7da363bebfa574782e59a
80bdebdd8593f007a2232ec04a7729bba6ebf12c
python/cpython
python__cpython-107374
# Optimize textwrap.indent() Current code: ```py def indent(text, prefix, predicate=None): """Adds 'prefix' to the beginning of selected lines in 'text'. If 'predicate' is provided, 'prefix' will only be added to the lines where 'predicate(line)' is True. If 'predicate' is not provided, it will default to adding 'prefix' to all non-empty lines that do not consist solely of whitespace characters. """ if predicate is None: def predicate(line): return line.strip() def prefixed_lines(): for line in text.splitlines(True): yield (prefix + line if predicate(line) else line) return ''.join(prefixed_lines()) ``` * `predicate = str.strip` is faster than `def predicate(line)` * `''.join(x)` converts input iterable to sequence. Using generator just makes overhead. * creating temporary `prefix + line` is avoidable. <!-- gh-linked-prs --> ### Linked PRs * gh-107374 * gh-131923 <!-- /gh-linked-prs -->
37551c9cef307ca3172c60b28c7de9db921808ad
f2d07d3289947d10b065b2bb7670c8fb6b6582f2
python/cpython
python__cpython-112389
# `ssl.create_default_context()`: add `VERIFY_X509_STRICT` and `VERIFY_X509_PARTIAL_CHAIN` to the default `verify_flags` # Feature or enhancement My proposal is to add two new flags to the `SSLContext.verify_flags` created within `ssl.create_default_context()`: 1. `VERIFY_X509_STRICT`: This will enable stricter RFC 5280 compliance checks within OpenSSL's X.509 path validation implementation. This will have no effect on the overwhelming majority of users (since the overwhelming majority of TLS connections are likely going through the Web PKI, which is already much stricter than RFC 5280). 2. `VERIFY_X509_PARTIAL_CHAIN`: This will allow OpenSSL's path validation to terminate at the first certificate listed in the user's root of trust, even if that certificate is not self-signed. Despite the confusing name and the fact that this isn't the default, this *is* the correct behavior per the various X.509 RFCs ([3280](https://datatracker.ietf.org/doc/html/rfc3280), [5280](https://datatracker.ietf.org/doc/html/rfc5280)): a trust anchor is defined to be an a priori trust relationship with a subject and its public key, regardless of whether the anchor comes in certificate form or is signed by another member of the trusted store. This should have no *breaking* effect on any users, but *may* cause some validations to produce shorter chains than the current `SSLContext` enables. My proposal is consistent with the stability policy for [`create_default_context`](https://docs.python.org/3/library/ssl.html#ssl.create_default_context), which says that CPython may introduce changes to the *default* context without a prior deprecation period: > The protocol, options, cipher and other settings may change to more restrictive values anytime without prior deprecation. The values represent a fair balance between compatibility and security. As with previous changes to the default context (such as the removal of 3DES support with 3.6), these proposed changes will not prevent people from constructing their own `SSLContext` without these new flags. In other words: users who do experience breakage or other behavioral changes will have a well-trodden alternative available to them, one that is documented as a matter of policy. # Pitch To summarize from DPO: * Enabling `VERIFY_X509_STRICT` is a net security win: it reduces the amount of flexibility in the X.509 certificates that the `ssl` module accepts by default, which means less attacker controlled flexibility. It also makes CPython itself more compatible with the X.509 profile defined in RFC 5280, meaning that end-users can more confidently expect interoperation with PKIs that use the 5280 profile. * Enabling `VERIFY_X509_PARTIAL_CHAIN` makes `ssl` comply more closely with other path validation/building implementations (like Go's), and eliminates an error mode that's only possible because of OpenSSL's non-standard default behavior (a chain is built to the root of trust successfully, but can still fail because OpenSSL can't find a self-signed root also within the root of trust). It's also consistent with what [curl](https://github.com/curl/curl/pull/4655) and other downstream consumers of OpenSSL do. # Previous discussion See DPO discussion here: https://discuss.python.org/t/ssl-changing-the-default-sslcontext-verify-flags/30230 <!-- gh-linked-prs --> ### Linked PRs * gh-112389 <!-- /gh-linked-prs -->
0876b921b28bb14e3fa61b188e52fc9b4c77cb1a
ea1803e608a7aaf9cf2c07e510d8540d46d3b9ad
python/cpython
python__cpython-107296
# zipapp docs should not suggest deleting .dist-info subdirectories From [_Creating Standalone Applications with zipapp_](https://docs.python.org/3/library/zipapp.html#creating-standalone-applications-with-zipapp), point 3 mentions you may delete .dist-info directories "_as you won’t be making any further use of pip they aren’t required_". But you can have a nasty surprise this way - the problem is that this totally breaks `importlib.metadata` usage. E.g. if you have an argparse `--version` in your app which uses `importlib.metadata.version("myapp")`, but you've unlinked all the .dist-info metadata before making the zipapp, you'll get: ``` importlib.metadata.PackageNotFoundError: No package metadata was found for myapp ``` We don't know if/when third party libraries want to look at their own package metadata, so I think this suggestion in the docs should be removed outright. <!-- gh-linked-prs --> ### Linked PRs * gh-107296 * gh-109281 * gh-109282 <!-- /gh-linked-prs -->
1ee50e2a78f644d81d341a08562073ad169d8cc7
bcce5e271815c0bdbe894964e853210d2c75949b
python/cpython
python__cpython-107400
# Update the importlib Docs for PEP 684 # Documentation https://docs.python.org/3.12/library/importlib.html#module-importlib.util * add an entry for `importlib.util._incompatible_extension_module_restrictions()` https://docs.python.org/3.12/library/importlib.html#importlib.machinery.ExtensionFileLoader * update `ExtensionFileLoader` about when imports may fail (See https://peps.python.org/pep-0684/ and gh-99113.) <!-- gh-linked-prs --> ### Linked PRs * gh-107400 * gh-107413 <!-- /gh-linked-prs -->
cf63df88d38ec3e6ebd44ed184312df9f07f9782
8ba4df91ae60833723d8d3b9afeb2b642f7176d5
python/cpython
python__cpython-107403
# Add a Docs Entry for the New Py_mod_multiple_interpreters Module Def Slot # Documentation https://docs.python.org/3.12/c-api/module.html?highlight=py_mod_create#c.PyModuleDef_Slot https://docs.python.org/3.12/howto/isolating-extensions.html (See https://peps.python.org/pep-0684/ and gh-99113.) <!-- gh-linked-prs --> ### Linked PRs * gh-107403 * gh-107521 <!-- /gh-linked-prs -->
fb344e99aa0da5bef9318684ade69978585fe060
abb71c6a8f73482c910ffdf050a86089a48e0e60
python/cpython
python__cpython-107324
# Update the C-API "Sub-interpreter support" Section for PEP 684 # Documentation https://docs.python.org/3.12/c-api/init.html#sub-interpreter-support * add an entry for `Py_NewInterpreterFromConfig()` and `PyInterpreterConfig` * section about the consequences of a Per-interpreter GIL * fix `Py_EndInterpreter()` (and `Py_NewInterpreter()`?) about holding GIL before/after (See https://peps.python.org/pep-0684/ and gh-99113.) <!-- gh-linked-prs --> ### Linked PRs * gh-107324 * gh-107402 <!-- /gh-linked-prs -->
c0b81c4b5438a3565fadd9d6f5bc69f989a3fdee
ecc05e23a1f4086645cfb5362c4c1351f70a4eb1
python/cpython
python__cpython-107300
# Fix Sphinx warnings in the C API documentation Recently, I saw a growing numbers of Sphinx warnings displayed as annotations which make reviews harder. I create this issue to track changes fixing warnings. See also gh-106948 which populates ``nitpick_ignore`` of ``Doc/conf.py`` with standard C functions, variables, macros and env vars. <!-- gh-linked-prs --> ### Linked PRs * gh-107300 * gh-107302 * gh-107304 * gh-107316 * gh-107329 * gh-107332 * gh-107333 * gh-107345 * gh-107370 * gh-107371 * gh-107373 * gh-107375 * gh-107376 * gh-107377 * gh-107380 * gh-107381 * gh-108011 * gh-108029 * gh-108034 * gh-108041 * gh-108048 * gh-108070 * gh-108071 * gh-108072 * gh-108074 * gh-108076 * gh-108077 * gh-108225 * gh-108226 * gh-108233 * gh-108234 * gh-108258 * gh-108284 * gh-108290 * gh-108361 * gh-109129 * gh-109236 * gh-109947 * gh-109948 <!-- /gh-linked-prs -->
87b39028e5f453a949a1675526c439f6479a04a8
b1de3807b832b72dfeb66dd5646159d08d2cc74a
python/cpython
python__cpython-107280
# Add `<stddef.h>` to `Modules/zlibmodule.c` to fix failing builds # Bug report Commits fabcbe9c12688eb9a902a5c89cb720ed373625c5, 6a43cce32b66e0f66992119dd82959069b6f324a, and 2b1a81e2cfa740609d48ad82627ae251262e6470 (and likely other commits) are failing during the build step with the following error: ``` ../Modules/zlibmodule.c:1802:21: error: implicit declaration of function ‘offsetof’ [-Werror=implicit-function-declaration] #define COMP_OFF(x) offsetof(compobject, x) ^~~~~~~~ ../Modules/zlibmodule.c:1804:39: note: in expansion of macro ‘COMP_OFF’ {"unused_data", _Py_T_OBJECT, COMP_OFF(unused_data), Py_READONLY}, ^~~~~~~~ ../Modules/zlibmodule.c:1802:21: note: ‘offsetof’ is defined in header ‘<stddef.h>’; did you forget to ‘#include <stddef.h>’? ../Modules/zlibmodule.c:1776:1: +#include <stddef.h> ../Modules/zlibmodule.c:1802:21: #define COMP_OFF(x) offsetof(compobject, x) ^~~~~~~~ ../Modules/zlibmodule.c:1804:39: note: in expansion of macro ‘COMP_OFF’ {"unused_data", _Py_T_OBJECT, COMP_OFF(unused_data), Py_READONLY}, ^~~~~~~~ ../Modules/zlibmodule.c:1802:30: error: expected expression before ‘compobject’ #define COMP_OFF(x) offsetof(compobject, x) ^~~~~~~~~~ ../Modules/zlibmodule.c:1804:39: note: in expansion of macro ‘COMP_OFF’ {"unused_data", _Py_T_OBJECT, COMP_OFF(unused_data), Py_READONLY}, ^~~~~~~~ ../Modules/zlibmodule.c:1802:30: error: expected expression before ‘compobject’ #define COMP_OFF(x) offsetof(compobject, x) ^~~~~~~~~~ ../Modules/zlibmodule.c:1805:39: note: in expansion of macro ‘COMP_OFF’ {"unconsumed_tail", _Py_T_OBJECT, COMP_OFF(unconsumed_tail), Py_READONLY}, ^~~~~~~~ ../Modules/zlibmodule.c:1802:30: error: expected expression before ‘compobject’ #define COMP_OFF(x) offsetof(compobject, x) ^~~~~~~~~~ ../Modules/zlibmodule.c:1806:38: note: in expansion of macro ‘COMP_OFF’ {"eof", Py_T_BOOL, COMP_OFF(eof), Py_READONLY}, ^~~~~~~~ ../Modules/zlibmodule.c:1820:33: error: expected expression before ‘ZlibDecompressor’ {"eof", Py_T_BOOL, offsetof(ZlibDecompressor, eof), ^~~~~~~~~~~~~~~~ ../Modules/zlibmodule.c:1820:24: error: initializer element is not constant {"eof", Py_T_BOOL, offsetof(ZlibDecompressor, eof), ^~~~~~~~ ../Modules/zlibmodule.c:1820:24: note: (near initialization for ‘ZlibDecompressor_members[0].offset’) ../Modules/zlibmodule.c:1822:46: error: expected expression before ‘ZlibDecompressor’ {"unused_data", Py_T_OBJECT_EX, offsetof(ZlibDecompressor, unused_data), ^~~~~~~~~~~~~~~~ ../Modules/zlibmodule.c:1822:37: error: initializer element is not constant {"unused_data", Py_T_OBJECT_EX, offsetof(ZlibDecompressor, unused_data), ^~~~~~~~ ../Modules/zlibmodule.c:1822:37: note: (near initialization for ‘ZlibDecompressor_members[1].offset’) ../Modules/zlibmodule.c:1824:41: error: expected expression before ‘ZlibDecompressor’ {"needs_input", Py_T_BOOL, offsetof(ZlibDecompressor, needs_input), Py_READONLY, ^~~~~~~~~~~~~~~~ ../Modules/zlibmodule.c:1824:32: error: initializer element is not constant {"needs_input", Py_T_BOOL, offsetof(ZlibDecompressor, needs_input), Py_READONLY, ^~~~~~~~ ../Modules/zlibmodule.c:1824:32: note: (near initialization for ‘ZlibDecompressor_members[2].offset’) cc1: some warnings being treated as errors make: *** [Makefile:2998: Modules/zlibmodule.o] Error 1 ``` # Your environment This is occurring in the python/cpython CICD pipeline. Clicking on the ❌ icon in the commits linked to above and checking the logs for the failing builds shows the error. Examples: - https://buildbot.python.org/all/#/builders/15/builds/5217/steps/4/logs/stdio - https://buildbot.python.org/all/#/builders/15/builds/5219/steps/4/logs/stdio <!-- gh-linked-prs --> ### Linked PRs * gh-107280 <!-- /gh-linked-prs -->
4b2e54bd3c23da37923a18ae5e82cfd574e9a439
abec9a1b20b70d8ced401d59fc4f02b331c6568b
python/cpython
python__cpython-107535
# Regression in 3.12 beta in json.dump deeply nested dict This was reported here: https://discuss.python.org/t/has-sys-setrecursionlimit-behaviour-changed-in-python-3-12b/30205 The following program works fine on 3.11, but crashes with RecursionError on 3.12: ``` d = {} for x in range(1_000): d = {'k': d} import json, sys sys.setrecursionlimit(100_000_000) foo = json.dumps(d) ``` I confirmed this bisects to https://github.com/python/cpython/pull/96510 <!-- gh-linked-prs --> ### Linked PRs * gh-107535 * gh-107618 <!-- /gh-linked-prs -->
fa45958450aa3489607daf9855ca0474a2a20878
0bd784b355edf0d1911a7830db5d41c84171e367
python/cpython
python__cpython-119322
# Tkinter: test failure due to Tk 8.6.14 listbox bugfix The current output of the `itemconfigure` command for listbox widgets falsely suggests that the configuration of listbox items is influenced by the options database (if I understand correctly). This will be fixed in Tk 8.6.14: see https://core.tcl-lang.org/tk/info/ed8eae599d76 and https://core.tcl-lang.org/tk/vdiff?from=edf00be1&to=025022a4 Although `tkinter.Listbox.itemconfigure()` will still work properly, test.test_tkinter.test_widgets.ListboxTest.test_itemconfigure will fail since it expects the erroneous output: ``` ====================================================================== FAIL: test_itemconfigure (test.test_tkinter.test_widgets.ListboxTest.test_itemconfigure) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/user/git/cpython/Lib/test/test_tkinter/test_widgets.py", line 1002, in test_itemconfigure self.assertEqual(widget.itemconfigure(0, 'background'), AssertionError: Tuples differ: ('background', '', '', '', 'red') != ('background', 'background', 'Background', '', 'red') First differing element 1: '' 'background' - ('background', '', '', '', 'red') + ('background', 'background', 'Background', '', 'red') ``` <!-- gh-linked-prs --> ### Linked PRs * gh-119322 * gh-119806 * gh-119807 * gh-130274 * gh-130275 * gh-130276 <!-- /gh-linked-prs -->
9732ed5ca94cd8fe9ca2fc7ba5a42dfa2b7791ea
ef01e95ae3659015c2ebe4ecdc048aadcda89930
python/cpython
python__cpython-107250
# Implement Py_UNUSED() for Windows MSVC compiler The ``Py_UNUSED()`` is not implemented for the Windows MSVC compiler. Example with this function included by Python.h: see https://github.com/python/cpython/pull/107239#issuecomment-1649982534 ``` static inline unsigned int PyUnicode_IS_READY(PyObject* Py_UNUSED(op)) { return 1; } ``` Without my change, building a C program with ``cl /W4`` which just includes Python.h emits the warning: ``` Include\cpython/unicodeobject.h(199): warning C4100: '_unused_op': unreferenced formal parameter ``` With my change, no warnings are emitted! <!-- gh-linked-prs --> ### Linked PRs * gh-107250 * gh-127907 <!-- /gh-linked-prs -->
6a43cce32b66e0f66992119dd82959069b6f324a
fabcbe9c12688eb9a902a5c89cb720ed373625c5
python/cpython
python__cpython-107238
# test_logging: test_udp_reconnection() fails randomly Example on Linux: ``` $ ./python -m test test_logging -m test_udp_reconnection -F -j100 -v == CPython 3.13.0a0 (heads/remove_structmember:438462a3a0, Jul 25 2023, 14:21:21) [GCC 13.1.1 20230614 (Red Hat 13.1.1-4)] == Linux-6.3.12-200.fc38.x86_64-x86_64-with-glibc2.37 little-endian == Python build: debug == cwd: /home/vstinner/python/main/build/test_python_694431æ == CPU count: 12 == encodings: locale=UTF-8, FS=utf-8 0:00:00 load avg: 4.60 Run tests in parallel using 100 child processes (...) 0:00:10 load avg: 20.39 [ 18] test_logging passed test_udp_reconnection (test.test_logging.IPv6SysLogHandlerTest.test_udp_reconnection) ... ok test_udp_reconnection (test.test_logging.SysLogHandlerTest.test_udp_reconnection) ... ok test_udp_reconnection (test.test_logging.UnixSysLogHandlerTest.test_udp_reconnection) ... ok ---------------------------------------------------------------------- Ran 3 tests in 0.305s OK 0:00:10 load avg: 20.39 [ 19/1] test_logging failed (1 failure) test_udp_reconnection (test.test_logging.IPv6SysLogHandlerTest.test_udp_reconnection) ... FAIL test_udp_reconnection (test.test_logging.SysLogHandlerTest.test_udp_reconnection) ... ok test_udp_reconnection (test.test_logging.UnixSysLogHandlerTest.test_udp_reconnection) ... ok ====================================================================== FAIL: test_udp_reconnection (test.test_logging.IPv6SysLogHandlerTest.test_udp_reconnection) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/vstinner/python/main/Lib/test/test_logging.py", line 2101, in test_udp_reconnection self.assertEqual(self.log_output, b'<11>sp\xc3\xa4m\x00') AssertionError: b'' != b'<11>sp\xc3\xa4m\x00' (...) ``` <!-- gh-linked-prs --> ### Linked PRs * gh-107238 * gh-107242 * gh-107243 * gh-107245 <!-- /gh-linked-prs -->
ed082383272c2c238e364e9cc83229234aee23cc
6261585d63a31835b65d445d99dc14cca3fe9cf5
python/cpython
python__cpython-107227
# PyModule_AddObjectRef() should only be in the limited API since 3.10 `PyModule_AddObjectRef()` was added in 3.10, but if use the limited API, it is available in all versions, independently from tha value of Py_LIMITED_API. @vstinner <!-- gh-linked-prs --> ### Linked PRs * gh-107227 * gh-107260 * gh-107261 <!-- /gh-linked-prs -->
698b01513550798886add5e06a1c3f9a89d7dfc6
b5ae7c498438657a6ba0bf4cc216b9c2c93a06c7
python/cpython
python__cpython-108974
# test_concurrent_futures.test_deadlock: test_crash_big_data() hangs randomly on Windows GHA Windows x86 job, test_crash_big_data() hangs on ``ProcessPoolExecutor.shutdown()``: https://github.com/python/cpython/actions/runs/5651960914/job/15310873235?pr=107217 * Main thread: ``ProcessPoolExecutor.shutdown()`` * Thread 2: ``Threading.join()`` * Thread 3: queue ``_feed()`` => connection ``send_bytes()`` ``` (...) 0:39:52 load avg: 0.06 running: test_concurrent_futures (19 min 2 sec) 0:40:22 load avg: 0.05 running: test_concurrent_futures (19 min 32 sec) 0:40:51 load avg: 0.03 [447/447/2] test_concurrent_futures crashed (Exit code 1) Timeout (0:20:00)! Thread 0x000007e8 (most recent call first): File "D:\a\cpython\cpython\Lib\multiprocessing\connection.py", line 282 in _send_bytes File "D:\a\cpython\cpython\Lib\multiprocessing\connection.py", line 199 in send_bytes File "D:\a\cpython\cpython\Lib\multiprocessing\queues.py", line 246 in _feed (...) File "D:\a\cpython\cpython\Lib\threading.py", line 1009 in _bootstrap Thread 0x00001738 (most recent call first): File "D:\a\cpython\cpython\Lib\threading.py", line 1146 in _wait_for_tstate_lock File "D:\a\cpython\cpython\Lib\threading.py", line 1126 in join (...) File "D:\a\cpython\cpython\Lib\threading.py", line 1009 in _bootstrap Thread 0x0000103c (most recent call first): File "D:\a\cpython\cpython\Lib\threading.py", line 1146 in _wait_for_tstate_lock File "D:\a\cpython\cpython\Lib\threading.py", line 1126 in join File "D:\a\cpython\cpython\Lib\concurrent\futures\process.py", line 836 in shutdown File "D:\a\cpython\cpython\Lib\concurrent\futures\_base.py", line 647 in __exit__ File "D:\a\cpython\cpython\Lib\test\test_concurrent_futures.py", line 1386 in test_crash_big_data (...) File "D:\a\cpython\cpython\Lib\test\support\__init__.py", line 1241 in run_unittest File "D:\a\cpython\cpython\Lib\test\libregrtest\runtest.py", line 294 in _test_module (...) ``` <!-- gh-linked-prs --> ### Linked PRs * gh-108974 * gh-109244 * gh-109254 * gh-109255 <!-- /gh-linked-prs -->
a8cae4071c795e55be46e339eda37e241fa0d7f8
b298b395e8ab1725c4f0dd736155b8c818664d42
python/cpython
python__cpython-107212
# C API: No longer export internal C API functions Many internal C API functions are exported with PyAPI_FUNC() and internal variables are exported with PyAPI_DATA(), whereas these APIs should not be used outside Python internals. I propose to replace PyAPI_FUNC() and PyAPI_DATA() with extern on symbols which are not used by stdlib shared extensions. The exception should be to export, not the default. For example, the ``_PyObject_DebugMallocStats()`` function is exported by the 3rd party guppy3 project. See also issue #106320: C API: Remove private C API functions (move them to the internal C API). <!-- gh-linked-prs --> ### Linked PRs * gh-107212 * gh-107213 * gh-107214 * gh-107215 * gh-107217 * gh-107218 * gh-108012 * gh-108229 * gh-108422 * gh-108423 * gh-108424 * gh-108425 * gh-108435 * gh-109037 <!-- /gh-linked-prs -->
2e0744955f1c213a55738de848a9d928b78ef289
4bbf071635504ee1c6d44f99c98e3fad191a3b13
python/cpython
python__cpython-108835
# Itertools Recipes - iter_index() silently suppresses ValueError # Documentation In Itertools Recipes there is a bug in the [`iter_index()`](https://github.com/pochmann/cpython/blob/ecd95bb943256ecb3afeb70540387475a73e6dd7/Doc/library/itertools.rst?plain=1#L893) function. The function silently suppresses `ValueError` exception raised by a generator given to the argument `iterable`. The bug was introduced by this pull request: gh-102088 Optimize iter_index itertools recipe #102360 Commit: https://github.com/python/cpython/pull/102360/commits/148bde644195408ec68cd145b779f42a214bfbb1 Code to reproduce the bug: ``` python def assert_no_value(iterable, forbidden_value): """Pass the iterable but raise ValueError if forbidden_value is found.""" for item in iterable: if item == forbidden_value: raise ValueError(f'Value {forbidden_value!r} is not allowed.') yield item # Here we should get ValueError exception # but it is being silently suppressed by iter_index() list(iter_index(assert_no_value('AABCADEAF', 'B'), 'A')) ``` Complete notebook reproducing the bug: https://github.com/vbrozik/python-ntb/blob/main/problems_from_forums/2023-07-24_iter_index.ipynb Possible solutions which come to my mind: * revert the commit https://github.com/python/cpython/pull/102360/commits/148bde644195408ec68cd145b779f42a214bfbb1 * check the value of `ValueError` inside the `iter_index()` function * open discussion to determine whether `operator.indexOf()` should use `ValueError` Note: I already mentioned the bug in the package `more-itertools` which inherited it: Update recipes.iter_index to match CPython PR 102360 [#690](https://github.com/more-itertools/more-itertools/pull/690) <!-- gh-linked-prs --> ### Linked PRs * gh-108835 * gh-108837 <!-- /gh-linked-prs -->
f373c6b9483e12d7f6e03a631601149ed60ab883
a52213bf830226fd969dc2a2ef8006c89edecc35
python/cpython
python__cpython-107197
# Remove unused _PyArg_VaParseTupleAndKeywordsFast() It seems like the ``_PyArg_VaParseTupleAndKeywordsFast()`` function is no longer used in the Python code base. Moreover, Argument Clinic (``Tools/clinic/clinic.py``) can produce code calling the ``_PyArg_ParseTupleAndKeywordsFast()`` function, but it is not the case currently: ``_PyArg_ParseStackAndKeywords()`` is used instead. What's the status of these two functions, ``_PyArg_ParseStackAndKeywords()`` and ``_PyArg_VaParseTupleAndKeywordsFast()``? cc @erlend-aasland @serhiy-storchaka <!-- gh-linked-prs --> ### Linked PRs * gh-107197 <!-- /gh-linked-prs -->
1dbb427dd67a1de5b3662cbda0277ff2c3b18095
c6539b36c163efff3d6ed02b938a6151325f4db7
python/cpython
python__cpython-107179
# Add the C API tests for Mapping Protocol and Sequence Protocol Currently only few functions in these protocols are covered by tests: `PyMapping_Keys`, `PyMapping_Values`, `PyMapping_Items`, `PyMapping_HasKey`, `PyMapping_HasKeyString`, `PySequence_SetSlice`, `PySequence_DelSlice`. Since we just added few new functions (`PyMapping_GetOptionalItem`, etc) and are planning to deprecate other functions (`PyMapping_HasKey`, etc), we need more tests. <!-- gh-linked-prs --> ### Linked PRs * gh-107179 * gh-107728 * gh-108436 <!-- /gh-linked-prs -->
16c9415fba4972743f1944ebc44946e475e68bc4
85793278793708ad6b7132a54ac9fb4b2c5bcac1
python/cpython
python__cpython-107401
# `help()` output of `lambda` with manually set `__annotations__` is one char off # Bug report `help()` output of `lambda` with manually set `__annotations__` is slightly scrambled. ``` f = lambda a, b, c: 0 # lambdas cannot have annotations f.__annotations__['return'] = int # but you can set them manually help(f) # superfluous ")" and missed last char # <lambda> lambda a, b, c) -> in import inspect print(inspect.signature(f)) # correctly displays # (a, b, c) -> int ``` ## Note This is a minor glitch for an atypical (perhaps even unsupported) use of annotations. ## Hypothesis Perhaps `help()` uses (the same logic as) `inspect.signature()` and (to reflect `lambda` syntax) wants to drop the brackets "(...)", but then has a *one-off* error for its text slice (picking `") -> in"` instead of `" -> int"`) # Environment - CPython versions tested on: 3.6.8 - 3.11.4, 3.12.0b4 - Operating system and architecture: Windows 11 <!-- gh-linked-prs --> ### Linked PRs * gh-107401 * gh-115612 * gh-115613 <!-- /gh-linked-prs -->
b9a9e3dd62326b726ad2e8e8efd87ca6327b4019
664965a1c141e8af5eb465d29099781a6a2fc3f3
python/cpython
python__cpython-108440
# C API: Rename _PyUnstable_GetUnaryIntrinsicName() to PyUnstable_GetUnaryIntrinsicName()? Python 3.13 added ``_PyUnstable_GetUnaryIntrinsicName()`` and ``_PyUnstable_GetBinaryIntrinsicName()`` to the C API. I don't get the ``_PyUnstable`` prefix: [PEP 689 – Unstable C API tier](https://peps.python.org/pep-0689/) uses ``PyUnstable_`` prefix. Is it just a typo, or is the API private on purpose? If it's private, why does its name look like as if it's part of the Unstable C API? cc @brandtbucher @iritkatriel @encukou <!-- gh-linked-prs --> ### Linked PRs * gh-108440 * gh-108441 * gh-108651 * gh-112042 <!-- /gh-linked-prs -->
9c03215a3ee31462045b2c2ee162bdda30c54572
b89b838ebc817e5fbffad1ad8e1a85aa2d9f3113
python/cpython
python__cpython-107856
# Don't run plausible analytics out of docs.python.org # Documentation Since e8ab0096a583184fe24dfbc39eff70d270c8e6f4, an HTTP request to plausible.io is triggered even for local builds. So I just triggered the tracker with a local build just to check a PR (this is how I discovered it, by seeing uBlock Origin telling me it blocked it). I don't feel that's OK as it means that Linux packages containing the Python doc, like [python3-doc](https://packages.debian.org/trixie/python3-doc) will embed the tracker too (or every distrib will take the pain to remove it...). I think e8ab0096a583184fe24dfbc39eff70d270c8e6f4 should be reverted and maybe implemented on docsbuild-scripts, or at least be made optional (using an environment flag?) and disabled by default so we could enable it in docsbuild-script. <!-- gh-linked-prs --> ### Linked PRs * gh-107856 * gh-108334 * gh-108335 <!-- /gh-linked-prs -->
fc23f34cc9701949e6832eb32f26ea89f6622b82
e97b7bef4fbe71821d59d2f41f311e514fd29e39
python/cpython
python__cpython-107126
# Provide clear method for dbm/gdbm module There was a similar [discussion](https://github.com/python/cpython/issues/53732) about adding MutableMapping interface from dbm/gdbm module. I didn't follow up on all of the progress in adding those methods but at this moment adding a clear method looks good even consider the situation of https://github.com/python/cpython/issues/107089 I am working on adding clear() method :) <!-- gh-linked-prs --> ### Linked PRs * gh-107126 * gh-107127 * gh-107135 <!-- /gh-linked-prs -->
0ae4870d09de82ed5063b6998c172cc63628437e
b3c34e55c053846beb35f5e4253ef237b3494bd0
python/cpython
python__cpython-107092
# Use the C domain roles consistently in the documentation `:c:member:`, `:c:data:` and `:c:var:` are equivalent. I do not know whether there is a semantic difference between `:c:data:` and `:c:var:` (although I think that `:c:member:` is semantically different and should be used for attributes). `:c:member:` is used 813 times for 202 names. `:c:data:` is used 265 times for 143 names: <details> ``` :c:data:`command` :c:data:`errno` :c:data:`immutable types <Py_TPFLAGS_IMMUTABLETYPE>` :c:data:`nb_long` :c:data:`nb_reserved` :c:data:`PyBool_Type` :c:data:`Py_buffer` :c:data:`Py_buffer.format` :c:data:`Py_buffer.itemsize` :c:data:`Py_BytesWarningFlag` :c:data:`PyCallIter_Type` :c:data:`PyCFunction` :c:data:`PyCMethod` :c:data:`PyContextToken_Type` :c:data:`PyContext_Type` :c:data:`PyContextVar_Type` :c:data:`PyDateTimeAPI` :c:data:`PyDateTime_Date` :c:data:`PyDateTime_DateTime` :c:data:`PyDateTime_DateTimeType` :c:data:`PyDateTime_DateType` :c:data:`PyDateTime_Delta` :c:data:`PyDateTime_DeltaType` :c:data:`PyDateTime_Time` :c:data:`PyDateTime_TimeType` :c:data:`PyDateTime_TimeZone_UTC` :c:data:`PyDateTime_TZInfoType` :c:data:`Py_Ellipsis` :c:data:`Py_eval_input` :c:data:`PyExc_ArithmeticError` :c:data:`PyExc_AssertionError` :c:data:`PyExc_AttributeError` :c:data:`PyExc_BaseException` :c:data:`PyExc_BlockingIOError` :c:data:`PyExc_BrokenPipeError` :c:data:`PyExc_BufferError` :c:data:`PyExc_BytesWarning` :c:data:`PyExc_ChildProcessError` :c:data:`PyExc_ConnectionAbortedError` :c:data:`PyExc_ConnectionError` :c:data:`PyExc_ConnectionRefusedError` :c:data:`PyExc_ConnectionResetError` :c:data:`PyExc_DeprecationWarning` :c:data:`PyExc_EnvironmentError` :c:data:`PyExc_EOFError` :c:data:`PyExc_Exception` :c:data:`PyExc_FileExistsError` :c:data:`PyExc_FileNotFoundError` :c:data:`PyExc_FloatingPointError` :c:data:`PyExc_FutureWarning` :c:data:`PyExc_GeneratorExit` :c:data:`PyExc_ImportError` :c:data:`PyExc_ImportWarning` :c:data:`PyExc_IndentationError` :c:data:`PyExc_IndexError` :c:data:`PyExc_InterruptedError` :c:data:`PyExc_IOError` :c:data:`PyExc_IsADirectoryError` :c:data:`PyExc_KeyboardInterrupt` :c:data:`PyExc_KeyError` :c:data:`PyExc_LookupError` :c:data:`PyExc_MemoryError` :c:data:`PyExc_ModuleNotFoundError` :c:data:`PyExc_NameError` :c:data:`PyExc_NotADirectoryError` :c:data:`PyExc_NotImplementedError` :c:data:`PyExc_OSError` :c:data:`PyExc_OverflowError` :c:data:`PyExc_PendingDeprecationWarning` :c:data:`PyExc_PermissionError` :c:data:`PyExc_ProcessLookupError` :c:data:`PyExc_RecursionError` :c:data:`PyExc_ReferenceError` :c:data:`PyExc_ResourceWarning` :c:data:`PyExc_RuntimeError` :c:data:`PyExc_RuntimeWarning` :c:data:`PyExc_StopAsyncIteration` :c:data:`PyExc_StopIteration` :c:data:`PyExc_SyntaxError` :c:data:`PyExc_SyntaxWarning` :c:data:`PyExc_SystemError` :c:data:`PyExc_SystemExit` :c:data:`PyExc_TabError` :c:data:`PyExc_TimeoutError` :c:data:`PyExc_TypeError` :c:data:`PyExc_UnboundLocalError` :c:data:`PyExc_UnicodeDecodeError` :c:data:`PyExc_UnicodeEncodeError` :c:data:`PyExc_UnicodeError` :c:data:`PyExc_UnicodeTranslateError` :c:data:`PyExc_UnicodeWarning` :c:data:`PyExc_UserWarning` :c:data:`PyExc_ValueError` :c:data:`PyExc_Warning` :c:data:`PyExc_WindowsError` :c:data:`PyExc_ZeroDivisionError` :c:data:`Py_False` :c:data:`Py_file_input` :c:data:`Py_FileSystemDefaultEncodeErrors` :c:data:`PyFunction_Type` :c:data:`Py_IgnoreEnvironmentFlag` :c:data:`PyImport_FrozenModules` :c:data:`PyImport_Inittab` :c:data:`PyInstanceMethod_Type` :c:data:`PyMethod_Type` :c:data:`Py_mod_exec` :c:data:`PyModuleDef_HEAD_INIT` :c:data:`PyModule_Type` :c:data:`Py_None` :c:data:`Py_NotImplemented` :c:data:`PyOS_ReadlineFunctionPointer` :c:data:`Py_Py3kWarningFlag` :c:data:`PySeqIter_Type` :c:data:`Py_single_input` :c:data:`PyStructSequence_UnnamedField` :c:data:`Py_tp_base` :c:data:`Py_tp_bases` :c:data:`PyTrace_CALL` :c:data:`PyTrace_C_CALL` :c:data:`PyTrace_C_EXCEPTION` :c:data:`PyTrace_C_RETURN` :c:data:`PyTrace_EXCEPTION` :c:data:`PyTrace_LINE` :c:data:`PyTrace_OPCODE` :c:data:`PyTrace_RETURN` :c:data:`Py_True` :c:data:`PyType_GetModuleByDef` :c:data:`PyType_Type` :c:data:`PyUnicode_1BYTE_KIND` :c:data:`PyUnicode_2BYTE_KIND` :c:data:`PyUnicode_4BYTE_KIND` :c:data:`PyUnicode_WCHAR_KIND` :c:data:`Py_UTF8Mode` :c:data:`Py_Version` :c:data:`rl_attempted_completion_function` :c:data:`rl_completer_word_break_characters` :c:data:`rl_completion_display_matches_hook` :c:data:`rl_completion_type` :c:data:`rl_line_buffer` :c:data:`rl_pre_input_hook` :c:data:`rl_startup_hook` :c:data:`SpamError` :c:data:`sts` ``` </details> In some of these cases (e.g. for `nb_long` or `Py_buffer.format`) `:c:member:` looks more semantically appropriate. `:c:var:` is used 51 times for 28 names: <details> ``` :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:`PyOS_InputHook` :c:var:`PyOS_ReadlineFunctionPointer` :c:var:`Py_QuietFlag` :c:var:`PyStructSequence_UnnamedField` :c:var:`PyType_Type` :c:var:`Py_UnbufferedStdioFlag` :c:var:`Py_UTF8Mode` :c:var:`Py_VerboseFlag` :c:var:`Py_Version` ``` </details> In some cases `:data:` (purposed for use with Python names) is used with a C name. It is definitely error. In what cases should we use `:c:data:` and in what cases should we use `:c:var:`? I do not see a system in the current use. <!-- gh-linked-prs --> ### Linked PRs * gh-107092 * gh-107113 * gh-107121 * gh-107129 * gh-107138 * gh-107063 * gh-107310 * gh-107311 * gh-107312 * gh-107313 * gh-107318 * gh-107330 * gh-107331 * gh-107378 * gh-107379 * gh-107384 * gh-107385 * gh-107416 * gh-107417 <!-- /gh-linked-prs -->
08a228da05a7aec937b65eea21f4091fa3c6b5cf
c65592c4d6d7552fb6284442906a96a6874cb266
python/cpython
python__cpython-107090
# shelve: `Shelf.clear()` has very poor performance # Bug report Calling the `clear` method on a `shelve.Shelf` object takes a very long time on databases that have thousands of entries. It can be seen in this script, which creates a database with 10,000 entries and immediately clears it. ```python import os import shelve import tempfile with tempfile.TemporaryDirectory() as tempdir: filename = os.path.join(tempdir, "test-shelf") with shelve.open(filename) as db: items = {str(x):x for x in range(10000)} db.update(items) db.clear() print("ok") ``` On my M2 Mac Mini, this script takes about 2.1 seconds. ``` james@iris ~ % time python shelve-clear-test.py ok python shelve-clear-test.py 1.18s user 0.92s system 99% cpu 2.100 total ``` On a Debian VPS: ``` james@asteroid:~$ time python3 shelve-clear-test.py ok real 0m43.665s user 0m34.330s sys 0m9.107s ``` # Your environment <!-- Include as many relevant details as possible about the environment you experienced the bug in --> - CPython versions tested on - 3.11.2 - 3.11.4 - cpython/main branch - Operating system and architecture - macOS/arm64 13.4.1 - Debian/x86_64 12.1 <!-- gh-linked-prs --> ### Linked PRs * gh-107090 <!-- /gh-linked-prs -->
810d5d87d9fe8d86aad99e48cef4f78a72e16ccf
11c055f5ff1a353de6d2e77f2af24aaa782878ba
python/cpython
python__cpython-107085
# test_capi.test_basic_loop(): _PyInstruction_GetLength() assertion error on s390x Fedora Clang 3.x buildbot s390x Fedora Clang 3.x: https://buildbot.python.org/all/#/builders/3/builds/4312 * Last successful build, build 4216 (July 7): https://buildbot.python.org/all/#/builders/3/builds/4216 -- commit 67a798888dcde13bbb1e17cfcc3c742c94e67a07 * First failed build, build 4217 (July 7): https://buildbot.python.org/all/#/builders/3/builds/4217 -- commit e1d45b8ed43e1590862319fec33539f8adbc0849 Differences between the two builds: ``` commit e1d45b8ed43e1590862319fec33539f8adbc0849 Author: Guido van Rossum <guido@python.org> Date: Thu Jul 6 16:46:06 2023 -0700 gh-104584: Handle EXTENDED_ARG in superblock creation (#106489) With test. commit c60df361ce2d734148d503f4a711e67c110fe223 Author: Gregory P. Smith <greg@krypto.org> Date: Thu Jul 6 15:46:50 2023 -0700 gh-90876: Restore the ability to import multiprocessing when `sys.executable` is `None` (#106464) Prevent `multiprocessing.spawn` from failing to *import* in environments where `sys.executable` is `None`. This regressed in 3.11 with the addition of support for path-like objects in multiprocessing. Adds a test decorator to have tests only run when part of test_multiprocessing_spawn to `_test_multiprocessing.py` so we can start to avoid re-running the same not-global-state specific test in all 3 modes when there is no need. commit 76fac7bce55302a8e9a524d72f5384fd89e6dfde Author: Guido van Rossum <guido@python.org> Date: Thu Jul 6 15:45:56 2023 -0700 gh-104584: Clean up and fix uops tests and fix crash (#106492) The uops test wasn't testing anything by default, and was failing when run with -Xuops. Made the two executor-related context managers global, so TestUops can use them (notably `with temporary_optimizer(opt)`). Made clear_executor() a little more thorough. Fixed a crash upon finalizing a uop optimizer, by adding a `tp_dealloc` handler. ``` Error: ``` 0:05:26 load avg: 7.08 [435/447/1] test_capi crashed (Exit code -6) -- running: (...) python: Python/instrumentation.c:262: int _PyInstruction_GetLength(PyCodeObject *, int): Assertion `opcode != 0' failed. Fatal Python error: Aborted Current thread 0x000003ff990770a0 (most recent call first): File "/home/dje/cpython-buildarea/3.x.edelsohn-fedora-z.clang/build/Lib/test/test_capi/test_misc.py", line 2441 in get_first_executor File "/home/dje/cpython-buildarea/3.x.edelsohn-fedora-z.clang/build/Lib/test/test_capi/test_misc.py", line 2459 in test_basic_loop (...) 0:07:22 load avg: 3.60 Re-running test_capi in verbose mode (...) test_gilstate_ensure_no_deadlock (test.test_capi.test_misc.TestThreadState.test_gilstate_ensure_no_deadlock) ... ok test_gilstate_matches_current (test.test_capi.test_misc.TestThreadState.test_gilstate_matches_current) ... ok test_thread_state (test.test_capi.test_misc.TestThreadState.test_thread_state) ... ok python: Python/instrumentation.c:262: int _PyInstruction_GetLength(PyCodeObject *, int): Assertion `opcode != 0' failed. Fatal Python error: Aborted Current thread 0x000003ff854770a0 (most recent call first): File "/home/dje/cpython-buildarea/3.x.edelsohn-fedora-z.clang/build/Lib/test/test_capi/test_misc.py", line 2441 in get_first_executor File "/home/dje/cpython-buildarea/3.x.edelsohn-fedora-z.clang/build/Lib/test/test_capi/test_misc.py", line 2459 in test_basic_loop File "/home/dje/cpython-buildarea/3.x.edelsohn-fedora-z.clang/build/Lib/unittest/case.py", line 589 in _callTestMethod File "/home/dje/cpython-buildarea/3.x.edelsohn-fedora-z.clang/build/Lib/unittest/case.py", line 634 in run File "/home/dje/cpython-buildarea/3.x.edelsohn-fedora-z.clang/build/Lib/unittest/case.py", line 690 in __call__ File "/home/dje/cpython-buildarea/3.x.edelsohn-fedora-z.clang/build/Lib/unittest/suite.py", line 122 in run (...) ``` cc @gvanrossum <!-- gh-linked-prs --> ### Linked PRs * gh-107085 * gh-107216 * gh-107256 <!-- /gh-linked-prs -->
7fc9be350af055538e70ece8d7de78414bad431e
9a6b278769b9f24e0650283f6c347db8ae52b7b3
python/cpython
python__cpython-107567
# test__xxsubinterpreters: test_already_running() crash randomly on Python built with TraceRefs: invalid object chain AMD64 Arch Linux TraceRefs 3.x: https://buildbot.python.org/all/#/builders/484/builds/3721 Assertion error: **Objects/object.c:2235: _Py_ForgetReference: Assertion failed: invalid object chain**. ``` $ ./python -m test -j2 test__xxsubinterpreters test__xxsubinterpreters -m test_already_running -v (...) == Python build: debug TraceRefs (...) == CPU count: 12 (...) 0:00:00 load avg: 1.19 Run tests in parallel using 2 child processes 0:00:00 load avg: 1.19 [1/2] test__xxsubinterpreters passed test_already_running (test.test__xxsubinterpreters.RunStringTests.test_already_running) ... ok (...) 0:00:00 load avg: 1.19 [2/2/1] test__xxsubinterpreters crashed (Exit code -6) test_already_running (test.test__xxsubinterpreters.RunStringTests.test_already_running) ... Objects/object.c:2235: _Py_ForgetReference: Assertion failed: invalid object chain Enable tracemalloc to get the memory block allocation traceback object address : 0x7f01d0be95a0 object refcount : 0 object type : 0xa1dc00 object type name: str object repr : <refcnt 0 at 0x7f01d0be95a0> Fatal Python error: _PyObject_AssertFailed: _PyObject_AssertFailed Python runtime state: initialized Current thread 0x00007f01df4a1740 (most recent call first): <no Python frame> (...) ``` Python built with: ``` git clean -fdx ./configure --with-pydebug --with-trace-refs CFLAGS="-O0" make -j14 ``` <!-- gh-linked-prs --> ### Linked PRs * gh-107567 * gh-107599 * gh-107648 * gh-107737 * gh-107751 <!-- /gh-linked-prs -->
707018cc75558d6695e9e199a3ed0c8a4ff7cbcc
5dc825d504ad08d64c9d1ce578f9deebbe012604
python/cpython
python__cpython-107586
# test_asyncio: test_create_connection_ssl_failed_certificate() failed on ARM64 macOS 3.x buildbot ARM64 macOS 3.x: https://buildbot.python.org/all/#/builders/725/builds/5088 The test started to fail when **OpenSSL** was upgrade from 3.0.0 to **3.1.1** at July 13. cc @pablogsal @ned-deily @ambv * Last successful build, build 4995 (July 13 at 5:01PM): https://buildbot.python.org/all/#/builders/725/builds/4995 * test.pythoninfo: ``ssl.OPENSSL_VERSION: OpenSSL 3.0.0 7 sep 2021`` * Fist failure, build 4999 (July 13 at 5:23PM): https://buildbot.python.org/all/#/builders/725/builds/4999 * test.pythoninfo: ``ssl.OPENSSL_VERSION: OpenSSL 3.1.1 30 May 2023`` * Between build 4995 and 4999, build failed with an exception Error: ``` ERROR: test_create_connection_ssl_failed_certificate (test.test_asyncio.test_ssl.TestSSL.test_create_connection_ssl_failed_certificate) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/buildbot/buildarea/3.x.pablogsal-macos-m1.macos-with-brew/build/Lib/test/test_asyncio/test_ssl.py", line 454, in test_create_connection_ssl_failed_certificate self.loop.run_until_complete(client(srv.addr)) File "/Users/buildbot/buildarea/3.x.pablogsal-macos-m1.macos-with-brew/build/Lib/asyncio/base_events.py", line 664, in run_until_complete return future.result() ^^^^^^^^^^^^^^^ File "/Users/buildbot/buildarea/3.x.pablogsal-macos-m1.macos-with-brew/build/Lib/test/test_asyncio/test_ssl.py", line 441, in client reader, writer = await asyncio.open_connection( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/buildbot/buildarea/3.x.pablogsal-macos-m1.macos-with-brew/build/Lib/asyncio/streams.py", line 47, in open_connection transport, _ = await loop.create_connection( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/buildbot/buildarea/3.x.pablogsal-macos-m1.macos-with-brew/build/Lib/asyncio/base_events.py", line 1126, in create_connection transport, protocol = await self._create_connection_transport( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/buildbot/buildarea/3.x.pablogsal-macos-m1.macos-with-brew/build/Lib/asyncio/base_events.py", line 1159, in _create_connection_transport await waiter File "/Users/buildbot/buildarea/3.x.pablogsal-macos-m1.macos-with-brew/build/Lib/asyncio/sslproto.py", line 575, in _on_handshake_complete raise handshake_exc File "/Users/buildbot/buildarea/3.x.pablogsal-macos-m1.macos-with-brew/build/Lib/asyncio/sslproto.py", line 557, in _do_handshake self._sslobj.do_handshake() File "/Users/buildbot/buildarea/3.x.pablogsal-macos-m1.macos-with-brew/build/Lib/ssl.py", line 917, in do_handshake self._sslobj.do_handshake() ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:1024) ``` test.pythoninfo: ``` os.uname: posix.uname_result(sysname='Darwin', nodename='Mac-mini', release='22.5.0', version='Darwin Kernel Version 22.5.0: Thu Jun 8 22:22:19 PDT 2023; root:xnu-8796.121.3~7/RELEASE_ARM64_T8103', machine='arm64') platform.architecture: 64bit platform.platform: macOS-13.4.1-arm64-arm-64bit platform.python_implementation: CPython ssl.HAS_SNI: True ssl.OPENSSL_VERSION: OpenSSL 3.1.1 30 May 2023 ssl.OPENSSL_VERSION_INFO: (3, 1, 0, 1, 0) ssl.OP_ALL: 0x80000050 ssl.OP_NO_TLSv1_1: 0x10000000 ssl.SSLContext.maximum_version: -1 ssl.SSLContext.minimum_version: 771 ssl.SSLContext.options: 2186412112 ssl.SSLContext.protocol: 16 ssl.SSLContext.verify_mode: 2 ssl.default_https_context.maximum_version: -1 ssl.default_https_context.minimum_version: 771 ssl.default_https_context.options: 2186412112 ssl.default_https_context.protocol: 16 ssl.default_https_context.verify_mode: 2 ssl.stdlib_context.maximum_version: -1 ssl.stdlib_context.minimum_version: 771 ssl.stdlib_context.options: 2186412112 ssl.stdlib_context.protocol: 16 ssl.stdlib_context.verify_mode: 0 ``` <!-- gh-linked-prs --> ### Linked PRs * gh-107586 * gh-107587 * gh-107588 * gh-107589 * gh-107590 * gh-107591 * gh-107602 <!-- /gh-linked-prs -->
77e09192b5f1caf14cd5f92ccb53a4592e83e8bc
a73daf54ebd7bd6bf32e82766a605ebead2f128c
python/cpython
python__cpython-108763
# C API: _PyObject_VisitManagedDict() function should be public **tl; dr: _PyObject_VisitManagedDict() and _PyObject_ClearManagedDict() function should be public.** If a C extension implements a type as a heap type, the type must support the GC protocol: it must implement visit and clear functions, and the dealloc function must DECREF the type. It seems like if a heap type uses the new Py_TPFLAGS_MANAGED_DICT flag, the visit function must call _PyObject_VisitManagedDict() and the clear function must call _PyObject_ClearManagedDict(). Correct me if I'm wrong. Problem: _PyObject_VisitManagedDict() and _PyObject_ClearManagedDict() functions are private. IMO they must be public. Either Py_TPFLAGS_MANAGED_DICT flag must be private, or it should be public and all related helper functions should be public as well. Py_TPFLAGS_MANAGED_DICT was added to Python 3.11. _PyObject_VisitManagedDict() and _PyObject_ClearManagedDict() functions were added to Python 3.12. In Python 3.12, typing.TypeVar, typing.ParamSpec, typing.TypeVarTuple are implemented with Py_TPFLAGS_MANAGED_DICT (and use the 2 helper functions). In Python 3.13, _asyncio.Future and _asyncio.Task are also implemented with Py_TPFLAGS_MANAGED_DICT (and use the 2 helper functions). Note: In Objects/typeobject.c, subtype_traverse() calls _PyObject_VisitManagedDict() in some cases, and subtype_clear() calls _PyObject_ClearManagedDict() in some cases. <!-- gh-linked-prs --> ### Linked PRs * gh-108763 * gh-110291 <!-- /gh-linked-prs -->
fc2cb86d210555d509debaeefd370d5331cd9d93
6387b5313c60c1403785b2245db33372476ac304
python/cpython
python__cpython-107029
# Ambiguity in documentation of `logger.handlers.MemoryHandler` method `flush()` # Documentation Behavior of the [MemoryHandler](https://docs.python.org/release/3.11.4/library/logging.handlers.html#memoryhandler) is slightly different as what the documentation is. Or, it has at least some ambiguity: The function `flush()` does not clear the buffer when flushed without a target, but the docstring states: `The record buffer is also cleared by this operation.` Since keeping the buffer full when flushing when no target is given (quite a corner case, but anyway) makes sense. Therefore suggested to adapt the documentation. <!-- gh-linked-prs --> ### Linked PRs * gh-107029 * gh-107065 * gh-107066 <!-- /gh-linked-prs -->
5e5a34ac3a827e040cd89426b1774fec2123336a
22422e9d1a50b4970bc6957a88569618d579c47f
python/cpython
python__cpython-107018
# Remove async_hacks from the tokenizer The `async_hacks` related functionality provides a specific compile mode that still allows treating ASYNC and AWAIT like soft keywords optionally. This is not used in the interpreter and it belongs to a version that has lost upstream support (and that would imply that someone is analyzing 3.6 code from 3.13 code) and it complicates the tokenizer logic, so we can remove it to clean things a bit. <!-- gh-linked-prs --> ### Linked PRs * gh-107018 <!-- /gh-linked-prs -->
da8f87b7ea421894c41dfc37f578e03409c5d280
b0202a4e5d6b629ba5acbc703e950f08ebaf07df
python/cpython
python__cpython-107011
# Document the curses module variables LINES and COLS In the `curses.update_lines_cols()` description `LINES` and `COLS` are referred as the environment variables. But actually they are the `curses` module variables. <!-- gh-linked-prs --> ### Linked PRs * gh-107011 * gh-107057 * gh-107058 <!-- /gh-linked-prs -->
26e08dfdd7ac1b3d567d30cd35e4898121580390
6fbc717214210e06313a283b2f3ec8ce67209609
python/cpython
python__cpython-131840
# Move threading.local docs from docstring to the docs # Documentation https://docs.python.org/3/library/threading.html#threading.local says: > For more details and extensive examples, see the documentation string of the _threading_local module: [Lib/_threading_local.py](https://github.com/python/cpython/tree/3.11/Lib/_threading_local.py). If we have good helpful words about a component in the standard library, we should publish them in the docs. The docstring should be moved to the .rst file, or at least parts harvested. <!-- gh-linked-prs --> ### Linked PRs * gh-131840 * gh-133432 <!-- /gh-linked-prs -->
b97328ef5d2435c08de3e4e2054c226f15b52d0f
8467026ed66ca3abefe3a13860d2633eae3d7164
python/cpython
python__cpython-106993
# tok_report_warnings in tokenizer state is not needed When we merged PEP 701, we added `tok_report_warnings`, which apparently got in by accident. The issue it was trying to solve was already resolved in #99891 and #99893. I think that it can safely removed both from the tokenizer struct and all occurences should be changed to use `report_warnings` instead. <!-- gh-linked-prs --> ### Linked PRs * gh-106993 * gh-107013 <!-- /gh-linked-prs -->
76e20c361c8d6bc20d939d436a1c3d4077a58186
adda43dc0bcea853cbfa33126e5549c584cef8be
python/cpython
python__cpython-106990
# Bump sphinx-lint to 0.6.8 # Documentation Bump sphinx-lint to 0.6.8 in `.pre-commit-config.yaml` and fix any newly reported issues. https://github.com/sphinx-contrib/sphinx-lint/releases/tag/v0.6.8 <!-- gh-linked-prs --> ### Linked PRs * gh-106990 * gh-106991 * gh-107023 <!-- /gh-linked-prs -->
6acd85d91063380d1afb86c116a66e0aadd4f909
ee5c01b473eeadb007b9f330db3143e34e46038b
python/cpython
python__cpython-106982
# Docs: alphabetise bullets by module name # Documentation Re: https://github.com/python/cpython/pull/106540#discussion_r1259964874 Look at: * https://docs.python.org/3.13/whatsnew/3.13.html#pending-removal-in-python-3-14 * https://docs.python.org/3.13/whatsnew/3.13.html#pending-removal-in-python-3-15 * https://docs.python.org/3.13/whatsnew/3.13.html#pending-removal-in-python-3-16 * https://docs.python.org/3.13/whatsnew/3.13.html#pending-removal-in-future-versions Each bullet point begins with the relevant module name, and the bullets are alphabetised. Let's do the same for: * [x] https://docs.python.org/3.13/whatsnew/3.13.html#deprecated * [x] https://docs.python.org/3.13/whatsnew/3.12.html#deprecated * [x] https://docs.python.org/3.13/whatsnew/3.12.html#pending-removal-in-python-3-14 * [x] https://docs.python.org/3.13/whatsnew/3.12.html#removed <!-- gh-linked-prs --> ### Linked PRs * gh-106982 * gh-107005 * gh-107106 <!-- /gh-linked-prs -->
443d9b3033bc6189e7f1ae936806779c02a46c43
d55b4da10c56f3299998b5b8fee3a8a744fac76c
python/cpython
python__cpython-106984
# What's new in 3.12: fix typo: non-integral -> non-integer # Documentation https://docs.python.org/3.12/whatsnew/3.12.html#changes-in-the-python-api says: > * Removed randrange() functionality deprecated since Python 3.10. Formerly, randrange(10.0) losslessly converted to randrange(10). Now, it raises a [TypeError](https://docs.python.org/3.12/library/exceptions.html#TypeError). Also, the exception raised for non-integral values such as randrange(10.5) or randrange('10') has been changed from [ValueError](https://docs.python.org/3.12/library/exceptions.html#ValueError) to [TypeError](https://docs.python.org/3.12/library/exceptions.html#TypeError). This also prevents bugs where randrange(1e25) would silently select from a larger range than randrange(10**25). (Originally suggested by Serhiy Storchaka [gh-86388](https://github.com/python/cpython/issues/86388).) "non-integral" should be "non-integer" <!-- gh-linked-prs --> ### Linked PRs * gh-106984 * gh-106986 <!-- /gh-linked-prs -->
d55b4da10c56f3299998b5b8fee3a8a744fac76c
806d7c98a5da5c1fd2e52a5b666f36ca4f545092
python/cpython
python__cpython-106992
# What's new in 3.12: add missing issue reference # Documentation https://docs.python.org/3.12/whatsnew/3.12.html#pending-removal-in-python-3-14 has: > * Creating immutable types ([Py_TPFLAGS_IMMUTABLETYPE](https://docs.python.org/3.12/c-api/typeobj.html#Py_TPFLAGS_IMMUTABLETYPE)) with mutable bases using the C API. This was added in https://github.com/python/cpython/issues/95388, let's add it as a reference: ```(:gh:`95388`)``` <!-- gh-linked-prs --> ### Linked PRs * gh-106992 * gh-108283 <!-- /gh-linked-prs -->
c556f9a3c9af48c9af9e1f298be638553a6c886e
1a1bfc28912a39b500c578e9f10a8a222638d411
python/cpython
python__cpython-106972
# Argument Clinic 'destination <name> clear' is broken The `destination <name> clear` command is documented like this: > It removes all the accumulated text up to this point in the destination. (I don’t know what you’d need this for, but I thought maybe it’d be useful while someone’s experimenting.) Clearly, the last sentence is correct, because this command contains two bugs, and nobody has ever complained: 1. It accesses [the wrong attribute](https://github.com/python/cpython/blob/0ba07b2108d4763273f3fb85544dde34c5acd40a/Tools/clinic/clinic.py#L1984-L1986) when clearing the accumulators 2. The directive parser [does not return immediately](https://github.com/python/cpython/blob/0ba07b2108d4763273f3fb85544dde34c5acd40a/Tools/clinic/clinic.py#L4494C3-L4496) after executing the `clear` command, so it jumps straight into "fail because we got an unknown command" The fixes are easy, so I suggest we apply the fixes and add regressions tests. An alternative could be to remove the `clear` command, but I don't think we should tear out features lightly, no matter how obscure they are. Found while working on #106935. <!-- gh-linked-prs --> ### Linked PRs * gh-106972 * gh-106983 * gh-107059 <!-- /gh-linked-prs -->
3372bcba9893030e4063a9264ec0b4d1b6166883
cdeb1a6caad5e3067f01d6058238803b8517f9de
python/cpython
python__cpython-106988
# New modules in 3.12: "None yet" # Documentation ["What's New in Python 3.12"](https://docs.python.org/3.12/whatsnew/3.12.html#new-modules) says: > **New Modules** > > * None yet. 3.12 is in feature freeze (https://devguide.python.org/versions/) and will get no new more new features or modules, so this should either read "None" or have the section removed. (What's been done before?) The same applies to the same section for "What's New in 3.10", let's update that too. <!-- gh-linked-prs --> ### Linked PRs * gh-106988 * gh-107093 * gh-107094 <!-- /gh-linked-prs -->
6dbffaed17d59079d6a2788d686009f762a3278f
c5adf26b1867767781af30ada6f05a29449fc650
python/cpython
python__cpython-107000
# Date is confusing on What's New page # Documentation On this page, the Date is confusing. What does it represent? Doesn't seem to be the date the version was released. Is it the last date the documentation was updated? https://github.com/python/cpython/blob/3.11/Doc/whatsnew/3.11.rst?plain=1#L6 <!-- gh-linked-prs --> ### Linked PRs * gh-107000 * gh-109648 <!-- /gh-linked-prs -->
c92ef6fe0e1384c090b94143cdc01e5e114a8747
3782def5a2b4d24ab5d356f89da181e99a9a59b2
python/cpython
python__cpython-106961
# Python cannot be compiled with the MPI wrapper around the GCC compiler The configure script and configure.ac check for compiler: ```sh case "$CC" in *icc*) # ICC needs -fp-model strict or floats behave badly CFLAGS_NODIST="$CFLAGS_NODIST -fp-model strict" ;; *xlc*) CFLAGS_NODIST="$CFLAGS_NODIST -qalias=noansi -qmaxmem=-1" ;; esac ``` The MPI GCC compiler: mpicc is qualified as the intel compiler, because of the 'icc' in the name, and applies the fp-model strict option to the arguments, which is invalid syntax for GCC, causing multiple compile time errors with recent GCC versions: gcc: error: unrecognized command-line option ‘-fp-model’; did you mean ‘-fipa-modref’? By first filtering out the mpicc compiler case, this mistake is prevented: ```sh case "$CC" in *mpicc*) CFLAGS_NODIST="$CFLAGS_NODIST" ;; *icc*) # ICC needs -fp-model strict or floats behave badly CFLAGS_NODIST="$CFLAGS_NODIST -fp-model strict" ;; *xlc*) CFLAGS_NODIST="$CFLAGS_NODIST -qalias=noansi -qmaxmem=-1" ;; esac ``` (Now that I have this created, I can no doubt use its issue number to get the pull request with this fix through the pipeline) <!-- gh-linked-prs --> ### Linked PRs * gh-106961 * gh-107081 <!-- /gh-linked-prs -->
9a6b278769b9f24e0650283f6c347db8ae52b7b3
3aeffc0d8f28655186f99d013ee9653c65b92f84
python/cpython
python__cpython-106949
# Docs: add standard external names to nitpick_ignore Sphinx in the nitpick mode complains about standard C identifiers like "size_t", "LONG_MAX" and "errno". This can be solved individually by adding `!` before the name, e.g. ``` :c:data:`errno` ``` or using literal text instead of semantic role, e.g. ``` ``errno`` ```. Although it does not solve complains about using types like `size_t` in function signature. Other way -- add them to the `nitpick_ignore` list in `conf.py`. <!-- gh-linked-prs --> ### Linked PRs * gh-106949 * gh-107060 * gh-107061 * gh-107154 * gh-107157 * gh-107278 * gh-107295 * gh-107297 * gh-107299 * gh-107301 <!-- /gh-linked-prs -->
f8b7fe2f2647813ae8249675a80e59c117d30fe1
26e08dfdd7ac1b3d567d30cd35e4898121580390
python/cpython
python__cpython-107272
# Global String Objects are Interned Only in the First Interpreter When a string object is interned via `_PyUnicode_InternInPlace()`, its "state.interned" field is set. Afterward, subsequent calls to `_PyUnicode_InternInPlace()` will skip that string. The problem is that some strings may be used in multiple interpreters, which each have their own interned dict. The string is shared between the interpreters, along with its "state.interned" field. That means the string will only be interned in the first interpreter where `_PyUnicode_InternInPlace()` is called (ignoring races in the function, e.g. gh-106930). We need to fix it so one of the following is true: * there should be one global interned "dict" shared by all interpreters (we tried this already and it is very tricky) * strings are always interned in every interpreter, regardless of the "state.interned" value <!-- gh-linked-prs --> ### Linked PRs * gh-107272 * gh-107358 * gh-107362 * gh-110713 <!-- /gh-linked-prs -->
b72947a8d26915156323ccfd04d273199ecb870c
4f67921ad28194155e3d4c16255fb140a6a4d89a
python/cpython
python__cpython-108959
# Support multi-line error locations in traceback and other related improvements (PEP-657, 3.11) # Feature or enhancement We propose a few improvements and fixes to PEP-657, namely: 1. Support underlining errors that span across multiple lines instead of only showing the first line 2. Use caret anchors for function calls as well 3. Fix bracket/binary op heuristic in the caret anchor computation function # Pitch We already implemented these items in PyTorch here: https://github.com/pytorch/pytorch/pull/104676. We're seeing if these may be worth adding to CPython. ## Rationale for 1 Multi-line expressions can negate the utility of PEP-657, for example: ```python really_long_expr_1 = 1 really_long_expr_2 = 2 really_long_expr_3 = 0 really_long_expr_4 = 4 y = ( ( really_long_expr_1 + really_long_expr_2 ) / really_long_expr_2 / really_long_expr_3 ) ``` Current traceback: ``` Traceback (most recent call last): File "/scratch/williamwen/work/pytorch/playground5.py", line 25, in <module> ( ZeroDivisionError: float division by zero ``` Better traceback: ``` Traceback (most recent call last): File "/scratch/williamwen/work/pytorch/playground5.py", line 25, in <module> ( ~ really_long_expr_1 + ~~~~~~~~~~~~~~~~~~~~ really_long_expr_2 ~~~~~~~~~~~~~~~~~~ ) / ~~^ really_long_expr_2 / ~~~~~~~~~~~~~~~~~~ ZeroDivisionError: float division by zero ``` ## Rationale for 2 Helpful for identifying function calls that cause errors in chained function calls. We may as well do it since we're already doing it for subscripts. For example: ```python def f1(x1): def f2(x2): raise RuntimeError() return f2 y = f1(1)(2)(3) ``` Current traceback: ``` Traceback (most recent call last): File "/scratch/williamwen/work/pytorch/playground5.py", line 22, in <module> y = f1(1)(2)(3) ^^^^^^^^ File "/scratch/williamwen/work/pytorch/playground5.py", line 6, in f2 raise RuntimeError() RuntimeError ``` Better traceback: ``` Traceback (most recent call last): File "/scratch/williamwen/work/pytorch/playground5.py", line 22, in <module> y = f1(1)(2)(3) ~~~~~^^^ File "/scratch/williamwen/work/pytorch/playground5.py", line 6, in f2 raise RuntimeError() RuntimeError ``` ## Rationale for 3 The binary op anchors are computed by taking the next non-space character after the left subexpression. This is incorrect in some simple cases: ``` x = (3) / 0 ~~^~~~~ ZeroDivisionError: division by zero ``` We should expect ``` x = (3) / 0 ~~~~^~~ ZeroDivisionError: division by zero ``` The fix is that we should continue advancing the anchor until we find a non-space character that is also not in `)\#` (for `\#`, we should move the anchor to the next line). Subscript has a similar issue as well. We should continue advancing the left anchor until we find `[`, and the right anchor should be the end of the entire subscript expression. cc @pablogsal @isidentical @ammaraskar @iritkatriel @ezyang <!-- gh-linked-prs --> ### Linked PRs * gh-108959 * gh-109147 * gh-109148 * gh-109589 * gh-112097 <!-- /gh-linked-prs -->
6275c67ea68645e5b296a80ea63b90707a0be792
aa51182320f3c391195eb7d5bd970867e63bd978
python/cpython
python__cpython-106920
# Use proper markup for the C "constants" Many of the C "constants" (actually macros without parameters) are declared in the documentation using the `data` directive and referred using `:data:` and `:const:` roles. It is incorrect, because these directive and roles are defined in the Python domain and purposed to use with Python module level variables. I think that it is better to document them as they are, the C macros. One of the differences is that the HTML anchors contains the `c.` prefix, e.g. `c.METH_VARARGS`. There may also be the difference in visual representation. Other issues in the current markup: * In the index they are marked as "(built-in variable)". * There are no index entries for `METH_KEYWORDS` and `METH_METHOD` and they cannot be referred. * There are two definitions of `Py_TPFLAGS_HAVE_GC`. They does not conflict only because they are in different namespaces. <!-- gh-linked-prs --> ### Linked PRs * gh-106920 * gh-106951 * gh-106952 <!-- /gh-linked-prs -->
fcc816dbff7ca66c26f57a506e4d2330fe41d0ff
81861fd90b4ae981e7881cd03a3c370713063525
python/cpython
python__cpython-106977
# 3.12.0b4 Backwards incompatible change with reassignment of `cls.__new__` and `super()` <!-- If you're new to Python and you're not sure whether what you're experiencing is a bug, the CPython issue tracker is not the right place to seek help. Consider the following options instead: - reading the Python tutorial: https://docs.python.org/3/tutorial/ - posting in the "Users" category on discuss.python.org: https://discuss.python.org/c/users/7 - emailing the Python-list mailing list: https://mail.python.org/mailman/listinfo/python-list - searching our issue tracker (https://github.com/python/cpython/issues) to see if your problem has already been reported --> # Bug report Noticed this while testing `3.12.0b4`. While in my particular case I can work around it, it never the less is a change in behavior to `3.11`. ```py class FixedIntType(int): _signed: bool def __new__(cls, *args, **kwargs): print(f"{cls}, {args=}") return super().__new__(cls, *args, **kwargs) def __init_subclass__(cls, signed: int | None = None) -> None: super().__init_subclass__() if signed is not None: cls._signed = signed if "__new__" not in cls.__dict__: cls.__new__ = cls.__new__ # <-- This line triggers the error class uint_t(FixedIntType, signed=False): pass class CustomInt(uint_t): def __new__(cls, value: int = 0): return super().__new__(cls, value) def with_id(self, value: int): return type(self)(value) CustomInt().with_id(1024) ``` ``` <class '__main__.CustomInt'>, args=(0,) <class '__main__.CustomInt'>, args=(<class '__main__.CustomInt'>, 1024) Traceback (most recent call last): File "/.../cpython/test.py", line 26, in <module> CustomInt().with_id(1024) File "/.../cpython/test.py", line 24, in with_id return type(self)(value) ^^^^^^^^^^^^^^^^^ File "/.../cpython/test.py", line 21, in __new__ return super().__new__(cls, value) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/.../cpython/test.py", line 6, in __new__ return super().__new__(cls, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ValueError: int() base must be >= 2 and <= 36, or 0 ``` Without `cls.__new__ = cls.__new__` ``` <class '__main__.CustomInt'>, args=(0,) <class '__main__.CustomInt'>, args=(1024,) ``` I bisected the issue to #103497. /CC: @carljm # Your environment - CPython versions tested on: `3.120b4` - Operating system and architecture: macOS ARM64 <!-- gh-linked-prs --> ### Linked PRs * gh-106977 * gh-107204 <!-- /gh-linked-prs -->
e5d5522612e03af3941db1d270bf6caebf330b8a
b38370349139e06f3a44150943ee44e345567d77