Skip to content

Commit 354cdfa

Browse files
authored
Merge branch 'main' into guess-mimetype-deprecate-paths
2 parents 48aabd7 + cb9d78f commit 354cdfa

39 files changed

Lines changed: 858 additions & 232 deletions

‎Doc/c-api/stable.rst‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,8 @@ versions of Python, without recompilation.
6464

6565
For simplicity, this document talks about *extensions*, but Stable ABI
6666
works the same way for all uses of the API – for example, embedding Python.
67+
When embedding Python on Linux, see :ref:`embedding-python-versions`
68+
for how to link the application and for limitations.
6769

6870
There are two Stable ABIs:
6971

‎Doc/extending/embedding.rst‎

Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -356,3 +356,178 @@ combine together. For example:
356356
357357
358358
.. XXX similar documentation for Windows missing
359+
360+
361+
.. _embedding-python-versions:
362+
363+
Linking for one or several Python versions on Linux
364+
===================================================
365+
366+
The flags obtained from ``pythonX.Y-config --ldflags --embed`` link the
367+
application against one minor version of Python.
368+
If that Python was built as a shared library, the executable records a
369+
dependency on the versioned library, such as :file:`libpython3.12.so.1.0`,
370+
and expected that specific minor version at runtime.
371+
This is the recommended setup for most host (embedding) applications.
372+
Build the application for each Python version that it supports,
373+
or distribute it together with the Python that it was built with.
374+
375+
Using the :ref:`Limited API <limited-c-api>` does not change this.
376+
Defining :c:macro:`Py_LIMITED_API` restricts your source code to API that is
377+
compatible across minor versions, but the library dependency is recorded when
378+
linking, so the executable still requires :file:`libpython3.12.so.1.0`.
379+
380+
A binary that needs to run with several minor Python versions must use only
381+
the Limited API and must *also* avoid the versioned dependency.
382+
383+
.. warning::
384+
385+
Host applications that use the :ref:`Limited API <limited-c-api>`
386+
must be aware of the following limitations:
387+
388+
* It can only initialize Python with :c:func:`Py_Initialize` or
389+
:c:func:`Py_InitializeEx`, which set Python up much like the
390+
:program:`python` command does.
391+
They honor :envvar:`PYTHONHOME` and :envvar:`PYTHONPATH`, add the
392+
:data:`user site-packages directory <site.USER_SITE>` to
393+
:data:`sys.path`, and terminate the process if initialization fails.
394+
They set :data:`sys.executable` to the :program:`python3` program found
395+
on :envvar:`!PATH`, which can belong to a different Python installation
396+
than the library that was loaded.
397+
The functions that accept an
398+
:ref:`isolated configuration <init-isolated-conf>`,
399+
:c:func:`Py_InitializeFromConfig` and
400+
:c:func:`Py_InitializeFromInitConfig`, are not part of the Limited API.
401+
* The Python that gets loaded is only known at run-time.
402+
Checking that it is suitable is up to the application.
403+
An incompatible Python, such as a too-old or too-new version,
404+
is not rejected automatically.
405+
* The Stable ABI keeps functions available in later versions, but it does
406+
not guarantee identical behavior.
407+
The default configuration and the way :data:`sys.path` is computed can
408+
change between Python versions, and between installations of the same
409+
version.
410+
Test the application with every Python version and installation that it
411+
is meant to support.
412+
See also :ref:`limited-api-caveats`.
413+
414+
A Python built with :option:`--enable-shared` and without
415+
:option:`--with-pydebug` installs :file:`libpython3.so` next to the versioned
416+
library.
417+
When the dynamic loader loads this library, it also loads the versioned
418+
library that it was built with, and symbols looked up through
419+
:file:`libpython3.so` are found in the versioned library.
420+
An application can therefore load :file:`libpython3.so` with
421+
:manpage:`dlopen(3)` and look up each function that it uses with
422+
:manpage:`dlsym(3)`.
423+
424+
This only works at run time.
425+
When linking an executable, the linker does not use the dependencies of a
426+
library to resolve symbols, and :file:`libpython3.so` defines no Python
427+
symbols of its own, so linking with ``-lpython3`` fails with
428+
``undefined reference`` errors.
429+
430+
For example, with Python 3.12 as the oldest supported version::
431+
432+
#define Py_LIMITED_API 0x030c0000 /* Limited API 3.12 */
433+
#include <Python.h>
434+
#include <dlfcn.h>
435+
#include <stdio.h>
436+
437+
/* The API this application uses, declared as in Python.h.
438+
Everything is reached through these pointers. */
439+
static struct {
440+
const unsigned long *Version;
441+
const char *(*GetVersion)(void);
442+
void (*InitializeEx)(int);
443+
int (*FinalizeEx)(void);
444+
} py;
445+
446+
#define LOAD(lib, pointer, name) \
447+
((*(void **)&(pointer) = dlsym(lib, name)) != NULL)
448+
449+
int
450+
main(int argc, char *argv[])
451+
{
452+
/* For brevity, the path comes from the command line. A real
453+
application reads it from its own configuration. */
454+
if (argc != 2 || argv[1][0] != '/') {
455+
fprintf(stderr, "usage: %s /absolute/path/to/libpython3.so\n",
456+
argv[0]);
457+
return 2;
458+
}
459+
/* RTLD_GLOBAL is required: it lets the extension modules that
460+
Python imports find Python's symbols. */
461+
void *lib = dlopen(argv[1], RTLD_NOW | RTLD_GLOBAL);
462+
if (lib == NULL) {
463+
fprintf(stderr, "Python is not available: %s\n", dlerror());
464+
return 1;
465+
}
466+
if (!LOAD(lib, py.Version, "Py_Version")
467+
|| !LOAD(lib, py.GetVersion, "Py_GetVersion")
468+
|| !LOAD(lib, py.InitializeEx, "Py_InitializeEx")
469+
|| !LOAD(lib, py.FinalizeEx, "Py_FinalizeEx"))
470+
{
471+
fprintf(stderr, "Unsupported Python: %s\n", dlerror());
472+
return 1;
473+
}
474+
if (*py.Version < Py_LIMITED_API) {
475+
fprintf(stderr, "Python %s is older than 3.12\n", py.GetVersion());
476+
return 1;
477+
}
478+
479+
py.InitializeEx(0);
480+
printf("Loaded Python %s\n", py.GetVersion());
481+
return py.FinalizeEx() < 0 ? 120 : 0;
482+
}
483+
484+
Compile the program with Python's headers, but without the output of
485+
``--ldflags``:
486+
487+
.. code-block:: shell-session
488+
489+
$ gcc $(/opt/bin/python3.12-config --includes) -o myapp myapp.c
490+
$ ./myapp /usr/local/lib/libpython3.so
491+
Loaded Python 3.14.10 (main, Nov 5 2026, 09:47:10) [GCC 14.2.0]
492+
493+
No Python library is passed to the linker, so the executable does not depend
494+
on one.
495+
You can check this with ``readelf``:
496+
497+
.. code-block:: shell-session
498+
499+
$ readelf -d myapp | grep NEEDED
500+
0x0000000000000001 (NEEDED) Shared library: [libc.so.6]
501+
502+
For the same reason, Python functions can only be called through such
503+
pointers.
504+
This includes the functions that macros in :file:`Python.h` expand to:
505+
for example, call :c:func:`Py_DecRef` through a pointer instead of using
506+
:c:func:`Py_DECREF`.
507+
508+
* The path passed to ``dlopen()`` selects the code that runs in your process.
509+
It should come from a trusted source and name a file that only trusted
510+
users can replace.
511+
* Use an absolute path.
512+
The dynamic loader looks for a name without a slash in its usual search
513+
path, such as :envvar:`!LD_LIBRARY_PATH` and the system library directories.
514+
It looks for the versioned library that :file:`libpython3.so` depends on in
515+
the same way, and not next to :file:`libpython3.so`.
516+
To choose the exact file, pass the absolute path of the versioned library
517+
to ``dlopen()`` instead.
518+
* ``RTLD_GLOBAL`` is required.
519+
Extension modules are generally not linked against a Python library,
520+
so Python can only import them if its symbols are visible globally.
521+
522+
.. rubric:: Unsupported workaround: renaming the dependency after linking
523+
524+
Some applications are instead linked against a versioned library as described
525+
:ref:`above <compiling>`, and the dependency recorded in the executable is
526+
then renamed to :file:`libpython3.so`, for example with ``patchelf``.
527+
528+
.. warning::
529+
530+
Renaming the dependency this way is unsupported.
531+
Nothing checks that such an executable only uses the Stable ABI, and it
532+
can contain copies of Python data, such as ``PyLong_Type``, whose size
533+
differs between Python versions.

