New features:
* refactor `hashlib_helper.requires_hashdigest` in prevision of a future
`hashlib_helper.requires_builtin_hashdigest` for built-in hashes only
* add `hashlib_helper.requires_openssl_hashdigest` to request OpenSSL
hashes, assuming that `_hashlib` exists.
Refactoring:
* split hmac.copy() test by implementation
* update how algorithms are discovered for RFC test cases
* simplify how OpenSSL hash digests are requested
* refactor hexdigest tests for RFC test vectors
* typo fix: `assert_hmac_hexdigest_by_new` -> `assert_hmac_hexdigest_by_name`
Improvements:
* strengthen contract on `hmac_new_by_name` and `hmac_digest_by_name`
* rename mixin classes to better match their responsibility
Remove the `test.test_pathlib.test_pathlib_abc` test module, which was
hollowed out in previous commits. Its few remaining tests are most relevant
to `PurePath` and `Path`, so we move them into `test_pathlib`.
Co-authored-by: blurb-it[bot] <43283697+blurb-it[bot]@users.noreply.github.com>
Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com>
The implementation of `PyLong_FromLong()`, `PyLong_FromLongLong()` and `PyLong_FromSsize_t()`
are now handled by a common macro `PYLONG_FROM_INT` which contains fast paths depending on the
size of the integer to convert. Consequently, `PyLong_FromSsize_t()` for medium-sized integers is faster
by roughly 25%.
---------
Co-authored-by: Sergey B Kirpichev <skirpichev@gmail.com>
`concurrent.futures.Executor.map` now supports limiting the number of submitted
tasks whose results have not yet been yielded via the new `buffersize` parameter.
---------
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
Modifies the behavior of the interpreter on crash under Emscripten:
1. No Python traceback shown on segfault/trap
2. The JavaScript source line is shown
The JavaScript source line is super long and completely unenlightening,
whereas the Python traceback is very helpful.
Check would fail if value would create a pseudo-member, but that member
had not yet been created. We now attempt to create a pseudo-member for
a passed-in value first.
Co-authored-by: Tomas R. <tomas.roun8@gmail.com>
Test `pathlib.types._WritablePath` in a dedicated test module. These tests
cover `WritableZipPath`, `WritableLocalPath` and `Path`, where the former
two classes are implementations of `_WritablePath` for use in tests.
Add free-threaded versions of existing specialization for FOR_ITER (list, tuples, fast range iterators and generators), without significantly affecting their thread-safety. (Iterating over shared lists/tuples/ranges should be fine like before. Reusing iterators between threads is not fine, like before. Sharing generators between threads is a recipe for significant crashes, like before.)
Test `pathlib.types._ReadablePath` in a dedicated test module. These tests
cover `ReadableZipPath`, `ReadableLocalPath` and `Path`, where the former
two classes are implementations of `_ReadablePath` for use in tests.
Test Windows-flavoured `pathlib.types._JoinablePath` in a dedicated test
module. These tests cover `LexicalWindowsPath`, `PureWindowsPath` and
`WindowsPath`, where `LexicalWindowsPath` is a simple implementation of
`_JoinablePath` for use in tests.
* gh-130959: Reject whitespace in fractions, in pure Python `fromisoformat()`
Fix the pure Python implementation of `fromisoformat()` to reject any
non-digit characters, including whitespace, in the fractional part
of time specification. This makes the behavior consistent with the C
implementation, and prevents incorrect parsing of these fractions
(e.g. `.400 ` would be misinterpreted as `.04`).
* Add the news entry
* Use a different example to fix Sphinx lint
* Apply suggestions from code review
Co-authored-by: Peter Bierma <zintensitydev@gmail.com>
Co-authored-by: Paul Ganssle <1377457+pganssle@users.noreply.github.com>
* Try fixing `:func:` ref.
---------
Co-authored-by: Peter Bierma <zintensitydev@gmail.com>
Co-authored-by: Paul Ganssle <1377457+pganssle@users.noreply.github.com>
Test Posix-flavoured `pathlib.types._JoinablePath` in a dedicated test
module. These tests cover `LexicalPosixPath`, `PurePosixPath` and
`PosixPath`, where `LexicalPosixPath` is a simple implementation of
`_JoinablePath` for use in tests.
Remove the *case_sensitive* argument from `_JoinablePath.full_match()` and
`_ReadablePath.glob()`. Using a non-native case sensitivity forces the use
of "case-pedantic" globbing, where we `iterdir()` even for non-wildcard
pattern segments. But it's hard to know when to enable this mode, as
case-sensitivity can vary by directory, so `_PathParser.normcase()` doesn't
always give the full picture. The `Path.glob()` implementation is forced to
make an educated guess, but we can avoid the issue in the ABCs by dropping
the *case_sensitive* argument.
(I probably shouldn't have added these arguments in `PurePath` and `Path`
in the first place!)
Also drop support for `_ReadablePath.glob(recurse_symlinks=False)`, which
makes recursive globbing much slower.
Test `pathlib.types._JoinablePath` in a dedicated test module. These tests
cover `LexicalPath`, `PurePath` and `Path`, where `LexicalPath` is defined
in a new `test.test_pathlib.support` package.
The test could deadlock trying join on the worker processes.
Apply the same technique as gh-130933.
Join the process before the test ends in `test_notify` as well.
The new methods simply delegate to the underlying buffer, much like the existing GzipFile.read[1] methods. This avoids extra allocations caused by the BufferedIOBase.readinto implementation previously used.
This commit also factors out a common readability check rather than copying it an additional two times.
The workload to advance the virtual timeout is too lightweight for some
platforms. As result the test goes in timeout as it never reaches the
end of the timer. By having a heavier workload, the virtual timer
advances rapidly and the SIGVTALRM is sent before the timeout.
The test could deadlock trying join on the worker processes due to a
combination of behaviors:
* The use of `assertReachesEventually` did not ensure that workers
actually woken.release() because the SyncManager's Semaphore does not
implement get_value.
* This mean that the test could finish and the variable "sleeping" would
got out of scope and be collected. This unregisters the proxy leading
to failures in the worker or possibly the manager.
* The subsequent call to `p.join()` during cleanUp therefore never
finished.
This takes two approaches to fix this:
1) Use woken.acquire() to ensure that the workers actually finish
calling woken.release()
2) At the end of the test, wait until the workers are finished, while `cond`,
`sleeping`, and `woken` are still valid.
I chose to not raise an exception here because I think it would be
confusing for module attribute access to start raising something other
than AttributeError if e.g. the cwd goes away
Without the change in moduleobject.c
```
./python.exe -m unittest test.test_import.ImportTests.test_script_shadowing_stdlib_cwd_failure
...
Assertion failed: (PyErr_Occurred()), function _PyObject_SetAttributeErrorContext, file object.c, line 1253.
```
Fix `test_list.ListTest.test_no_memory` under trace refs build
Memory allocation ends up failing in _PyRefchainTrace(), which produces
different output. Assert that we don't segfault, which is the thing
we want to test and is less brittle than checking output.
This adds two new methods to `multiprocessing`'s `ProcessPoolExecutor`:
- **`terminate_workers()`**: forcefully terminates worker processes using `Process.terminate()`
- **`kill_workers()`**: forcefully kills worker processes using `Process.kill()`
These methods provide users with a direct way to stop worker processes without `shutdown()` or relying on implementation details, addressing situations where immediate termination is needed.
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
Co-authored-by: blurb-it[bot] <43283697+blurb-it[bot]@users.noreply.github.com>
Co-authored-by: Sam Gross @colesbury
Commit-message-mostly-authored-by: Claude Sonnet 3.7 (because why not -greg)
* Fix use after free in list objects
Set the items pointer in the list object to NULL after the items array
is freed during list deallocation. Otherwise, we can end up with a list
object added to the free list that contains a pointer to an already-freed
items array.
* Mark `_PyList_FromStackRefStealOnSuccess` as escaping
I think technically it's not escaping, because the only object that
can be decrefed if allocation fails is an exact list, which cannot
execute arbitrary code when it is destroyed. However, this seems less
intrusive than trying to special cases objects in the assert in `_Py_Dealloc`
that checks for non-null stackpointers and shouldn't matter for performance.
The bytecode compiler only generates a few different types of constants,
like str, int, tuple, slices, etc. Users can construct code objects with
various unusual constants, including ones that are not hashable or not
even constant.
The free threaded build previously crashed with a fatal error when
confronted with these constants. Instead, treat distinct objects of
otherwise unhandled types as not equal for the purposes of deduplication.
Fix a race condition in test_check_output_timeout() of
test_subprocess. Don't write into stdout anymore, since there is no
reliable way to synchronize the parent and the child processes.
Change the timeout from 3 seconds to 0.1 seconds, and remove
@requires_resource('walltime') decorator.
Disable pedantic check for c++03 (unlimited API)
Also add a check for c++03 *limited* API, which passes in pedantic mode
after removing a comma in the `PySendResult` declaration, and allowing
`long long`.
Add support for generating UUIDv7 objects according to RFC 9562, §5.7 [1].
The functionality is provided by the `uuid.uuid7()` function. The implementation
is based on a 42-bit counter as described by Method 1, §6.2 [2] and guarantees
monotonicity within the same millisecond.
[1]: https://www.rfc-editor.org/rfc/rfc9562.html#section-5.7
[2]: https://www.rfc-editor.org/rfc/rfc9562.html#section-6.2
---------
Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com>
Co-authored-by: Victor Stinner <vstinner@python.org>
Co-authored-by: Éric <merwok@netwok.org>
Replace hardcoded delay (100 ms) with a loop awaiting until a
condition is true: replace assertReturnsIfImplemented() with
assertReachesEventually().
Use sleeping_retry() in assertReachesEventually() to tolerate slow
buildbots and raise an exception on timeout (30 seconds).
There used to be a meaningful distinction between these modules: `pathlib`
imported `pathlib._abc` but not `pathlib.types`. This is no longer the
case (neither module is imported), so we move the ABCs as follows:
- `pathlib._abc.JoinablePath` --> `pathlib.types._JoinablePath`
- `pathlib._abc.ReadablePath` --> `pathlib.types._ReadablePath`
- `pathlib._abc.WritablePath` --> `pathlib.types._WritablePath`
* Mark functions that will never be called with # pragma: no cover
* Fix testpatch.PatchTest.test_exit_idempotent
.stop() and __exit__ have subtly different code paths, so to really test __exit__ idempotency, we need to call it specifically twice.
Since we plan to introduce a built-in implementation for HMAC based on HACL*,
it becomes important for the HMAC tests to be flexible enough to avoid code
duplication.
In addition to the new layout based on mixin classes, we extend test coverage by
also testing the `__repr__` of HMAC objects and the HMAC one-shot functions.
We also fix the import to `_sha256` which, since gh-101924, resulted in some tests being
skipped as the module is no more available (its content was moved to the `_sha2` module).
This adds two new methods to `multiprocessing`'s `ProcessPoolExecutor`:
- **`terminate_workers()`**: forcefully terminates worker processes using `Process.terminate()`
- **`kill_workers()`**: forcefully kills worker processes using `Process.kill()`
These methods provide users with a direct way to stop worker processes without `shutdown()` or relying on implementation details, addressing situations where immediate termination is needed.
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
Co-authored-by: blurb-it[bot] <43283697+blurb-it[bot]@users.noreply.github.com>
Commit-message-mostly-authored-by: Claude Sonnet 3.7 (because why not -greg)
Add support for generating UUIDv6 objects according to RFC 9562, §5.6 [1].
The functionality is provided by the `uuid.uuid6()` function which takes as inputs an optional 48-bit
hardware address and an optional 14-bit clock sequence. The UUIDv6 temporal fields are ordered
differently than those of UUIDv1, thereby providing improved database locality.
[1]: https://www.rfc-editor.org/rfc/rfc9562.html#section-5.6
---------
Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com>
Co-authored-by: Victor Stinner <vstinner@python.org>
Remove the *mode*, *parents* and *exist_ok* arguments from
`WritablePath.mkdir()`. These arguments imply support for POSIX permissions
and checking for preexistence of the path or its parents, but subclasses of
`WritablePath` may not have these capabilities.
The public `Path.mkdir()` method retains these arguments.
Remove `ReadablePath` methods duplicated by `ReadablePath.info`. To be
specific, we remove `exists()`, `is_dir()`, `is_file()` and `is_symlink()`.
The public `Path` class retains these methods.
This broke tests on the 'aarch64 Fedora Stable Clang Installed 3.x' and
'AMD64 Fedora Stable Clang Installed 3.x' build bots.
This reverts commit da4899b94a.
## Filtered recursive walk
Expanding a recursive `**` segment entails walking the entire directory
tree, and so any subsequent pattern segments (except special segments) can
be evaluated by filtering the expanded paths through a regex. For example,
`glob.glob("foo/**/*.py", recursive=True)` recursively walks `foo/` with
`os.scandir()`, and then filters paths through a regex based on "`**/*.py`,
with no further filesystem access needed.
This fixes an issue where `glob()` could return duplicate results.
## Tracking path existence
We store a flag alongside each path indicating whether the path is
guaranteed to exist. As we process the pattern:
- Certain special pattern segments (`""`, `"."` and `".."`) leave the flag
unchanged
- Literal pattern segments (e.g. `foo/bar`) set the flag to false
- Wildcard pattern segments (e.g. `*/*.py`) set the flag to true (because
children are found via `os.scandir()`)
- Recursive pattern segments (e.g. `**`) leave the flag unchanged for the
root path, and set it to true for descendants discovered via
`os.scandir()`.
If the flag is false at the end, we call `lstat()` on each path to filter
out missing paths.
## Minor speed-ups
- Exclude paths that don't match a non-terminal non-recursive wildcard
pattern _prior_ to calling `is_dir()`.
- Use a stack rather than recursion to implement recursive wildcards.
- This fixes a recursion error when globbing deep trees.
- Pre-compile regular expressions and pre-join literal pattern segments.
- Convert to/from `bytes` (a minor use-case) in `iglob()` rather than
supporting `bytes` throughout. This particularly simplifies the code
needed to handle relative bytes paths with `dir_fd`.
- Avoid calling `os.path.join()`; instead we keep paths in a normalized
form and append trailing slashes when needed.
- Avoid calling `os.path.normcase()`; instead we use case-insensitive regex
matching.
## Implementation notes
Much of this functionality is already present in pathlib's implementation
of globbing. The specific additions we make are:
1. Support for `dir_fd`
2. Support for `include_hidden`
3. Support for generating paths relative to `root_dir`
This unifies the implementations of globbing in the `glob` and `pathlib`
modules.
Co-authored-by: Pieter Eendebak <pieter.eendebak@gmail.com>
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
* Combine _GUARD_GLOBALS_VERSION_PUSH_KEYS and _LOAD_GLOBAL_MODULE_FROM_KEYS into _LOAD_GLOBAL_MODULE
* Combine _GUARD_BUILTINS_VERSION_PUSH_KEYS and _LOAD_GLOBAL_BUILTINS_FROM_KEYS into _LOAD_GLOBAL_BUILTINS
* Combine _CHECK_ATTR_MODULE_PUSH_KEYS and _LOAD_ATTR_MODULE_FROM_KEYS into _LOAD_ATTR_MODULE
* Remove stack transient in LOAD_ATTR_WITH_HINT
A reference loop was resulting in the `fileobj` held by the `GzipFile`
being closed before the `GzipFile`.
The issue started with gh-89550 in 3.12, but was hidden in most cases
until 3.13 when gh-62948 made it more visible.
Add two optional, traling elements in the AF_BLUETOOTH socket address tuple:
- l2_cid, to allow e.g raw LE ATT connections
- l2_bdaddr_type. To be able to connect L2CAP sockets to Bluetooth LE devices,
the l2_bdaddr_type must be set to BDADDR_LE_PUBLIC or BDADDR_LE_RANDOM.
There are a number of data races in the default build without
suppressions that are exposed by this test. Disable the test for now
under TSAN until we have suppressions or fix the data races.
The `free_work_item()` function in QSBR may call arbitrary code via
Python object destructors, which may reenter the QSBR code. Reorder
the processing of work items to be robust to reentrancy.
Also fix the TODO for the out of memory situation.
* Revert "gh-128982: Substitute regular expression in `http.cookiejar.join_header_words` for an efficient alternative (GH-128983)"
This reverts commit 56e1900681.
* Add tests
The use of PySys_GetObject() and _PySys_GetAttr(), which return a borrowed
reference, has been replaced by using one of the following functions, which
return a strong reference and distinguish a missing attribute from an error:
_PySys_GetOptionalAttr(), _PySys_GetOptionalAttrString(),
_PySys_GetRequiredAttr(), and _PySys_GetRequiredAttrString().
There are multiple data races reported when running the
InterpreterPoolMixin tests, but it's still useful to run the other
test_concurrent_futures tests under TSAN.
Add test_concurrent_futures to the TSAN test suite.
* Implement C recursion protection with limit pointers for Linux, MacOS and Windows
* Remove calls to PyOS_CheckStack
* Add stack protection to parser
* Make tests more robust to low stacks
* Improve error messages for stack overflow
In `pathlib.Path.copy()` and `move()`, return a fresh `Path` object with an
unpopulated `info` attribute, rather than a `Path` object with information
recorded *prior* to the path's creation.
Revert "GH-91079: Implement C stack limits using addresses, not counters. (GH-130007)" for now
Unfortunatlely, the change broke some buildbots.
This reverts commit 2498c22fa0.
The SyncManager provided support for various data structures such as dict, list, and queue, but oddly, not set.
This introduces support for set by defining SetProxy and registering it with SyncManager.
---
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
Co-authored-by: Gregory P. Smith <greg@krypto.org>
To support virtual terminal mode in Windows PYREPL, we need a scanner
to read over the supported escaped VT sequences.
Windows REPL input was using virtual key mode, which does not support
terminal escape sequences. This patch calls `SetConsoleMode` properly
when initializing and send sequences to enable bracketed-paste modes
to support verbatim copy-and-paste.
Signed-off-by: y5c4l3 <y5c4l3@proton.me>
Co-authored-by: Petr Viktorin <encukou@gmail.com>
Co-authored-by: Pablo Galindo Salgado <Pablogsal@gmail.com>
Co-authored-by: Dustin L. Howett <dustin@howett.net>
Co-authored-by: wheeheee <104880306+wheeheee@users.noreply.github.com>
First, write the test name without color. Then, write the test name
and the result with color. Each test is displayed twice.
Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com>
The `test_trace.test_coverage_ignore` test would fail if you had
`setuptools` installed, such as in `~/.local/lib/python3.xxx/site-packages/`.
Ignore everything in `sys.path` when running the test.
The code is still flawed, because it does not recognize class and static
methods, and the first argument is not removed from the signature of
bound methods, but at least it does not worse than in 3.13 and older.
Ensure colorize tests will run on dumb terminals (or environment with TERM=dumb set)
Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com>
* Implement C recursion protection with limit pointers
* Remove calls to PyOS_CheckStack
* Add stack protection to parser
* Make tests more robust to low stacks
* Improve error messages for stack overflow
Make tuple iteration more thread-safe, and actually test concurrent iteration of tuple, range and list. (This is prep work for enabling specialization of FOR_ITER in free-threaded builds.) The basic premise is:
Iterating over a shared iterable (list, tuple or range) should be safe, not involve data races, and behave like iteration normally does.
Using a shared iterator should not crash or involve data races, and should only produce items regular iteration would produce. It is not guaranteed to produce all items, or produce each item only once. (This is not the case for range iteration even after this PR.)
Providing stronger guarantees is possible for some of these iterators, but it's not always straight-forward and can significantly hamper the common case. Since iterators in general aren't shared between threads, and it's simply impossible to concurrently use many iterators (like generators), better to make sharing iterators without explicit synchronization clearly wrong.
Specific issues fixed in order to make the tests pass:
- List iteration could occasionally fail an assertion when a shared list was shrunk and an item past the new end was retrieved concurrently. There's still some unsafety when deleting/inserting multiple items through for example slice assignment, which uses memmove/memcpy.
- Tuple iteration could occasionally crash when the iterator's reference to the tuple was cleared on exhaustion. Like with list iteration, in free-threaded builds we can't safely and efficiently clear the iterator's reference to the iterable (doing it safely would mean extra, slow refcount operations), so just keep the iterable reference around.
In the Python implementation, "Z" was allowed where only "+" or "-" should be allowed in time zone specifiers. In the C implementation, ":" was allowed as a separator between the whole and fractional portion of times (seconds). These have both been forbidden and the error messages harmonized.
The test should use the correct idiom for starting the task, `loop._run_once` is private API which should not be used directly, instead use `asyncio.sleep(0)` for 1 event loop cycle.
Add the following private methods to `pathlib.Path.info`:
- `_posix_permissions()`: the POSIX file permissions (`S_IMODE(st_mode)`)
- `_file_id()`: the file ID (`(st_dev, st_ino)`)
- `_access_time_ns()`: the access time in nanoseconds (`st_atime_ns`)
- `_mod_time_ns()`: the modify time in nanoseconds (`st_mtime_ns`)
- `_bsd_flags()`: the BSD file flags (`st_flags`)
- `_xattrs()`: the file extended attributes as a list of key, value pairs,
or an empty list if `listxattr()` or `getxattr()` fail in an ignorable
way.
These methods replace `LocalCopyReader.read_metadata()`, and so we can
delete the `CopyReader` and `LocalCopyReader` classes. Rather than reading
metadata via `source._copy_reader.read_metadata()`, we instead call
`source.info._posix_permissions()`, `_access_time_ns()`, etc.
Preserving metadata is only supported for local-to-local copies at the
moment. To support copying metadata between arbitrary `ReadablePath` and
`WritablePath` objects, we'd need to make the new methods public and
documented.
Co-authored-by: Petr Viktorin <encukou@gmail.com>
Remove broken singledispatchmethod caching introduced in gh-85160.
Achieve the same performance using different optimization.
* Add more tests.
* Fix issues with __module__ and __doc__ descriptors.
Convert `JoinablePath`, `ReadablePath` and `WritablePath` to real ABCs
derived from `abc.ABC`.
Make `JoinablePath.parser` abstract, rather than defaulting to `posixpath`.
Register `PurePath` and `Path` as virtual subclasses of the ABCs rather
than deriving. This avoids a hit to path object instantiation performance.
No change of behaviour in the public (non-abstract) classes.
We had the definition of what makes a character "printable" documented in three places, giving two different definitions.
The definition in the comment on `_PyUnicode_IsPrintable` was inverted; correct that.
With that correction, the two definitions turn out to be equivalent -- but to confirm that, you have to go look up, or happen to know, that those are the only five "Other" categories and only three "Separator" categories in the Unicode character database. That makes it hard for the reader to tell whether they really are the same, or if there's some subtle difference in the intended semantics.
Fix that by cutting the C API docs' and the C comment's copies of the subtle details, in favor of referring to the Python-level docs. That ensures it's explicit that these are all meant to agree, and also lets us concentrate improvements to the wording in one place.
Speaking of which, borrow some ideas from the C comment, along with other tweaks, to hopefully add a bit more clarity to that one newly-centralized copy in the docs.
Also add a thorough test that the implementation agrees with this definition.
Author: Greg Price <gnprice@gmail.com>
Co-authored-by: Greg Price <gnprice@gmail.com>
As it says in its documentation, walk_stack was meant to just
follow `f.f_back` like other functions in the traceback module.
Instead it was previously doing `f.f_back.f_back` and then this
changed to `f_back.f_back.f_back.f_back' in Python 3.11 breaking
its behavior for external users.
This happened because the walk_stack function never really had
any good direct tests and its only consumer in the traceback module was
`extract_stack` which passed the result into `StackSummary.extract`.
As a generator, it was previously capturing the state of the stack
when it was first iterated over, rather than the stack when `walk_stack`
was called. Meaning when called inside the two method deep
`extract` and `extract_stack` calls, two `f_back`s were needed.
When 3.11 modified the sequence of calls in `extract`, two more
`f_back`s were needed to make the tests happy.
This changes the generator to capture the stack when `walk_stack` is
called, rather than when it is first iterated over. Since this is
technically a breaking change in behavior, there is a versionchanged
to the documentation. In practice, this is unlikely to break anyone,
you would have been needing to store the result of `walk_stack` and
expecting it to change.
Updates error messages in datetime and makes them consistent between Python and C.
---------
Co-authored-by: Erlend E. Aasland <erlend.aasland@protonmail.com>
Co-authored-by: Peter Bierma <zintensitydev@gmail.com>
Co-authored-by: Paul Ganssle <1377457+pganssle@users.noreply.github.com>
The call to `PySequence_List()` could temporarily unlock and relock the
set, allowing the items to be cleared and return the incorrect
notation `{}` for a empty set (it should be `set()`).
Co-authored-by: T. Wouters <thomas@python.org>
Fix a few thread-safety bugs to enable test_opcache when run with TSAN:
* Use relaxed atomics when clearing `ht->_spec_cache.getitem`
(gh-115999)
* Add temporary suppression for type slot modifications (gh-127266)
* Use atomic load when reading `*dictptr`
In case gcc is not available, the test will fail with FileNotFoundError.
So catch the exception to skip the test correctly.
Signed-off-by: Peter Marko <peter.marko@siemens.com>
* gh-128657: Run test_hashlib with `--parallel-threads`
This catches the race in `py_digest_by_name` that is fixed separately
in gh-128886.
* Adjust assertion order
Add function to list the currently loaded libraries to ctypes.util
The dllist() function calls platform-specific APIs in order to
list the runtime libraries loaded by Python and any imported modules.
On unsupported platforms the function may be missing.
Co-authored-by: Eryk Sun <eryksun@gmail.com>
Co-authored-by: Peter Bierma <zintensitydev@gmail.com>
In the private pathlib ABCs, make `ReadablePath.glob('')` yield a path with
a trailing slash (if it yields anything at all). As a result, `glob()`
works similarly to `joinpath()` when given a non-magic pattern.
In the globbing implementation, we preemptively add trailing slashes to
intermediate paths if there are pattern parts remaining; this removes the
need to check for existing trailing slashes (in the removed `add_slash()`
method) at subsequent steps.
Add `pathlib.Path.info` attribute, which stores an object implementing the `pathlib.types.PathInfo` protocol (also new). The object supports querying the file type and internally caching `os.stat()` results. Path objects generated by `Path.iterdir()` are initialised with status information from `os.DirEntry` objects, which is gleaned from scanning the parent directory.
The `PathInfo` protocol has four methods: `exists()`, `is_dir()`, `is_file()` and `is_symlink()`.
* gh-55454: Add IMAP4 IDLE support to imaplib
This extends imaplib with support for the rfc2177 IMAP IDLE command,
as requested in #55454. It allows events to be pushed to a client as
they occur, rather than having to continually poll for mailbox changes.
The interface is a new idle() method, which returns an iterable context
manager. Entering the context starts IDLE mode, during which events
(untagged responses) can be retrieved using the iteration protocol.
Exiting the context sends DONE to the server, ending IDLE mode.
An optional time limit for the IDLE session is supported, for use with
servers that impose an inactivity timeout.
The context manager also offers a burst() method, designed for programs
wishing to process events in batch rather than one at a time.
Notable differences from other implementations:
- It's an extension to imaplib, rather than a replacement.
- It doesn't introduce additional threads.
- It doesn't impose new requirements on the use of imaplib's existing methods.
- It passes the unit tests in CPython's test/test_imaplib.py module
(and adds new ones).
- It works on Windows, Linux, and other unix-like systems.
- It makes IDLE available on all of imaplib's client variants
(including IMAP4_stream).
- The interface is pythonic and easy to use.
Caveats:
- Due to a Windows limitation, the special case of IMAP4_stream running
on Windows lacks a duration/timeout feature. (This is the stdin/stdout
pipe connection variant; timeouts work fine for socket-based
connections, even on Windows.) I have documented it where appropriate.
- The file-like imaplib instance attributes are changed from buffered to
unbuffered mode. This could potentially break any client code that
uses those objects directly without expecting partial reads/writes.
However, these attributes are undocumented. As such, I think (and
PEP 8 confirms) that they are fair game for changes.
https://peps.python.org/pep-0008/#public-and-internal-interfaces
Usage examples:
https://github.com/python/cpython/issues/55454#issuecomment-2227543041
Original discussion:
https://discuss.python.org/t/gauging-interest-in-my-imap4-idle-implementation-for-imaplib/59272
Earlier requests and suggestions:
https://github.com/python/cpython/issues/55454https://mail.python.org/archives/list/python-ideas@python.org/thread/C4TVEYL5IBESQQPPS5GBR7WFBXCLQMZ2/
* gh-55454: Clarify imaplib idle() docs
- Add example idle response tuples, to make the minor difference from other
imaplib response tuples more obvious.
- Merge the idle context manager's burst() method docs with the IMAP
object's idle() method docs, for easier understanding.
- Upgrade the Windows note regarding lack of pipe timeouts to a warning.
- Rephrase various things for clarity.
* docs: words instead of <=
Co-authored-by: Peter Bierma <zintensitydev@gmail.com>
* docs: improve style in an example
Co-authored-by: Peter Bierma <zintensitydev@gmail.com>
* docs: grammatical edit
Co-authored-by: Peter Bierma <zintensitydev@gmail.com>
* docs consistency
Co-authored-by: Peter Bierma <zintensitydev@gmail.com>
* comment -> docstring
Co-authored-by: Peter Bierma <zintensitydev@gmail.com>
* docs: refer to imaplib as "this module"
Co-authored-by: Peter Bierma <zintensitydev@gmail.com>
* imaplib: simplify & clarify idle debug message
Co-authored-by: Peter Bierma <zintensitydev@gmail.com>
* imaplib: elaborate in idle context manager comment
* imaplib: re-raise BaseException instead of bare except
Co-authored-by: Peter Bierma <zintensitydev@gmail.com>
* imaplib: convert private doc string to comment
* docs: correct mistake in imaplib example
This is a correction to 8077f2eab2, which
changed a variable name in only one place and broke the subsequent
reference to it, departed from the naming convention used in the rest of
the module, and shadowed the type() builtin along the way.
* imaplib: simplify example code in doc string
This is for consistency with the documentation change in 8077f2eab2
and subsequent correction in 013bbf18fc.
* imaplib: rename _Idler to Idler, update its docs
* imaplib: add comment in Idler._pop()
Co-authored-by: Peter Bierma <zintensitydev@gmail.com>
* imaplib: remove unnecessary blank line
Co-authored-by: Peter Bierma <zintensitydev@gmail.com>
* imaplib: comment on use of unbuffered pipes
* docs: imaplib: use the reStructuredText :class: role
Co-authored-by: Peter Bierma <zintensitydev@gmail.com>
* Revert "docs: imaplib: use the reStructuredText :class: role"
This reverts commit f385e441df, because it
triggers CI failures in the docs by referencing a class that is
(deliberately) undocumented.
* docs: imaplib: use the reST :class: role, escaped
This is a different approach to f385e441df, which was reverted for
creating dangling link references.
By prefixing the reStructuredText role target with a ! we disable
conversion to a link, thereby passing continuous integration checks
even though the referenced class is deliberately absent from the
documentation.
* docs: refer to IMAP4 IDLE instead of just IDLE
This clarifies that we are referring to the email protocol, not the editor with the same name.
Co-authored-by: Guido van Rossum <gvanrossum@gmail.com>
* imaplib: IDLE -> IMAP4 IDLE in exception message
Co-authored-by: Peter Bierma <zintensitydev@gmail.com>
* docs: imaplib idle() phrasing and linking tweaks
* docs: imaplib: avoid linking to an invalid target
This reverts and rephrases part of a3f21cd75b
which created links to a method on a deliberately undocumented class.
The links didn't work consistently, and caused sphinx warnings that
broke cpython's continuous integration tests.
* imaplib: update test after recent exception change
This fixes a test that was broken by changing an exception in
b01de95171
* imaplib: rename idle() dur argument to duration
* imaplib: bytes.index() -> bytes.find()
This makes it more obvious which statement triggers the branch.
* imaplib: remove no-longer-necessary statement
Co-authored-by: Martin Panter <vadmium@users.noreply.github.com>
* docs: imaplib: concise & valid method links
The burst() method is a little tricky to link in restructuredText, due
to quirks of its parent class. This syntax allows sphinx to generate
working links without generating warnings (which break continuous
integration) and without burdening the reader with unimportant namespace
qualifications. It makes the reST source ugly, but few people read
the reST source, so it's a tolerable tradeoff.
* imaplib: note data types present in IDLE responses
* docs: imaplib: add comma to reST changes header
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
* imaplib: sync doc strings with reST docs
* docs: imaplib: minor Idler clarifications
* imaplib: idle: emit (type, [data, ...]) tuples
This allows our iterator to emit untagged responses that contain literal
strings in the same way that imaplib's existing methods do, while still
emitting exactly one whole response per iteration.
* imaplib: while/yield instead of yield from iter()
* imaplib: idle: use deadline idiom when iterating
This simplifies the code, and avoids idle duration drift from time spent
processing each iteration.
* docs: imaplib: state duration/interval arg types
* docs: imaplib: minor rephrasing of a sentence
* docs: imaplib: reposition a paragraph
This might improve readability, especially when encountering Idler.burst()
for the first time.
* docs: imaplib: wrap long lines in idle() section
* docs: imaplib: note: Idler objects require 'with'
* docs: imaplib: say that 29 minutes is 1740 seconds
* docs: imaplib: mark a paragraph as a 'tip'
* docs: imaplib: rephrase reference to MS Windows
* imaplib: end doc string titles with a period
* imaplib: idle: socket timeouts instead of select()
IDLE timeouts were originally implemented using select() after
checking for the presence of already-buffered data.
That allowed timeouts on pipe connetions like IMAP4_stream.
However, it seemed possible that SSL data arriving without any
IMAP data afterward could cause select() to indicate available
application data when there was none, leading to a read() call
that would block with no timeout. It was unclear under what
conditions this would happen in practice. This change switches
to socket timeouts instead of select(), just to be safe.
This also reverts IMAP4_stream changes that were made to support IDLE
timeouts, since our new implementation only supports socket connections.
* imaplib: Idler: rename private state attributes
* imaplib: rephrase a comment in example code
* docs: imaplib: idle: use Sphinx code-block:: pycon
* docs: whatsnew: imaplib: reformat IMAP4.idle entry
* imaplib: idle: make doc strings brief
Since we generally rely on the reST/html documentation for details, we
can keep these doc strings short. This matches the module's existing doc
string style and avoids having to sync small changes between two files.
* imaplib: Idler: split assert into two statements
* imaplib: Idler: move assignment out of try: block
* imaplib: Idler: move __exit__() for readability
* imaplib: Idler: move __next__() for readability
* imaplib: test: make IdleCmdHandler a global class
* docs: imaplib: idle: collapse double-spaces
* imaplib: warn on use of undocumented 'file' attr
* imaplib: revert import reformatting
Since we no longer import platform or selectors, the original import
statement style can be restored, reducing the footprint of PR #122542.
* imaplib: restore original exception msg formatting
This reduces the footprint of PR #122542.
* docs: imaplib: idle: versionadded:: next
* imaplib: move import statement to where it's used
This import is only needed if external code tries to use an attribute
that it shouldn't be using. Making it a local import reduces module
loading time in supported cases.
* imaplib test: RuntimeWarning on IMAP4.file access
* imaplib: use stacklevel=2 in warnings.warn()
* imaplib test: simplify IMAP4.file warning test
* imaplib test: pre-idle-continuation response
* imaplib test: post-done untagged response
* imaplib: downgrade idle-denied exception to error
This makes it easier for client code to distinguish a temporary
rejection of the IDLE command from a server responding incorrectly to
IDLE.
* imaplib: simplify check for socket object
* imaplib: narrow the scope of IDLE socket timeouts
If an IDLE duration or burst() was in use, and an unsolicited response
contained a literal string, and crossed a packet boundary, and the
subsequent packet was delayed beyond the IDLE feature's time limit, the
timeout would leave the incoming protocol stream in a bad state (with
the tail of that response appearing where the start of a response is
expected).
This change moves the IDLE socket timeout to cover only the start
of a response, so it can no longer cause that problem.
* imaplib: preserve partial reads on exception
This ensures that short IDLE durations / burst() intervals
won't risk corrupting response lines that span multiple packets.
* imaplib: read/readline: save multipart buffer tail
For resilience if read() or readline() ever complete with more than one
bytes object remaining in the buffer. This is not expected to happen,
but it seems wise to be prepared for a future change making it possible.
* imaplib: use TimeoutError subclass only if needed
* doc: imaplib: elaborate on IDLE response delivery
* doc: imaplib: elaborate in note re: IMAP4.response
* imaplib: comment on benefit of reading in chunks
Our read() implementation designed to support IDLE replaces the one from
PR #119514, fixing the same problem it was addressing. The tests that it
added are preserved.
* imaplib: readline(): treat ConnectionError as EOF
---------
Co-authored-by: Gregory P. Smith <greg@krypto.org>
Co-authored-by: Peter Bierma <zintensitydev@gmail.com>
Co-authored-by: Guido van Rossum <guido@python.org>
Co-authored-by: Guido van Rossum <gvanrossum@gmail.com>
Co-authored-by: Martin Panter <vadmium@users.noreply.github.com>
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
This adds a new command line argument, `--parallel-threads` to the
regression test runner to allow it to run individual tests in multiple
threads in parallel in order to find multithreading bugs.
Some tests pass when run with `--parallel-threads`, but there's still
more work before the entire suite passes.
Test that the trailing pathname separator is preserved.
Multiple trailing pathname separators are only preserved if the pattern
does not contain metacharacters, otherwise only one trailing pathname
separator is preserved. This is rather an implementation detail.
Restore the skipUnless removed by #119465.
This test can only pass on virtual machines, not actual machines.
actual machines see:
```
self.cli.connect((cid, VSOCKPORT))
~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^
OSError: [Errno 19] No such device
```
Reproduced on (Linux) Ubuntu 24.04.1 running 6.8.0-52-generic.
Move many functions from _testcapimodule.c into more specific files
in Modules/_testcapi/.
In moved code:
* Replace get_testerror() with PyExc_AssertionError.
* Replace raiseTestError() with
PyErr_Format(PyExc_AssertionError, ...).
Codegen phase has an optimization that transforms
```
LOAD_CONST x
LOAD_CONST y
LOAD_CONXT z
BUILD_LIST/BUILD_SET (3)
```
->
```
BUILD_LIST/BUILD_SET (0)
LOAD_CONST (x, y, z)
LIST_EXTEND/SET_UPDATE 1
```
This optimization has now been moved to CFG phase to make #128802 work.
Co-authored-by: Irit Katriel <1055913+iritkatriel@users.noreply.github.com>
Co-authored-by: Yan Yanchii <yyanchiy@gmail.com>
* gh-105704: Disallow square brackets ( and ) in domain names for parsed URLs
* Use Sphinx references
Co-authored-by: Peter Bierma <zintensitydev@gmail.com>
* Add mismatched bracket test cases, fix news format
* Add more test coverage for ports
---------
Co-authored-by: Peter Bierma <zintensitydev@gmail.com>
* Move PyFunction C API tests to a new file.
* Add Lib/test/test_capi/test_function.py.
* Move tests from test_capi.test_misc to test_capi.test_function.
Move PyType C API tests to a new file.
Move following tests from test_capi.test_misc to test_capi.test_type:
* BuiltinStaticTypesTests
* test_get_type_name()
* test_get_base_by_token()
* Add Lib/test/test_capi/test_frame.py file.
* Move C API tests from test_frame to test_capi.test_frame.
* Add Modules/_testcapi/frame.c file.
* Move C API tests from _testcapimodule.c to frame.c
Add tests for the following functions in test_capi.test_file:
* PyFile_FromFd()
* PyFile_GetLine()
* PyFile_NewStdPrinter()
* PyFile_WriteObject()
* PyFile_WriteString()
* PyObject_AsFileDescriptor()
Add Modules/_testlimitedcapi/file.c file.
Remove test_embed.StdPrinterTests which became redundant.
The `dict.get` implementation uses `_Py_dict_lookup_threadsafe`, which is
thread-safe, so we remove the critical section from the argument clinic.
Add a test for concurrent dict get and set operations.
Unlike `ReadablePath.[r]glob()` and `JoinablePath.full_match()`, the
`JoinablePath.match()` method doesn't support the recursive wildcard `**`,
and matches from the right when a fully relative pattern is given. These
quirks means its probably unsuitable for inclusion in the pathlib ABCs,
especially given `full_match()` handles the same use case.
The parameter `amt` of `HTTPResponse.read()`, which could be a negative integer,
has not been handled before and led to waiting for the connection to close
for `keep-alive connections`. Now, this has been fixed, and passing negative values
to `HTTPResponse().read()` works the same as passing `None` value.
This reduces the size of _PyInterpreterFrame by 8 bytes on 64-bit
platforms using the free threading build due to alignment requirements.
This allows for slightly more recursive calls into the interpreter (from
C), but `test_call.test_super_deep` still crashes.
* Remove all 'if (0)' and 'if (1)' conditional stack effects
* Use array instead of conditional for BUILD_SLICE args
* Refactor LOAD_GLOBAL to use a common conditional uop
* Remove conditional stack effects from LOAD_ATTR specializations
* Replace conditional stack effects in LOAD_ATTR with a 0 or 1 sized array.
* Remove conditional stack effects from CALL_FUNCTION_EX