In `urllib.request.url2pathname()`, if the authority resolves to the
current host, discard it. If an authority is present but resolves somewhere
else, then on Windows we return a UNC path (as before), and on other
platforms we raise `URLError`.
Affects `pathlib.Path.from_uri()` in the same way.
Co-authored-by: Adam Turner <9087854+AA-Turner@users.noreply.github.com>
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
Make `warnings.catch_warnings()` use a context variable for holding
the warning filtering state if the `sys.flags.context_aware_warnings`
flag is set to true. This makes using the context manager thread-safe in
multi-threaded programs.
Add the `sys.flags.thread_inherit_context` flag. If true, starting a new
thread with `threading.Thread` will use a copy of the context
from the caller of `Thread.start()`.
Both these flags are set to true by default for the free-threaded build
and false for the default build.
Move the Python implementation of warnings.py into _py_warnings.py.
Make _contextvars a builtin module.
Co-authored-by: Kumar Aditya <kumaraditya@python.org>
* Always quote strings with non-ASCII characters.
* Allow some non-separator and non-control characters (like "." or "-")
be unquoted.
* Always quote strings that end with "\n".
* Use the fullmatch() method for clarity and optimization.
Non-tuple sequences are deprecated as argument for the "(items)" format unit
in PyArg_ParseTuple() and other argument parsing functions if items contains
format units which store borrowed buffer or reference (e.g. "s" and "O").
str and bytearray are no longer accepted as valid sequences.
Adding aliases for Thai language support. The current code page is an implementation of the windows code page.
This will alias '874', 'ms874', and 'windows_874' to cp874, adding Thai language support for those users.
Co-authored-by: Łukasz Langa <lukasz@langa.pl>
* Add _PYTHON_SUBPROCESS_USE_POSIX_SPAWN environment knob
Add support for disabling the use of `posix_spawn` via a variable in
the process environment.
While it was previously possible to toggle this by modifying the value
of `subprocess._USE_POSIX_SPAWN`, this required either patching CPython
or modifying it within the interpreter instance which is not always
possible, such as when running applications or scripts not under a
user's control.
Signed-off-by: Vincent Fazio <vfazio@gmail.com>
* fixup NEWS entry
---------
Signed-off-by: Vincent Fazio <vfazio@gmail.com>
* Add ZipFile.data_offset attribute
This attribute provides the offset to zip data from the start of the file, when available.
* Add blurb-it
* Try fixing class ref in NEWS
The `http.server` module now supports serving over HTTPS using the `http.server.HTTPSServer` class.
This functionality is also exposed by the command-line interface (`python -m http.server`) through the
`--tls-cert`, `--tls-key` and `--tls-password-file` options.
A new extension module, `_hmac`, now exposes the HACL* HMAC (formally verified) implementation.
The HACL* implementation is used as a fallback implementation when the OpenSSL implementation of HMAC
is not available or disabled. For now, only named hash algorithms are recognized and SIMD support provided
by HACL* for the BLAKE2 hash functions is not yet used.
annotationlib is used quite a few times in typing.py, but I think the
usages are just rare enough that this makes sense.
The import would get triggered by:
- Using get_type_hints(), evaluate_forward_ref(), and similar introspection
functions
- Using a string annotation anywhere that goes through _type_convert (e.g.,
"Final['x']" will trigger an annotationlib import in order to access the
ForwardRef class).
- Creating a TypedDict or NamedTuple (unless it's empty or PEP 563 is on).
Lots of programs will want to use typing without any of these, so the tradeoff
seems worth it.
The exception message for `xml.etree.ElementTree.Element.remove` when an element is not found
has been updated from "list.remove(x): x not in list" to "Element.remove(x): element not found".
It doesn't make sense to use a deprecation for evaluate_forward_ref,
as it is a new function in Python 3.14 and doesn't have compatibility
guarantees.
I considered making it throw an error if type_params it not passed and
there is no owner. However, I think this is too unfriendly for users. The
case where this param is really needed is fairly esoteric and I don't think
this case is worth the pain of forcing users to write "type_params=()".
Optimize `LOAD_FAST` opcodes into faster versions that load borrowed references onto the operand stack when we can prove that the lifetime of the local outlives the lifetime of the temporary that is loaded onto the stack.
* Rename 'defined' attribute to 'in_local' to more accurately reflect how it is used
* Make death of variables explicit even for array variables.
* Convert in_memory from boolean to stack offset
* Don't apply liveness analyis to optimizer generated code
* Add 'out' parameter to stack.pop
We fix a use-after-free in the `find`, `findtext` and `findall` methods of `xml.etree.ElementTree.Element`
objects that can be triggered when the tag to find implements an `__eq__` method that mutates the
element being queried.
`email.message.Message` objects now validate header names specified via `__setitem__`
or `add_header` according to RFC 5322, §2.2 [1].
In particular, callers should expect a ValueError to be raised for invalid header names.
[1]: https://datatracker.ietf.org/doc/html/rfc5322#section-2.2
---------
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
Co-authored-by: R. David Murray <rdmurray@bitdance.com>
Update os.walk example to be more modern, skip `__pycache__` dirs rather than `CVS` dirs.
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
The bin tag is 3.0.16.1 because we rebuilt without uplink support to fix gh-131804.
This PR also prevents making calls that are now unsafe without uplink, and updates
the tests to property interpret these failures as unsupported.
In the free threaded build, the `_PyObject_LookupSpecial()` call can lead to
reference count contention on the returned function object becuase it
doesn't use stackrefs. Refactor some of the callers to use
`_PyObject_MaybeCallSpecialNoArgs`, which uses stackrefs internally.
This fixes the scaling bottleneck in the "lookup_special" microbenchmark
in `ftscalingbench.py`. However, the are still some uses of
`_PyObject_LookupSpecial()` that need to be addressed in future PRs.
Concurrent accesses from multiple threads to the same `cell` object did not
scale well in the free-threaded build. Use `_PyStackRef` and optimistically
avoid locking to improve scaling.
With the locks around cell reads gone, some of the free threading tests were
prone to starvation: the readers were able to run in a tight loop and the
writer threads weren't scheduled frequently enough to make timely progress.
Adjust the tests to avoid this.
Co-authored-by: Donghee Na <donghee.na@python.org>
* Rename 'defined' attribute to 'in_local' to more accurately reflect how it is used
* Make death of variables explicit even for array variables.
* Convert in_memory from boolean to stack offset
* Don't apply liveness analysis to optimizer generated code
* Fix RETURN_VALUE in optimizer
In `JoinablePath.full_match()` and `ReadablePath.glob()`, accept a `str`
pattern argument rather than `JoinablePath | str`.
In `ReadablePath.copy()` and `copy_into()`, accept a `WritablePath` target
argument rather than `WritablePath | str`.
When `pathlib._os.magic_open()` is called to open a path in binary mode,
raise `ValueError` if any of the *encoding*, *errors* or *newline*
arguments are given. This matches the `open()` built-in.
- Restore max field size to sys.maxsize, as in Python 3.13 & below
- PyCField: Split out bit/byte sizes/offsets.
- Expose CField's size/offset data to Python code
- Add generic checks for all the test structs/unions, using the newly exposed attrs
add a set of asserts to test.test_capi.test_bytearray
1. Assert empty bytearray object for PyByteArray_Check.
2. Assert empty bytearray object for PyByteArray_CheckExact.
3. Assert 0-size bytearray object for PyByteArray_Size.
4. Assert empty bytearray object for PyByteArray_AsString.
5. Assert concatenation of the bytearray object with itself for PyByteArray_Concat.
Adjust the tests for the `pathlib.types` module so that they can be run
against the `pathlib-abc` PyPI package, which is a backport of the module
for older Python versions.
Specifically, we add a `.support.is_pypi` switch that is false in the
stdlib and true in the pathlib-abc package. This controls which package
we import, and whether or not we run tests against `PurePath` and `Path`.
For compatibility with older Python versions, we stop using
`zipfile.ZipFile.mkdir()` and `zipfile.ZipInfo._for_archive()`.
The subinterpreter tests have data races (see gh-129824).
TSAN attempts to intercept some of the fatal signals, which can lead to
bogus reports. We could possibly handle these via TSAN_OPTIONS, but it's
simpler to just skip those tests -- they're not multithreaded anyways.
Call `urllib.request.pathname2url()` from `pathlib.Path.as_uri()`, and
deprecate the duplicate implementation in `PurePath`.
Co-authored-by: Adam Turner <9087854+AA-Turner@users.noreply.github.com>
Call `urllib.request.url2pathname()` from `pathlib.Path.from_uri()` rather
than re-implementing it. This paves the way for solving the main issue
(ignoring local authorities and rejecting non-local ones) in urllib, not
pathlib.
Deprecate the `nturl2path` module. Its functionality is merged into
`urllib.request`.
Add `tests.test_nturl2path` to exercise `nturl2path`, as it's no longer
covered by `test_urllib`.
* Make musl test skips smarter (fixes Alpine errors)
A relatively small number of tests fail when the underlying c library is
provided by musl. This was originally reported in bpo-46390 by
Christian Heimes. Among other changes, these tests were marked for
skipping in gh-31947/ef1327e3 as part of bpo-40280 (emscripten support),
but the skips were conditioned on the *platform* being emscripten (or
wasi, skips for which ere added in 9b50585e02).
In gh-131071 Victor Stinner added a linked_to_musl function to enable
skipping a test in test_math that fails under musl, like it does on a
number of other platforms. This check can successfully detect that
python is running under musl on Alpine, which was the original problem
report in bpo-46390.
This PR replaces Victor's solution with an enhancement to
platform.libc_ver that does the check more cheaply, and also gets the
version number. The latter is important because the math test being
skipped is due to a bug in musl that has been fixed, but as of this
checkin date has not yet been released. When it is, the test skip can
be fixed to check for the minimum needed version.
The enhanced version of linked_to_musl is also used to do the skips of
the other tests that generically fail under musl, as opposed to
emscripten or wasi only failures. This will allow these tests to be
skipped automatically on Alpine.
This PR does *not* enhance libc_ver to support emscripten and wasi, as
I'm not familiar with those platforms; instead it returns a version
triple of (0, 0, 0) for those platforms. This means the musl tests will
be skipped regardless of musl version, so ideally someone will add
support to libc_ver for these platforms.
* Platform tests and bug fixes.
In adding tests for the new platform code I found a bug in the old code:
if a valid version is passed for version and it is greater than the
version found for an so *and* there is no glibc version, then the
version from the argument was returned. The code changes here fix
that.
* Add support docs, including for some preexisting is_xxx's.
* Add news item about libc_ver enhancement.
* Prettify platform re expression using re.VERBOSE.
Closes#130914: Make graphlib.TopologicalSorter.prepare() idempotent
Relax the rules so that `.prepare()` can be called multiple times, provided that no work has been passed out by `.get_ready()` yet.
Email generators using email.policy.default may convert an RFC 2047
encoded-word to unencoded form during header refolding. In a structured
header, this could allow 'specials' chars outside a quoted-string,
leading to invalid address headers and enabling spoofing. This change
ensures a parsed encoded-word that contains specials is kept as an
encoded-word while the header is refolded.
[Better fix from @bitdancer.]
---------
Co-authored-by: R David Murray <rdmurray@bitdance.com>
Co-authored-by: Petr Viktorin <encukou@gmail.com>
The pure Python implementation of `warnings.warn_explicit` constructs a `WarningMessage`
with an incorrect source (it incorrectly sets the WarningMessage's line to the given `source`).
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
In the private pathlib ABCs, replace `_WritablePath._write_info()` with
`_WritablePath._copy_from()`. This provides the target path object with
more control over the copying process, including support for querying and
setting metadata *before* the path is created.
Adjust `_ReadablePath.copy()` so that it forwards its keyword arguments to
`_WritablePath._copy_from()` of the target path object. This allows us to
remove the unimplemented *preserve_metadata* argument in the ABC method,
making it a `Path` exclusive.
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: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
Co-authored-by: Victor Stinner <vstinner@python.org>
Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com>
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>