‎Doc/library/copyreg.rst‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,30 @@ Such constructors may be factory functions or class instances.
3939
object or subclass of :class:`pickle.Pickler` can also be used for
4040
declaring reduction functions.
4141

42+
43+
.. class:: Proxy(obj)
44+
45+
A wrapper for an object which is pickled weakly.
46+
Reduction functions can use it to pickle objects
47+
to which the reconstructed object only holds weak references.
48+
For example, a weak reference is reduced to
49+
``(weakref.ref, (Proxy(referent),))``.
50+
51+
A proxy is pickled as the wrapped object *obj*,
52+
which is unpickled in its place.
53+
*obj* must also be strongly referenced elsewhere in the same pickle;
54+
otherwise pickling raises :exc:`pickle.PicklingError`.
55+
56+
:func:`copy.copy` of a proxy returns *obj*,
57+
and :func:`copy.deepcopy` returns the deep copy of *obj*.
58+
59+
.. attribute:: obj
60+
61+
The wrapped object.
62+
63+
.. versionadded:: next
64+
65+
4266
Example
4367
-------
4468

‎Doc/library/pickle.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -924,6 +924,7 @@ If both the :attr:`~Pickler.dispatch_table` and
924924
exact instances of :class:`int`, :class:`float`, :class:`bytes`,
925925
:class:`str`, :class:`dict`, :class:`set`, :class:`frozenset`, :class:`list`
926926
and :class:`tuple`.
927+
It is never called for :class:`copyreg.Proxy` objects.
927928

928929
Here is a simple example where we allow pickling and reconstructing
929930
a given class::

‎Doc/library/statistics.rst‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,9 +47,9 @@ functions::
4747

4848
>>> data = [20.7, float('NaN'),19.2, 18.3, float('NaN'), 14.4]
4949
>>> sorted(data) # This has surprising behavior
50-
[20.7, nan, 14.4, 18.3, 19.2, nan]
50+
[18.3, nan, 14.4, 20.7, nan, 19.2]
5151
>>> median(data) # This result is unexpected
52-
16.35
52+
17.55
5353

5454
>>> sum(map(isnan, data)) # Number of missing values
5555
2

‎Doc/library/weakref.rst‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -276,8 +276,10 @@ These have the same issues as the :meth:`WeakKeyDictionary.keyrefs` method.
276276

277277
A :class:`!WeakSet` can be pickled if the elements are strongly
278278
referenced elsewhere in the same pickle (see :class:`ref`).
279-
A copy or a deep copy shares the elements with the original;
280-
user-defined attributes are copied or deep-copied.
279+
A shallow copy contains the same elements as the original.
280+
A deep copy refers to the deep copies of the elements,
281+
so they must be deep-copied together with it;
282+
its user-defined attributes are deep-copied.
281283

282284
.. versionchanged:: 3.16
283285
:class:`!WeakSet` can now be pickled and copied.
@@ -314,7 +316,9 @@ These have the same issues as the :meth:`WeakKeyDictionary.keyrefs` method.
314316
A :class:`!WeakMethod` can be copied,
315317
and pickled if the object the method is bound to is strongly referenced
316318
elsewhere in the same pickle (see :class:`ref`).
317-
A copy or a deep copy is an equal weak method to the same object.
319+
A copy is an equal weak method bound to the same object.
320+
A deep copy is bound to the deep copy of the object,
321+
so it must be deep-copied together with it.
318322

319323
.. versionadded:: 3.4
320324

‎Doc/reference/expressions.rst‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2426,6 +2426,15 @@ The expression ``x if C else y`` first evaluates the condition, *C* rather than
24262426
If *C* is true, *x* is evaluated and its value is returned; otherwise, *y* is
24272427
evaluated and its value is returned.
24282428

2429+
Conditional expressions group from right to left, so
2430+
``a if b else c if d else e`` means ``a if b else (c if d else e)``::
2431+
2432+
>>> n = 2
2433+
>>> print('positive' if n > 0
2434+
... else 'negative' if n < 0
2435+
... else 'zero')
2436+
positive
2437+
24292438
See :pep:`308` for more details about conditional expressions.
24302439

24312440

‎Doc/whatsnew/3.16.rst‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,17 @@ copy
249249
:gh:`155044`, :gh:`155041`, :gh:`155040`, and :gh:`155033`.)
250250

251251

252+
copyreg
253+
-------
254+
255+
* Add :class:`copyreg.Proxy`, a wrapper that is pickled as the wrapped object.
256+
Reduction functions can use it to pickle objects
257+
to which the reconstructed object only holds weak references.
258+
The wrapped object must be strongly referenced elsewhere in the same pickle;
259+
otherwise pickling raises :exc:`pickle.PicklingError`.
260+
(Contributed by Serhiy Storchaka in :gh:`74876`.)
261+
262+
252263
csv
253264
---
254265

‎Lib/_weakrefset.py‎

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
# by abc.py to load everything else at startup.
44

55
from _weakref import ref
6+
from copyreg import Proxy
67
from types import GenericAlias
78

89
__all__ = ['WeakSet']
@@ -44,14 +45,13 @@ def __contains__(self, item):
4445
return wr in self.data
4546

4647
def __reduce__(self):
47-
# Pickle the elements as weak references; data and _remove are
48-
# rebuilt by the reconstructor. Copying shares the elements.
48+
# The elements must be strongly referenced elsewhere in the pickle.
49+
# data and _remove are rebuilt by the constructor.
4950
dict, slots = self.__getstate__()
5051
for name in ('data', '_remove'):
5152
slots.pop(name, None)
5253
state = (dict, slots) if dict or slots else None
53-
return (_restore_weakset, (self.__class__, [ref(item) for item in self]),
54-
state)
54+
return (self.__class__, ([Proxy(item) for item in self],), state)
5555

5656
def add(self, item):
5757
self.data.add(ref(item, self._remove))
@@ -62,6 +62,8 @@ def clear(self):
6262
def copy(self):
6363
return self.__class__(self)
6464

65+
__copy__ = copy
66+
6567
def pop(self):
6668
while True:
6769
try:
@@ -156,10 +158,3 @@ def __repr__(self):
156158
return repr(self.data)
157159

158160
__class_getitem__ = classmethod(GenericAlias)
159-
160-
161-
def _restore_weakset(cls, refs):
162-
self = cls.__new__(cls)
163-
WeakSet.__init__(self)
164-
self.update(item for r in refs for item in [r()] if item is not None)
165-
return self

‎Lib/copy.py‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ class instances).
5151

5252
import types
5353
import weakref
54-
from copyreg import dispatch_table
54+
from copyreg import dispatch_table, Proxy
5555

5656
class Error(Exception):
5757
pass
@@ -71,6 +71,8 @@ def copy(x):
7171
return x
7272
if cls in _copy_builtin_containers:
7373
return cls.copy(x)
74+
if cls is Proxy:
75+
return x.obj
7476

7577

7678
if issubclass(cls, type):
@@ -221,6 +223,10 @@ def _deepcopy_method(x, memo): # Copy instance methods
221223
return type(x)(x.__func__, deepcopy(x.__self__, memo))
222224
d[types.MethodType] = _deepcopy_method
223225

226+
def _deepcopy_proxy(x, memo, deepcopy=deepcopy):
227+
return deepcopy(x.obj, memo)
228+
d[Proxy] = _deepcopy_proxy
229+
224230
del d
225231

226232
def _keep_alive(x, memo):

0 commit comments

Comments
 (0)