LoLBench / cpython_18 /instruction.md
lolbench26's picture
Publish LoLBench Harbor tasks from artifact branch (part 2)
a4edccc verified
|
Raw History Blame Contribute Delete
134 kB

You are working in /workspace/cpython, a source tree checked out at the base commit for this task. Implement the requested behavior in the source tree, then run:

lolbench-submit

Do not stop after editing files, running tests, or describing the solution. The task is complete only when lolbench-submit has created /logs/artifacts/solution.patch. If that file does not exist, continue working and run lolbench-submit again.

That command writes your implementation diff to /logs/artifacts/solution.patch, which is the artifact the Harbor verifier will grade. Before running lolbench-submit, clean or revert any test files you created or modified; test files must not be included in the final solution.patch.

This environment has no outbound internet access — curl/wget, git fetch/clone, package installs, and web fetch/search will all fail. Implement the requirements using only the code already in the workspace and your own knowledge; do not attempt to fetch or search external resources.

Now please implement the following requirements in the source tree:


PEP 820: PySlot: Unified slot system for the C API

Abstract

Replace type and module slots with a new structure: a tagged anonymous union with flags. This improves type safety and allows adding new slots in a more forward-compatible way.

API added in 3.15 (PyModule_FromSlotsAndSpec and the new extension export hook) will be changed to use the new slots.

The existing slot structures and related API is soft-deprecated. (That is: they will continue to work without warnings, and it’ll be fully documented and supported, but we plan to not add any new features to it.)

Background

The C API in Python 3.14 contains two extendable structs used to provide information when creating a new object: PyType_Spec and PyModuleDef.

Each has a family of C API functions that create a Python object from it. (Each family works as a single function, with optional arguments that got added over time.) These are:

  • PyType_From* functions, like PyType_FromMetaclass, for PyType_Spec;
  • PyModule_FromDef* functions, like PyModule_FromDefAndSpec, for PyModuleDef.

Separating "input" structures from runtime objects allows the internal structure of the object to stay opaque (in both the API and the ABI), allowing future CPython versions (or even alternative implementations) to change the details.

Both structures contain a slots field, essentially an array of tagged unions (void pointers taged with an int ID). This allows for future expansion.

In PEP 793, new module creation API was added. Instead of the PyModuleDef structure, it uses only an array of slots. To replace the existing members of PyModuleDef, it adds corresponding slot IDs -- for example, the module name is specified in a Py_mod_name slot, rather than in PyModuleDef.m_name. That PEP notes:

The PyModuleDef_Slot struct does have some downsides compared to fixed fields. We believe these are fixable, but leave that out of scope of this PEP.

This proposal addresses the downsides.

Motivation

The main shortcomings of the existing PyModuleDef_Slot and PyType_Slot are:

Type safety : void * is used for data pointers, function pointers and small integers, requiring casting that works in practice on all relevant architectures, but is technically undefined or implementation-defined behaviour in C.

For example: `Py_tp_doc` marks a string; `Py_mod_gil`
a small integer, and `Py_tp_repr` a function; all must
be cast to `void*`.

Limited forward compatibility : If an extension provides a slot ID that's unknown to the current interpreter, type/module creation will fail. This makes it cumbersome to use "optional" features – ones that should only take effect if the interpreter supports them. The recently added slots Py_mod_gil and Py_mod_multiple_interpreters are good examples.

One workaround is to check the Python version, and omit slots
that predate the current interpreter.
This is cumbersome for users.
It also constraints possible non-CPython implementations of the C API,
preventing them from "cherry-picking" features introduced in newer CPython
versions.

Endorsements

This PEP is unusual in that it doesn't immediately help end users -- it needs to be in place well before it starts being helpful. In the words of a Cython maintainer, Da Woods:

I suspect Cython wouldn’t immediately use it (at least for classes… obviously if it goes into PEP 793 then we would for that). Just because it’s mostly targeted at future improvements rather than an immediate new feature. It looks usable though.

Instead, support comes from core devs who'll need change the C API, and want do so in backwards-compatible ways:

  • Mark Shannon:

    This seems like a worthwhile improvement. Count me as a +1

  • Victor Stinner:

    I changed my mind and I’m now a supporter of PEP 820 :) It took me a while but I now see the PEP 820 advantages: it enhances the backward compatibility and the stable ABI.

Example

This proposal adds API to create classes and modules from arrays of slots, which can be specified as C literals using macros, like this:

static PySlot myClass_slots[] = {
   PySlot_STATIC(tp_name, "mymod.MyClass"),
   PySlot_SIZE(tp_extra_basicsize, sizeof(struct myClass)),
   PySlot_FUNC(tp_repr, myClass_repr),
   PySlot_INT64(tp_flags, Py_TPFLAGS_DEFAULT | Py_TPFLAGS_MANAGED_DICT),
   PySlot_END,
}

// ...

PyObject *MyClass = PyType_FromSlots(myClass_slots);

The macros simplify hand-written literals. For more complex use cases, like compatibility between several Python versions, or templated/auto-generated slot arrays, as well as for non-C users of the C API, the slot struct definitions can be written out. For example, if the nb_matrix_multiply slot (PEP 465) was added in the near future (say, CPython 3.17) rather than in 3.5, users could add it with an "OPTIONAL" flag, making their class support the @ operator only on CPython versions with that operator:

static PySlot myClass_slots[] = {
   ...
   {   // skipped if not supported
       .sl_id=Py_nb_matrix_multiply,
       .sl_flags=PySlot_OPTIONAL,
       .sl_func=myClass_matmul,
   },
   PySlot_END,
}

Rationale

Here we explain the design decisions in this proposal.

Some of the rationale is repeated from PEP 793, which replaced the PyModuleDef struct with an array of slots.

Using slots

The main alternative to slots is using a versioned struct for input.

There are two variants of such a design:

  • A large struct with fields for all info. As we can see with PyTypeObject, most of such a struct tends to be NULLs in practice. As more fields become obsolete, either the wastage grows, or we introduce new struct layouts (while keeping compatibility with the old ones for a while).

  • A small struct with only the info necessary for initial creation, with other info added afterwards (with dedicated function calls, or Python-level setattr). This design:

    • makes it cumbersome to add/obsolete/adjust the required info (for example, in PEP 697 I gave meaning to negative values of an existing field; adding a new field would be cleaner in similar situations);
    • increases the number of API calls between an extension and the interpreter.

    We believe that “batch” API for type/module creation makes sense, even if it partially duplicates an API to modify “live” objects.

Using slots only

The classes PyType_Spec and PyModuleDef have explicit fields in addition to a slots array. These include:

  • Required information, such as the class name (PyType_Spec.name). This proposal adds a slot ID for the name, and makes it required.
  • Non-pointers (basicsize, flags). Originally, slots were intended to only contain function pointers; they now contain data pointers as well as integers or flags. This proposal uses a union to handle types cleanly.
  • Items added before the slots mechanism. The PyModuleDef.m_slots itself was repurposed from m_reload which was always NULL; the optional m_traverse or m_methods members predate it.

We can do without these fields, and have only an array of slots. A wrapper class around the array would complicate the design. If fields in such a class ever become obsolete, they are hard to remove or repurpose.

Nested slot tables

In this proposal, the array of slots can reference another array of slots, which is treated as if it was merged into its “parent”, recursively. This complicates slot handling inside the interpreter, but allows:

  • Mixing dynamically allocated (or stack-allocated) slots with static ones. This solves the issue that lead to the PyType_From* family of functions expanding with values that typically can't be static. For example, the module argument to PyType_FromModuleAndSpec should be a heap-allocated module object.
  • Sharing a subset of the slots to implement functionality common to several classes/modules.
  • Easily including some slots conditionally, e.g. based on the Python version.

Nested “legacy” slot tables

Similarly to nested arrays of PyType_Slot, we also propose supporting arrays of “legacy” slots (PyType_Slot and PyModuleDef_Slot) in the “new” slots, and vice versa.

This way, users can reuse code they already have written without rewriting/reformatting, and only use the “new” slots if they need any new features.

Fixed-width integers

This proposal uses fixed-width integers (uint16_t) for slot IDs and flags. With the C int type, using more than 16 bits would not be portable, but it would silently work on common platforms. Using int but avoiding values over UINT16_MAX wastes 16 bits on common platforms.

Memory layout

On common 64-bit platforms, we can keep the size of the new struct the same as the existing PyType_Slot and PyModuleDef_Slot. (The existing struct waste 6 out of 16 bytes due to int portability and padding; this proposal puts some of those bits to use for new features.) On 32-bit platforms, this proposal calls for the same layout as on 64-bit, doubling the size compared to the existing structs (from 8 bytes to 16). For “configuration” data that's usually static, it should be OK.

The proposal does not use bit-fields and enums, whose memory representation is compiler-dependent, causing issues when using the API from languages other than C.

The structure is laid out assuming that a type's alignment matches its size.

Single ID space

Currently, the numeric values of module and type slots overlap:

  • Py_bf_getbuffer == Py_mod_create == 1
  • Py_bf_releasebuffer == Py_mod_exec == 2
  • Py_mp_ass_subscript == Py_mod_multiple_interpreters == 3
  • Py_mp_length == Py_mod_gil == 4
  • and similar for module slots added in CPython 3.15

This proposal use a single sequence for both, so future slots avoid this overlap. This is to:

  • Avoid accidentally using type slots for modules, and vice versa
  • Allow external libraries or checkers to determine a slot's meaning (and type) based on the ID.

The 4 existing overlaps means we don't reach these goals right now, but we can gradually migrate to new numeric IDs in a way that's transparent to the user.

The main disadvantage is that any internal lookup tables will be either bigger (if we use separate ones for types & modules, so they'll contain blanks), or harder to manage (if they're merged).

Deprecation warnings

Multiple slots are documented to not allow NULL values, but CPython allows NULL for backwards compatibility. Similarly, multiple slot IDs should not appear more than once in a single array, but CPython allows such duplicates.

This is a maintenance issue, as CPython should preserve its undocumented (and often untested) behaviour in these cases as the implementation is changed.

It also prevents API extensions. For example, instead of adding the Py_TPFLAGS_DISALLOW_INSTANTIATION flag in 3.10, we could have allowed settning the Py_tp_new slot to NULL for the same effect.

To allow changing the edge case behaviour in the (far) future, and to allow freedom for possible alternative implementations of the C API, we'll start issuing runtime deprecation warnings in these cases. To avoid flooding users with warnings for things that are outside of their control, we'll only show deprecation warnings when the new API is used.

Specification

A new PySlot structure will be defined as follows:

typedef struct PySlot {
    uint16_t sl_id;
    uint16_t sl_flags;
    union {
        uint32_t _sl_reserved;  // must be 0
    };
    union {
        void *sl_ptr;
        void (*sl_func)(void);
        Py_ssize_t sl_size;
        int64_t sl_int64;
        uint64_t sl_uint64;
    };
} PySlot;
  • sl_id: A slot number, identifying what the slot does.
  • sl_flags: Flags, defined below.
  • 32 bits reserved for future extensions (expected to be enabled by future flags).
  • An union with the data, whose type depends on the slot.

New API

The following function will be added. It will create the corresponding Python type object from the given array of slots:

PyObject *PyType_FromSlots(const PySlot *slots);

With this function, the Py_tp_token slot may not be set to Py_TP_USE_SPEC (i.e. NULL).

Changed API

The PyModule_FromSlotsAndSpec function (added in CPython 3.15 in PEP 793) will be changed to take the new slot structure:

PyObject *PyModule_FromSlotsAndSpec(const PySlot *slots, PyObject *spec)

The extension module export hook added in PEP 793 (PyModExport_{}) will be changed to return the new slot structure. The PyMODEXPORT_FUNC macro will be updated accordingly.

General slot semantics

When slots are passed to a function that applies them, the function will not modify the slot array, nor any data it points to (recursively).

After the function is done, the user is allowed to modify or deallocate the array, and any data it points to (recursively), unless it's explicitly marked as "static" (see PySlot_STATIC below). This means the interpreter typically needs to make a copy of all data in the struct, including char * text.

Flags

sl_flags may set the following bits. Unassigned bits must be set to zero.

  • PySlot_OPTIONAL: If the slot ID is unknown, the interpreter should ignore the slot entirely. (For example, if nb_matrix_multiply was being added to CPython now, your type could use this.)

  • PySlot_STATIC: All data the slot points to is statically allocated and constant. Thus, the interpreter does not need to copy the information. This flag is implied for function pointers.

    The flag applies even to data the slot points to "indirectly", except for nested slots -- see pep820-nested-tables below -- which can have their own PySlot_STATIC flag. For example, if applied to a Py_tp_members slot that points to an array of PyMemberDef structures, then the entire array, as well as the name and doc strings in its elements, must be static and constant.

  • PySlot_INTPTR: The data is stored in sl_ptr, and must be cast to the appropriate type.

    This flag simplifies porting from the existing PyType_Slot and PyModuleDef_Slot, where all slots work this way.

Convenience macros

The following macros will be added to the API to simplify slot definition:

#define PySlot_DATA(NAME, VALUE) \
   {.sl_id=NAME, .sl_ptr=(void*)(VALUE)}

#define PySlot_FUNC(NAME, VALUE) \
   {.sl_id=NAME, .sl_func=(VALUE)}

#define PySlot_SIZE(NAME, VALUE) \
   {.sl_id=NAME, .sl_size=(VALUE)}

#define PySlot_INT64(NAME, VALUE) \
   {.sl_id=NAME, .sl_int64=(VALUE)}

#define PySlot_UINT64(NAME, VALUE) \
   {.sl_id=NAME, .sl_uint64=(VALUE)}

#define PySlot_STATIC_DATA(NAME, VALUE) \
   {.sl_id=NAME, .sl_flags=PySlot_STATIC, .sl_ptr=(VALUE)}

#define PySlot_END {0}

We'll also add two more macros that avoid named initializers, for use in C++11-compatibile code. Note that these cast the value to void*, so they do not improve type safety over existing slots:

#define PySlot_PTR(NAME, VALUE) \
   {NAME, PySlot_INTPTR, {0}, {(void*)(VALUE)}}

#define PySlot_PTR_STATIC(NAME, VALUE) \
   {NAME, PySlot_INTPTR|Py_SLOT_STATIC, {0}, {(void*)(VALUE)}}

Nested slot tables

A new slot, Py_slot_subslots, will be added to allow nesting slot tables. Its value (sl_ptr) should point to an array of PySlot structures, which will be treated as if they were part of the current slot array. sl_ptr can be NULL to indicate that there are no slots.

Two more slots will allow similar nesting for existing slot structures:

  • Py_tp_slots for an array of PyType_Slot
  • Py_mod_slots for an array of PyModuleDef_Slot

Each PyType_Slot in the array will be converted to (PySlot){.sl_id=slot, .sl_flags=PySlot_INTPTR, .sl_ptr=func}, and similar with PyModuleDef_Slot.

In the initial implementation, nesting depth will be limited to 5 levels. This restriction may be lifted in the future.

New slot IDs

The following new slot IDs, usable for both type and module definitions, will be added:

  • Py_slot_end (defined as 0): Marks the end of a slots array.

    • The PySlot_INTPTR and PySlot_STATIC flags are ignored.
    • The PySlot_OPTIONAL flags is not allowed with Py_slot_end.
  • Py_slot_subslots, Py_tp_slots, Py_mod_slots: see pep820-nested-tables above

  • Py_slot_invalid (defined as UINT16_MAX, i.e. -1): treated as an unknown slot ID.

The following new slot IDs will be added to cover existing members of PyModuleDef:

  • Py_tp_name (mandatory for type creation)
  • Py_tp_basicsize (of type Py_ssize_t)
  • Py_tp_extra_basicsize (equivalent to setting PyType_Spec.basicsize to -extra_basicsize)
  • Py_tp_itemsize
  • Py_tp_flags

The following new slot IDs will be added to cover arguments of PyType_FromMetaclass:

  • Py_tp_metaclass (used to set ob_type after metaclass calculation)
  • Py_tp_module

Note that Py_tp_base and Py_tp_bases already exist. The interpreter will treat them identically: either can specify a class object or a tuple of them. Py_tp_base will be soft-deprecated in favour of Py_tp_bases. Specifying both in a single definition will be deprecated (currently, Py_tp_bases overrides Py_tp_base).

None of the new slots will be usable with PyType_GetSlot. (This limitation may be lifted in the future, with C API WG approval.)

Of the new slots, only Py_slot_end, Py_slot_subslots, Py_tp_slots, Py_mod_slots will be allowed in PyType_Spec and/or PyModuleDef.

Slot renumbering

New slots IDs will have unique numeric values (that is, Py_slot_*, Py_tp_* and Py_mod_* won't share IDs).

Slots numbered 1 through 4 (Py_bf_getbuffer...Py_mp_length and Py_mod_create...Py_mod_gil) will be redefined as new (larger) numbers. The old numbers will remain as aliases, and will be used when compiling for Stable ABI versions below 3.15.

Slots for members of PyModuleDef, which were added in PEP 793, will be renumbered so that they have unique IDs:

  • Py_mod_name
  • Py_mod_doc
  • Py_mod_state_size
  • Py_mod_methods
  • Py_mod_state_traverse
  • Py_mod_state_clear
  • Py_mod_state_free

Soft deprecation

These existing functions will be soft-deprecated:

  • PyType_FromSpec
  • PyType_FromSpecWithBases
  • PyType_FromModuleAndSpec
  • PyType_FromMetaclass
  • PyModule_FromDefAndSpec
  • PyModule_FromDefAndSpec2
  • PyModule_ExecDef

(As a reminder: soft-deprecated API is not scheduled for removal, does not raise warnings, and remains documented and tested. However, no new functionality will be added to it.)

Arrays of PyType_Slot or PyModuleDef_Slot, which are accepted by these functions, can contain any slots, including "new" ones defined in this PEP. This includes nested "new-style" slots (Py_slot_subslots).

Deprecation warnings

Functions that take PySlot arrays (but not functions that take the older PyType_Slot or PyModuleDef_Slot arrays) will emit runtime deprecation warnings for the following cases, for slots where the case is currently disallowed in documentation but allowed by the runtime:

  • setting a slot value to NULL:

    • all type slots except Py_tp_doc
    • Py_mod_create
    • Py_mod_exec
  • repeating a slot ID in a single slots array (including sub-slot arrays added in this PEP):

    • all type slots, except slots where this is already a runtime error (Py_tp_doc, Py_tp_members)
    • Py_mod_create
    • Py_mod_abi

Backwards Compatibility

This PEP proposes to change API that was already released in alpha versions of Python 3.15. This will inconvenience early adopters of that API, but -- as long as the PEP is accepted and implemented before the first bety -- this change is within the letter and spirit of our backwards compatibility policy.

Renumbering of slots is done in a backwards-compatible way. Old values continue to be accepted, and are used when compiling for earlier Stable ABI.

Some cases that are documented as illegal will begin emitting deprecation warnings (see pep820-hard-deprecations).

Otherwise, this PEP only adds and soft-deprecates APIs, which is backwards compatible.

Security Implications

None known

How to Teach This

Adjust the "Extending and Embedding" tutorial to use this.

Reference Implementation

Draft implementation is available as pull request #37 in the author's fork.

Rejected Ideas

See the pep820-rationale section for several alternative ideas.

Third-party slot ID allocation

It was suggested to allow third parties to reserve slot IDs for their own use. This would be mainly useful for alternate implementations. For example, something like GraalPy might want custom type slots (e.g. an "inherits from this Java class" slot). Similarly, at one point PyPy had an extra tp_pypy_flags in their typeobject struct.

This PEP does not specify a namespace mechanism. One can be added in the future. We're also free to reserve individual slot IDs for alternate implementations.

Note that slots are not a good way for extension modules to add extra data to types or modules, as there is no API to retrieve the slots used to create a specific object.

Avoiding anonymous unions

This PEP proposes a struct with anonymous unions, which are not yet used in CPython's documented public API.

There is no known issue with adding these, but the following notes may be relevant:

  • Anonymous unions are only supported in C since C11. But, CPython already requires the feature, and uses it for internal members of the PyObject struct.

  • Until C++20, which adds C-style designated initializers, C++ initializers only allow setting the first member of a union. However, this is an issue for named unions as well. Avoiding unions entirely would mean losing most of the type-safety improvements of this PEP.

    Note that the proposed flag PySlot_INTPTR, and the workaround macros PySlot_PTR & PySlot_PTR_STATIC, allow using this API in code that needs to be compatible with C++11 or has similar union-related limitations.

  • C++ doesn't have anonymous structs. This might surprise C programmers for whom anonymous structs/unions are a single language feature.

  • Non-C/C++ language wrappers may need to give the union a name. This is fine. (Dear reader: if you need this, please open a CPython issue about exposing a preferred name in headers and documentation.)

For a bigger picture: anonymous unions can be a helpful tool for implemeting tagged unions and for evolving public API in backwards-compatible ways. This PEP intentionally opens the door to using them more often.

Fallback slots

An earlier version of this PEP proposed a flag: PySlot_HAS_FALLBACK:

If the flagged slot's ID is unknown, the interpreter will ignore the slot. If it's known, the interpreter should ignore subsequent slots up to (and including) the first one without HAS_FALLBACK.

Effectively, consecutive slots with the HAS_FALLBACK flag, plus the first non-HAS_FALLBACK slot after them, form a "block" where the the interpreter will only consider the first slot in the block that it understands. If the entire block is to be optional, it should end with a slot with the OPTIONAL flag.

This flag may be added later, in the Python version where it's needed. (For backwards compatibility, all slots flagged HAS_FALLBACK will also need the OPTIONAL flag).

Open Issues

None yet.

Linked PEP 793 — PyModExport: A new entry point for C extension modules

Abstract

In this PEP, we propose a new entry point for C extension modules, by which one can define a module using an array of PyModuleDef_Slot structures without an enclosing PyModuleDef structure. This allows extension authors to avoid using a statically allocated PyObject, lifting the most common obstacle to making one compiled library file usable with both regular and free-threaded builds of CPython.

To make this viable, we also specify new module slot types to replace PyModuleDef's fields, and to allow adding a token similar to the Py_tp_token used for type objects.

We also add an API for defining modules from slots dynamically.

The existing API (PyInit_*) is soft-deprecated. (That is: it will continue to work without warnings, and it'll be fully documented and supported, but we plan to not add any new features to it.)

Background & Motivation

The memory layout of Python objects differs between regular and free-threading builds. So, an ABI that supports both regular and free-threading builds cannot include the current PyObject memory layout. To stay compatible with existing ABI (and API), it cannot support statically allocated Python objects.

There is one type of object that is needed in most extension modules and is allocated statically in virtually all cases: the PyModuleDef returned from the module export hooks (that is, PyInit_* functions).

Module export hooks (PyInit_* functions) can return two kinds of objects:

  1. A fully initialized module object (for so-called single-phase initialization). This was the only option in 3.4 and below. Modules created this way have surprising (but backwards-compatible) behaviour around multiple interpreters or repeated loading. (Specifically, the contents of such a module's __dict__ are shared across all instances of the module object.)

    The module returned is typically created using the PyModule_Create function, which requires a statically allocated (or at least long-lived) PyModuleDef struct.

    It is possible to bypass this using the lower-level PyModule_New* API. This avoids the need for PyModuleDef, but offers much less functionality.

  2. A PyModuleDef object containing a description of how to create a module object. This option, multi-phase initialization, was introduced in PEP 489; see its motivation for why it exists.

The interpreter cannot distinguish between these cases before the export hook is called.

The interpreter switch

Python 3.12 added a way for modules to mark whether they may be loaded in a subinterpreter: the Py_mod_multiple_interpreters slot. Setting it to the “not supported” value signals that an extension can only be loaded in the main interpreter.

Unfortunately, Python can only get this information by calling the module export hook. For single-phase modules, that creates the module object and runs arbitrary initialization code. For modules that set Py_mod_multiple_interpreters to “not supported”, this initialization needs to happen in the main interpreter.

To make this work, if a new module is loaded in a sub-interpreter, Python temporarily switches to the main interpreter, calls the export hook there, and then either switches back and redoes the import, or fails.

This unnecessary and fragile extra work highlights the underlying design issue: Python has no way to get information about an extension before the extension can, potentially, fully initialize itself.

Rationale

For avoiding the module export hook requiring a statically allocated PyObject*, two options come to mind:

  • Returning a dynamically allocated object, whose ownership is transferred to the interpreter. This stucture could be very similar to the existing PyModuleDef, since it needs to contain the same data. Unlike the existing PyModuleDef, this one would need to be reference-counted so that it both outlives “its” module and does not leak.

  • Adding a new export hook, which does not return a PyObject*.

    This was considered already for Python 3.5 in PEP 489, but rejected:

    Keeping only the PyInit hook name, even if it’s not entirely appropriate for exporting a definition, yielded a much simpler solution.

    Alas, after a decade of fixing the implications of this choice, the solution is no longer simple.

A new hook will also allow Python to avoid the second issue mentioned in Motivation -- the interpreter switch. Effectivelly, it will add a new phase to multi-phase initialization, in which Python can check whether the module is compatible.

Using slots without a wrapper struct

The existing PyModuleDef is a struct with some fixed fields and a “slots” array. Unlike slots, the fixed fields cannot be individually deprecated and replaced. This proposal does away with fixed fields and proposes using a slots array directly, without a wrapper struct.

The PyModuleDef_Slot struct does have some downsides compared to fixed fields. We believe these are fixable, but leave that out of scope of this PEP (see “Improving slots in general” in the Possible Future Directions section).

Tokens

A static PyModuleDef has another purpose besides describing how a module should be created. As a statically allocated singleton that remains attached to the module object, it allows extension authors to check whether a given Python module is “theirs”: if a module object has a known PyModuleDef, its module state will have a known memory layout.

An analogous issue was solved for types by adding Py_tp_token. This proposal adds the same mechanism to modules.

Unlike types, the import mechanism often has a pointer that's known to be suitable as a token value; in these cases it can provide a default token. Thus, module tokens do not need a variant of the inelegant Py_TP_USE_SPEC.

To help extensions that straddle Python versions, PyModuleDef addresses are used as default tokens, and where it's reasonable, they are made interchangeable with tokens.

Soft-deprecating the existing export hook

The only reason for authors of existing extensions to switch to the API proposed here is that it allows a single module for both free-threaded and non-free-threaded builds. It is important that Python allows that, but for many existing modules, it is nowhere near worth losing compatibility with 3.14 and lower versions.

It is much too early to plan deprecation of the old API.

Instead, this PEP proposes to stop adding new features to the PyInit_* scheme. After all, the perfect time for extension authors to switch is when they want to modify module initialization anyway.

Specification

The export hook

When importing an extension module, Python will now first look for an export hook like this:

 PyModuleDef_Slot *PyModExport_<NAME>(void);

where <NAME> is the name of the module. For non-ASCII names, it will instead look for PyModExportU_<NAME>, with <NAME> encoded as for existing PyInitU_* hooks (that is, punycode-encoded with hyphens replaced by underscores).

If not found, the import will continue as in previous Python versions (that is, by looking up a PyInit_* or PyInitU_* function).

If found, Python will call the hook with no arguments.

On failure, the export hook must return NULL with an exception set. This will cause the import to fail. (Python will not fall back to PyInit_* on error.)

On success, the hook must return a pointer to an array of PyModuleDef_Slot structs. Python will then create a module based on the given slots by calling functions proposed below: PyModule_FromSlotsAndSpec and PyModule_Exec. See their description for requirements on the slots array.

The returned array and all data it points to (recursively) must remain valid and constant until runtime shutdown. (We expect functions to export a static constant, or one of several constants chosen depending on, for example, Py_Version. Dynamic behaviour should generally happen in the Py_mod_create and Py_mod_exec functions.)

Dynamic creation

A new function will be added to create a module from an array of slots:

 PyObject *PyModule_FromSlotsAndSpec(const PyModuleDef_Slot *slots, PyObject *spec)

The slots argument must point to an array of PyModuleDef_Slot structures, terminated by a slot with slot=0 (typically written as {0} in C). The Py_mod_abi slot is required: it records the ABI the module was built against, so a slots array that omits Py_mod_abi raises SystemError when the module is created. Apart from that mandatory slot no particular slot is required, though slots must not be NULL, and it follows that the minimal input contains the Py_mod_abi slot together with the terminator slot.

Note: Making Py_mod_abi mandatory follows the direction of PEP 803; this PEP's implementation already enforces the requirement, raising SystemError for a slot-based module definition that leaves it out. The spec argument is a duck-typed ModuleSpec-like object, meaning that any attributes defined for importlib.machinery.ModuleSpec have matching semantics. The name attribute is required, but this limitation may be lifted in the future. The name will be used instead of the Py_mod_name slot (just like PyModule_FromDefAndSpec ignores PyModuleDef.m_name).

The slots arrays for both PyModule_FromSlotsAndSpec and the new export hook will only allow up to one Py_mod_exec slot. Arrays in PyModuleDef.m_slots may have more; this will not change. This limitation is easy to work around and multiple exec slots are rarely used .

For modules created without a PyModuleDef, the Py_mod_create function will be called with NULL for the second argument (def). (In the future, if we find a use case for passing the input slots array, a new slot with an updated signature can be added.)

Unlike the PyModExport_* hook, the slots array may be changed or destroyed after the PyModule_FromSlotsAndSpec call. (That is, Python must take a copy of all input data.) As an exception, any PyMethodDef array given by Py_mod_methods must be statically allocated (or be otherwise guaranteed to outlive the objects created from it). This limitation may be lifted in the future.

A new function, PyModule_Exec, will be added to run the exec slot(s) for a module. This acts like PyModule_ExecDef, but supports modules created using slots, and does not take an explicit def:

 int PyModule_Exec(PyObject *module)

Calling this is required to fully initialize a module. PyModule_FromSlotsAndSpec will not run it (just like PyModule_FromDefAndSpec does not call PyModule_ExecDef).

For modules created from a def, calling this is equivalent to calling PyModule_ExecDef(module, PyModule_GetDef(module)).

Tokens

Module objects will optionally store a “token”: a void* pointer similar to Py_tp_token for types.

Note: This is specialized functionality meant replace the Note: PyType_GetModuleByDef function; users that don't need Note: PyType_GetModuleByDef will most likely not need tokens either. Note: This section contains the technical specification; Note: for an example of intended usage, see exampletype_repr in the Note: Example section <pep793-example>. If specified, using a new Py_mod_token slot, the module token must:

  • outlive the module, so it's not reused for something else while the module exists; and
  • "belong" to the extension module where the module lives, so it will not clash with other extension modules.

(Typically, it should be the slots array or PyModuleDef that a module is created from, or another static constant for dynamically created modules.)

When the address of a PyModuleDef is used as a module's token, the module should behave as if it was created from that PyModuleDef. In particular, the module state must have matching layout and semantics.

Modules created using the PyModule_FromSlotsAndSpec or the PyModExport_<NAME> export hook can use a new Py_mod_token slot to set the token.

Modules created from a PyModuleDef will have the token set to that definition. An explicit Py_mod_token slot will we rejected for these. (This allows implementations to share storage for the token and def.)

For modules created via the new export hook, the token will be set to the address of the slots array by default. (This does not apply to modules created by PyModule_FromSlotsAndSpec, as that function's input might not outlive the module.)

The token will not be set for non-PyModuleType instances.

A PyModule_GetToken function will be added to get the token. Since the result may be NULL, it will be passed via a pointer; the function will return 0 on success and -1 on failure:

 int PyModule_GetToken(PyObject *, void **token_p)

A new PyType_GetModuleByToken function will be added, with a signature like the existing PyType_GetModuleByDef but a const void *token argument, and the same behaviour except matching tokens rather than only defs, and returning a strong reference.

For easier backwards compatibility, the existing PyType_GetModuleByDef will be changed to also allow a token (cast to a PyModuleDef * pointer) as the def argument. That is, PyType_GetModuleByToken and PyType_GetModuleByDef will differ only in the formal signature of the second argument and by returning a borrowed vs. strong reference. (The PyModule_GetDef function will not get a similar change, as users may access members of its result.)

New slots

For each field of the PyModuleDef struct, except ones from PyModuleDef_HEAD_INIT, a new slot ID will be provided: Py_mod_name, Py_mod_doc, Py_mod_clear, etc. Slots related to the module state rather than the module object will use a Py_mod_state_ prefix. See pep793-api-summary for a full list.

All new slots -- these and Py_tp_token discussed above -- may not be repeated in the slots array, and may not be used in a PyModuleDef.m_slots array. They may not have a NULL value (instead, the slot can be omitted entirely).

Note that currently, for modules created from a spec (that is, using PyModule_FromDefAndSpec), the PyModuleDef.m_name member is ignored and the name from the spec is used instead. All API proposed in this document creates modules from a spec, and it will ignore Py_mod_name in the same way. The slot will be optional, but extension authors are strongly encouraged to include it for the benefit of future APIs, external tooling, debugging, and introspection.

Bits & Pieces

A PyMODEXPORT_FUNC macro will be added, similar to the PyMODINIT_FUNC macro but with PyModuleDef_Slot * as the return type.

A PyModule_GetStateSize function will be added to retrieve the size set by Py_mod_state_size or PyModuleDef.m_size. Since the result may be -1 (for single-phase-init modules), it will be output via a pointer; the function will return 0 on success and -1 on failure:

 int PyModule_GetStateSize(PyObject *, Py_ssize_t *result);

Soft-deprecating the existing export hook

The PyInit_* export hook will be soft-deprecated .

New API summary

Python will load a new module export hook, with two variants:

 PyModuleDef_Slot *PyModExport_<NAME>(void);
 PyModuleDef_Slot *PyModExportU_<ENCODED_NAME>(void);

The following functions will be added:

 PyObject *PyModule_FromSlotsAndSpec(const PyModuleDef_Slot *, PyObject *spec)
 int PyModule_Exec(PyObject *)
 int PyModule_GetToken(PyObject *, void**)
 PyObject *PyType_GetModuleByToken(PyTypeObject *type, const void *token)
 int PyModule_GetStateSize(PyObject *, Py_ssize_t *result);

A new macro will be added:

 PyMODEXPORT_FUNC

And new slot types (#define\d names for small integers):

  • Py_mod_name (equivalent to PyModuleDef.m_name)
  • Py_mod_doc (equivalent to PyModuleDef.m_doc)
  • Py_mod_state_size (equivalent to PyModuleDef.m_size)
  • Py_mod_methods (equivalent to PyModuleDef.m_methods)
  • Py_mod_state_traverse (equivalent to PyModuleDef.m_traverse)
  • Py_mod_state_clear (equivalent to PyModuleDef.m_clear)
  • Py_mod_state_free (equivalent to PyModuleDef.m_free)
  • Py_mod_token (see above)

All this will be added to the Limited API.

Backwards Compatibility

If an existing module is ported to use the new mechanism, then PyModule_GetDef will start returning NULL for it. (This matches PyModule_GetDef's current documentation.) We claim that how a module was defined is an implementation detail of that module, so this should not be considered a breaking change.

Similarly, the PyType_GetModuleByDef function may stop matching modules whose definition changed. Module authors may avoid this by explicitly setting a def as the token.

PyType_GetModuleByDef will now accept a module token as the def argument. We specify a suitable restriction on using PyModuleDef addresses as tokens, and non-PyModuleDef pointers were previously invalid input, so this is not a backwards-compatibility issue.

The Py_mod_create function may now be called with NULL for the second argument. This could trip people porting from def to slots, so it needs to be mentioned in porting notes.

Forward compatibility

If a module defines the new export hook, CPython versions that implement this PEP will ignore the traditional PyInit_* hook.

Extensions that straddle Python versions are expected to define both hooks; each build of CPython will “pick” the newest one that it supports.

Porting guide

Here is a guide to convert an existing module to the new API, including some tricky edge cases. It should be moved to a HOWTO in the documentation.

This guide is meant for hand-written modules. For code generators and language wrappers, the pep793-shim below may be more useful.

  1. Scan your code for uses of PyModule_GetDef. This function will return NULL for modules that use the new mechanism. Instead:

    • For getting the contents of the module's PyModuleDef, use the C struct directly. Alternatively, get attributes from the module using, for example, PyModule_GetNameObject, the __doc__ attribute, and PyModule_GetStateSize. (Note that Python code can mutate a module's attributes.)
    • For testing if a module object is “yours”, use PyModule_GetToken instead. Later in this guide, you'll set the token to be the existing PyModuleDef structure.
  2. Optionally, scan your code for uses of PyType_GetModuleByDef, and replace them with PyType_GetModuleByToken. Later in this guide, you'll set the token to be the existing PyModuleDef structure.

    (You may skip this step if targetting Python versions that don't expose PyType_GetModuleByToken, since PyType_GetModuleByDef is backwards-compatible.)

  3. Look at the function identified by Py_mod_create, if any. Make sure that it does not use its second argument (PyModuleDef), as it will be called with NULL. Instead of the argument, use the existing PyModuleDef struct directly.

  4. If using multiple Py_mod_exec slots, consolidate them: pick one of the functions, or write a new one, and call the others from it. Remove all but one Py_mod_exec slots.

  5. Make a copy of the existing PyModuleDef_Slot array pointed to by the m_slots member of your PyModuleDef. If you don't have an existing slots array, create one like this:

    static PyModuleDef_Slot module_slots[] = {
        {0}
    };
    

    Give this array a unique name. Further examples will assume that you've named it module_slots.

  6. Add slots for all members of the existing PyModuleDef structure. See pep793-api-summary for a list of the new slots. For example, to add a name and docstring:

    static PyModuleDef_Slot module_slots[] = {
        {Py_mod_name, "mymodule"},
        {Py_mod_doc, (char*)PyDoc_STR("my docstring")},
        // ... (keep existing slots here)
        {0}
    };
    
  7. If you switched from PyModule_GetDef to PyModule_GetToken, and/or if you use PyType_GetModuleByDef or PyType_GetModuleByToken, add a Py_mod_token slot pointing to the existing PyModuleDef struct:

    static PyModuleDef_Slot module_slots[] = {
        // ... (keep existing slots here)
        {Py_mod_token, &your_module_def},
        {0}
    };
    
  8. Add a new export hook.

    PyMODEXPORT_FUNC PyModExport_examplemodule(PyObject);
    
    PyMODEXPORT_FUNC
    PyModExport_examplemodule(void)
    {
        return module_slots;
    }
    

The new export hook will be used on Python 3.15 and above. Once your module no longer supports lower versions:

  1. Delete the PyInit_ function.

  2. If the existing PyModuleDef struct is used only for Py_mod_token and/or PyType_GetModuleByToken, you may remove the Py_mod_token line and replace &your_module_def with module_slots everywhere else.

  3. Delete any unused data. The PyModuleDef struct and the original slots array are likely to be unused.

Backwards compatibility shim

It is possible to write a generic function that implements the “old” export hook (PyInit_) in terms of the API proposed here.

The following implementation can be copied and pasted to a project; only the names PyInit_examplemodule (twice) and PyModExport_examplemodule should need adjusting.

When added to the pep793-example below and compiled with a non-free-threaded build of this PEP's reference implementation, the resulting extension is compatible with non-free-threading 3.9+ builds, in addition to a free-threading build of the reference implementation. (The module must be named without a version tag, e.g. examplemodule.so, and be placed on sys.path.)

Full support for creating such modules will require backports of some new API, and support in build/install tools. This is out of scope of this PEP. (In particular, the demo “cheats” by using a subset of Limited API 3.15 that happens to work on 3.9; a proper implementation would use Limited API 3.9 with backport shims for new API like Py_mod_name.)

This implementation places a few additional requirements on the slots array:

  • Slots that correspond to PyModuleDef members must come first.
  • A Py_mod_name slot is required.
  • Any Py_mod_token must be set to &module_def_and_token, defined here.

pep-0793/shim.c :language: c

Security Implications

None known

How to Teach This

In addition to regular reference docs, the pep793-porting-notes should be added as a new HOWTO.

Example

pep-0793/examplemodule.c :language: c

Reference Implementation

Implementation is tracked in GitHub issue #140550 .

A draft implementation was available in a GitHub branch .

Rejected Ideas

Exporting a data pointer rather than a function

This proposes a new module export function, which is expected to return static constant data. That data could be exported directly as a data pointer.

With a function, we avoid dealing with a new kind of exported symbol.

A function also allows the extension to introspect its environment in a limited way -- for example, to tailor the returned data to the current Python version.

Changing PyModuleDef to not be PyObject

It is possible to change PyModuleDef to no longer include the PyObject header, and continue using the current PyInit_* hook. There are several issues with this approach:

  • The import machinery would need to examine bit-patterns in the objects to distinguish between different memory layouts:

    • the “old” PyObject-based PyModuleDef, returned by current abi3 extensions,
    • the new PyModuleDef,
    • PyObject-based module objects, for single-phase initialization.

    This is fragile, and places constraints on future changes to PyObject: the memory layouts need to stay distinguishable until both single-phase initialization and the current Stable ABI are no longer supported.

  • PyModuleDef_Init is documented to “Ensure a module definition is a properly initialized Python object that correctly reports its type and a reference count.” This would need to change without warning, breaking any user code that treats PyModuleDefs as Python objects.

Possible Future Directions

These ideas are out of scope for this proposal.

Improving slots in general

Slots -- and specifically the existing PyModuleDef_Slot -- do have a few shortcomings. The most important are:

  • Type safety: void * is used for data pointers, function pointers and small integers, requiring casting that is technically undefined behaviour in C -- but works in practice on all relevant architectures. (For example: Py_tp_doc marks a string; Py_mod_gil an integer.)

  • Limited forward compatibility: if an extension provides a slot ID that's unknown to the current interpreter, module creation will fail. This makes it cumbersome to use “optional” features -- ones that should only take effect if the interpreter supports them. (The recently added slots Py_mod_gil and Py_mod_multiple_interpreters are good examples.)

    One workaround is to check Py_Version in the export function, and return a slot array suitable for the current interpreter.

Updating defaults

With a new API, we could update defaults for the Py_mod_multiple_interpreters and Py_mod_gil slots.

The inittab

We'll need to allow PyModuleDef-less slots in the inittab -- that is, add a new variant of PyImport_ExtendInittab. Should that be part of this PEP?

The inittab is used for embedding, where a common/stable ABI is not that important. So, it might be OK to leave this to a later change.

Source: https://peps.python.org/pep-0793/

Linked PEP 465 — A dedicated infix operator for matrix multiplication

Abstract

This PEP proposes a new binary operator to be used for matrix multiplication, called @. (Mnemonic: @ is * for mATrices.)

Specification

A new binary operator is added to the Python language, together with the corresponding in-place version:

======= ========================= =============================== Op Precedence/associativity Methods ======= ========================= =============================== @ Same as * __matmul__, __rmatmul__ @= n/a __imatmul__ ======= ========================= ===============================

No implementations of these methods are added to the builtin or standard library types. However, a number of projects have reached consensus on the recommended semantics for these operations; see Intended usage details_ below for details.

For details on how this operator will be implemented in CPython, see Implementation details_.

Motivation

Executive summary

In numerical code, there are two important operations which compete for use of Python's * operator: elementwise multiplication, and matrix multiplication. In the nearly twenty years since the Numeric library was first proposed, there have been many attempts to resolve this tension ; none have been really satisfactory. Currently, most numerical Python code uses * for elementwise multiplication, and function/method syntax for matrix multiplication; however, this leads to ugly and unreadable code in common circumstances. The problem is bad enough that significant amounts of code continue to use the opposite convention (which has the virtue of producing ugly and unreadable code in different circumstances), and this API fragmentation across codebases then creates yet more problems. There does not seem to be any good solution to the problem of designing a numerical API within current Python syntax -- only a landscape of options that are bad in different ways. The minimal change to Python syntax which is sufficient to resolve these problems is the addition of a single new infix operator for matrix multiplication.

Matrix multiplication has a singular combination of features which distinguish it from other binary operations, which together provide a uniquely compelling case for the addition of a dedicated infix operator:

  • Just as for the existing numerical operators, there exists a vast body of prior art supporting the use of infix notation for matrix multiplication across all fields of mathematics, science, and engineering; @ harmoniously fills a hole in Python's existing operator system.

  • @ greatly clarifies real-world code.

  • @ provides a smoother onramp for less experienced users, who are particularly harmed by hard-to-read code and API fragmentation.

  • @ benefits a substantial and growing portion of the Python user community.

  • @ will be used frequently -- in fact, evidence suggests it may be used more frequently than // or the bitwise operators.

  • @ allows the Python numerical community to reduce fragmentation, and finally standardize on a single consensus duck type for all numerical array objects.

Background: What's wrong with the status quo?

When we crunch numbers on a computer, we usually have lots and lots of numbers to deal with. Trying to deal with them one at a time is cumbersome and slow -- especially when using an interpreted language. Instead, we want the ability to write down simple operations that apply to large collections of numbers all at once. The n-dimensional array is the basic object that all popular numeric computing environments use to make this possible. Python has several libraries that provide such arrays, with numpy being at present the most prominent.

When working with n-dimensional arrays, there are two different ways we might want to define multiplication. One is elementwise multiplication:

[[1, 2], [[11, 12], [[1 * 11, 2 * 12], [3, 4]] x [13, 14]] = [3 * 13, 4 * 14]]

and the other is matrix multiplication_:

.. _matrix multiplication: https://en.wikipedia.org/wiki/Matrix_multiplication

[[1, 2],     [[11, 12],     [[1 * 11 + 2 * 13, 1 * 12 + 2 * 14],
 [3, 4]]  x   [13, 14]]  =   [3 * 11 + 4 * 13, 3 * 12 + 4 * 14]]

Elementwise multiplication is useful because it lets us easily and quickly perform many multiplications on a large collection of values, without writing a slow and cumbersome for loop. And this works as part of a very general schema: when using the array objects provided by numpy or other numerical libraries, all Python operators work elementwise on arrays of all dimensionalities. The result is that one can write functions using straightforward code like a * b + c / d, treating the variables as if they were simple values, but then immediately use this function to efficiently perform this calculation on large collections of values, while keeping them organized using whatever arbitrarily complex array layout works best for the problem at hand.

Matrix multiplication is more of a special case. It's only defined on 2d arrays (also known as "matrices"), and multiplication is the only operation that has an important "matrix" version -- "matrix addition" is the same as elementwise addition; there is no such thing as "matrix bitwise-or" or "matrix floordiv"; "matrix division" and "matrix to-the-power-of" can be defined but are not very useful, etc. However, matrix multiplication is still used very heavily across all numerical application areas; mathematically, it's one of the most fundamental operations there is.

Because Python syntax currently allows for only a single multiplication operator *, libraries providing array-like objects must decide: either use * for elementwise multiplication, or use * for matrix multiplication. And, unfortunately, it turns out that when doing general-purpose number crunching, both operations are used frequently, and there are major advantages to using infix rather than function call syntax in both cases. Thus it is not at all clear which convention is optimal, or even acceptable; often it varies on a case-by-case basis.

Nonetheless, network effects mean that it is very important that we pick just one convention. In numpy, for example, it is technically possible to switch between the conventions, because numpy provides two different types with different __mul__ methods. For numpy.ndarray objects, * performs elementwise multiplication, and matrix multiplication must use a function call (numpy.dot). For numpy.matrix objects, * performs matrix multiplication, and elementwise multiplication requires function syntax. Writing code using numpy.ndarray works fine. Writing code using numpy.matrix also works fine. But trouble begins as soon as we try to integrate these two pieces of code together. Code that expects an ndarray and gets a matrix, or vice-versa, may crash or return incorrect results. Keeping track of which functions expect which types as inputs, and return which types as outputs, and then converting back and forth all the time, is incredibly cumbersome and impossible to get right at any scale. Functions that defensively try to handle both types as input and DTRT, find themselves floundering into a swamp of isinstance and if statements.

PEP 238 split / into two operators: / and //. Imagine the chaos that would have resulted if it had instead split int into two types: classic_int, whose __div__ implemented floor division, and new_int, whose __div__ implemented true division. This, in a more limited way, is the situation that Python number-crunchers currently find themselves in.

In practice, the vast majority of projects have settled on the convention of using * for elementwise multiplication, and function call syntax for matrix multiplication (e.g., using numpy.ndarray instead of numpy.matrix). This reduces the problems caused by API fragmentation, but it doesn't eliminate them. The strong desire to use infix notation for matrix multiplication has caused a number of specialized array libraries to continue to use the opposing convention (e.g., scipy.sparse, pyoperators, pyviennacl) despite the problems this causes, and numpy.matrix itself still gets used in introductory programming courses, often appears in StackOverflow answers, and so forth. Well-written libraries thus must continue to be prepared to deal with both types of objects, and, of course, are also stuck using unpleasant funcall syntax for matrix multiplication. After nearly two decades of trying, the numerical community has still not found any way to resolve these problems within the constraints of current Python syntax (see Rejected alternatives to adding a new operator_ below).

This PEP proposes the minimum effective change to Python syntax that will allow us to drain this swamp. It splits * into two operators, just as was done for /: * for elementwise multiplication, and @ for matrix multiplication. (Why not the reverse? Because this way is compatible with the existing consensus, and because it gives us a consistent rule that all the built-in numeric operators also apply in an elementwise manner to arrays; the reverse convention would lead to more special cases.)

So that's why matrix multiplication doesn't and can't just use *. Now, in the rest of this section, we'll explain why it nonetheless meets the high bar for adding a new operator.

Why should matrix multiplication be infix?

Right now, most numerical code in Python uses syntax like numpy.dot(a, b) or a.dot(b) to perform matrix multiplication. This obviously works, so why do people make such a fuss about it, even to the point of creating API fragmentation and compatibility swamps?

Matrix multiplication shares two features with ordinary arithmetic operations like addition and multiplication on numbers: (a) it is used very heavily in numerical programs -- often multiple times per line of code -- and (b) it has an ancient and universally adopted tradition of being written using infix syntax. This is because, for typical formulas, this notation is dramatically more readable than any function call syntax. Here's an example to demonstrate:

One of the most useful tools for testing a statistical hypothesis is the linear hypothesis test for OLS regression models. It doesn't really matter what all those words I just said mean; if we find ourselves having to implement this thing, what we'll do is look up some textbook or paper on it, and encounter many mathematical formulas that look like:

S = (H \beta - r)^T (H V H^T)^{-1} (H \beta - r)

Here the various variables are all vectors or matrices (details for the curious: ).

Now we need to write code to perform this calculation. In current numpy, matrix multiplication can be performed using either the function or method call syntax. Neither provides a particularly readable translation of the formula:

import numpy as np
from numpy.linalg import inv, solve

# Using dot function:
S = np.dot((np.dot(H, beta) - r).T,
           np.dot(inv(np.dot(np.dot(H, V), H.T)), np.dot(H, beta) - r))

# Using dot method:
S = (H.dot(beta) - r).T.dot(inv(H.dot(V).dot(H.T))).dot(H.dot(beta) - r)

With the @ operator, the direct translation of the above formula becomes:

S = (H @ beta - r).T @ inv(H @ V @ H.T) @ (H @ beta - r)

Notice that there is now a transparent, 1-to-1 mapping between the symbols in the original formula and the code that implements it.

Of course, an experienced programmer will probably notice that this is not the best way to compute this expression. The repeated computation of H \beta - r should perhaps be factored out; and, expressions of the form dot(inv(A), B) should almost always be replaced by the more numerically stable solve(A, B). When using @, performing these two refactorings gives us:

# Version 1 (as above)
S = (H @ beta - r).T @ inv(H @ V @ H.T) @ (H @ beta - r)

# Version 2
trans_coef = H @ beta - r
S = trans_coef.T @ inv(H @ V @ H.T) @ trans_coef

# Version 3
S = trans_coef.T @ solve(H @ V @ H.T, trans_coef)

Notice that when comparing between each pair of steps, it's very easy to see exactly what was changed. If we apply the equivalent transformations to the code using the .dot method, then the changes are much harder to read out or verify for correctness:

# Version 1 (as above)
S = (H.dot(beta) - r).T.dot(inv(H.dot(V).dot(H.T))).dot(H.dot(beta) - r)

# Version 2
trans_coef = H.dot(beta) - r
S = trans_coef.T.dot(inv(H.dot(V).dot(H.T))).dot(trans_coef)

# Version 3
S = trans_coef.T.dot(solve(H.dot(V).dot(H.T)), trans_coef)

Readability counts! The statements using @ are shorter, contain more whitespace, can be directly and easily compared both to each other and to the textbook formula, and contain only meaningful parentheses. This last point is particularly important for readability: when using function-call syntax, the required parentheses on every operation create visual clutter that makes it very difficult to parse out the overall structure of the formula by eye, even for a relatively simple formula like this one. Eyes are terrible at parsing non-regular languages. I made and caught many errors while trying to write out the 'dot' formulas above. I know they still contain at least one error, maybe more. (Exercise: find it. Or them.) The @ examples, by contrast, are not only correct, they're obviously correct at a glance.

If we are even more sophisticated programmers, and writing code that we expect to be reused, then considerations of speed or numerical accuracy might lead us to prefer some particular order of evaluation. Because @ makes it possible to omit irrelevant parentheses, we can be certain that if we do write something like (H @ V) @ H.T, then our readers will know that the parentheses must have been added intentionally to accomplish some meaningful purpose. In the dot examples, it's impossible to know which nesting decisions are important, and which are arbitrary.

Infix @ dramatically improves matrix code usability at all stages of programmer interaction.

Transparent syntax is especially crucial for non-expert programmers

A large proportion of scientific code is written by people who are experts in their domain, but are not experts in programming. And there are many university courses run each year with titles like "Data analysis for social scientists" which assume no programming background, and teach some combination of mathematical techniques, introduction to programming, and the use of programming to implement these mathematical techniques, all within a 10-15 week period. These courses are more and more often being taught in Python rather than special-purpose languages like R or Matlab.

For these kinds of users, whose programming knowledge is fragile, the existence of a transparent mapping between formulas and code often means the difference between succeeding and failing to write that code at all. This is so important that such classes often use the numpy.matrix type which defines * to mean matrix multiplication, even though this type is buggy and heavily disrecommended by the rest of the numpy community for the fragmentation that it causes. This pedagogical use case is, in fact, the only reason numpy.matrix remains a supported part of numpy. Adding @ will benefit both beginning and advanced users with better syntax; and furthermore, it will allow both groups to standardize on the same notation from the start, providing a smoother on-ramp to expertise.

But isn't matrix multiplication a pretty niche requirement?

The world is full of continuous data, and computers are increasingly called upon to work with it in sophisticated ways. Arrays are the lingua franca of finance, machine learning, 3d graphics, computer vision, robotics, operations research, econometrics, meteorology, computational linguistics, recommendation systems, neuroscience, astronomy, bioinformatics (including genetics, cancer research, drug discovery, etc.), physics engines, quantum mechanics, geophysics, network analysis, and many other application areas. In most or all of these areas, Python is rapidly becoming a dominant player, in large part because of its ability to elegantly mix traditional discrete data structures (hash tables, strings, etc.) on an equal footing with modern numerical data types and algorithms.

We all live in our own little sub-communities, so some Python users may be surprised to realize the sheer extent to which Python is used for number crunching -- especially since much of this particular sub-community's activity occurs outside of traditional Python/FOSS channels. So, to give some rough idea of just how many numerical Python programmers are actually out there, here are two numbers: In 2013, there were 7 international conferences organized specifically on numerical Python . At PyCon 2014, ~20% of the tutorials appear to involve the use of matrices .

To quantify this further, we used Github's "search" function to look at what modules are actually imported across a wide range of real-world code (i.e., all the code on Github). We checked for imports of several popular stdlib modules, a variety of numerically oriented modules, and various other extremely high-profile modules like django and lxml (the latter of which is the #1 most downloaded package on PyPI). Starred lines indicate packages which export array- or matrix-like objects which will adopt @ if this PEP is approved:

Count of Python source files on Github matching given search terms
                 (as of 2014-04-10, ~21:00 UTC)
================ ==========  ===============  =======  ===========
module           "import X"  "from X import"    total  total/numpy
================ ==========  ===============  =======  ===========
sys                 2374638            63301  2437939         5.85
os                  1971515            37571  2009086         4.82
re                  1294651             8358  1303009         3.12
numpy ************** 337916 ********** 79065 * 416981 ******* 1.00
warnings             298195            73150   371345         0.89
subprocess           281290            63644   344934         0.83
django                62795           219302   282097         0.68
math                 200084            81903   281987         0.68
threading            212302            45423   257725         0.62
pickle+cPickle       215349            22672   238021         0.57
matplotlib           119054            27859   146913         0.35
sqlalchemy            29842            82850   112692         0.27
pylab *************** 36754 ********** 41063 ** 77817 ******* 0.19
scipy *************** 40829 ********** 28263 ** 69092 ******* 0.17
lxml                  19026            38061    57087         0.14
zlib                  40486             6623    47109         0.11
multiprocessing       25247            19850    45097         0.11
requests              30896              560    31456         0.08
jinja2                 8057            24047    32104         0.08
twisted               13858             6404    20262         0.05
gevent                11309             8529    19838         0.05
pandas ************** 14923 *********** 4005 ** 18928 ******* 0.05
sympy                  2779             9537    12316         0.03
theano *************** 3654 *********** 1828 *** 5482 ******* 0.01
================ ==========  ===============  =======  ===========

These numbers should be taken with several grains of salt (see footnote for discussion: ), but, to the extent they can be trusted, they suggest that numpy might be the single most-imported non-stdlib module in the entire Pythonverse; it's even more-imported than such stdlib stalwarts as subprocess, math, pickle, and threading. And numpy users represent only a subset of the broader numerical community that will benefit from the @ operator. Matrices may once have been a niche data type restricted to Fortran programs running in university labs and military clusters, but those days are long gone. Number crunching is a mainstream part of modern Python usage.

In addition, there is some precedence for adding an infix operator to handle a more-specialized arithmetic operation: the floor division operator //, like the bitwise operators, is very useful under certain circumstances when performing exact calculations on discrete values. But it seems likely that there are many Python programmers who have never had reason to use // (or, for that matter, the bitwise operators). @ is no more niche than //.

So @ is good for matrix formulas, but how common are those really?

We've seen that @ makes matrix formulas dramatically easier to work with for both experts and non-experts, that matrix formulas appear in many important applications, and that numerical libraries like numpy are used by a substantial proportion of Python's user base. But numerical libraries aren't just about matrix formulas, and being important doesn't necessarily mean taking up a lot of code: if matrix formulas only occurred in one or two places in the average numerically-oriented project, then it still wouldn't be worth adding a new operator. So how common is matrix multiplication, really?

When the going gets tough, the tough get empirical. To get a rough estimate of how useful the @ operator will be, the table below shows the rate at which different Python operators are actually used in the stdlib, and also in two high-profile numerical packages -- the scikit-learn machine learning library, and the nipy neuroimaging library -- normalized by source lines of code (SLOC). Rows are sorted by the 'combined' column, which pools all three code bases together. The combined column is thus strongly weighted towards the stdlib, which is much larger than both projects put together (stdlib: 411575 SLOC, scikit-learn: 50924 SLOC, nipy: 37078 SLOC).

The dot row (marked ******) counts how common matrix multiply operations are in each codebase.

====  ======  ============  ====  ========
  op  stdlib  scikit-learn  nipy  combined
====  ======  ============  ====  ========
   =    2969          5536  4932      3376 / 10,000 SLOC
   -     218           444   496       261
   +     224           201   348       231
  ==     177           248   334       196
   *     156           284   465       192
   %     121           114   107       119
  **      59           111   118        68
  !=      40            56    74        44
   /      18           121   183        41
   >      29            70   110        39
  +=      34            61    67        39
   <      32            62    76        38
  >=      19            17    17        18
  <=      18            27    12        18
 dot ***** 0 ********** 99 ** 74 ****** 16
   |      18             1     2        15
   &      14             0     6        12
  <<      10             1     1         8
  //       9             9     1         8
  -=       5            21    14         8
  *=       2            19    22         5
  /=       0            23    16         4
  >>       4             0     0         3
   ^       3             0     0         3
   ~       2             4     5         2
  |=       3             0     0         2
  &=       1             0     0         1
 //=       1             0     0         1
  ^=       1             0     0         0
 **=       0             2     0         0
  %=       0             0     0         0
 <<=       0             0     0         0
 >>=       0             0     0         0
====  ======  ============  ====  ========

These two numerical packages alone contain ~780 uses of matrix multiplication. Within these packages, matrix multiplication is used more heavily than most comparison operators (< != <= >=). Even when we dilute these counts by including the stdlib into our comparisons, matrix multiplication is still used more often in total than any of the bitwise operators, and 2x as often as //. This is true even though the stdlib, which contains a fair amount of integer arithmetic and no matrix operations, makes up more than 80% of the combined code base.

By coincidence, the numeric libraries make up approximately the same proportion of the 'combined' codebase as numeric tutorials make up of PyCon 2014's tutorial schedule, which suggests that the 'combined' column may not be wildly unrepresentative of new Python code in general. While it's impossible to know for certain, from this data it seems entirely possible that across all Python code currently being written, matrix multiplication is already used more often than // and the bitwise operations.

But isn't it weird to add an operator with no stdlib uses?

It's certainly unusual (though extended slicing existed for some time builtin types gained support for it, Ellipsis is still unused within the stdlib, etc.). But the important thing is whether a change will benefit users, not where the software is being downloaded from. It's clear from the above that @ will be used, and used heavily. And this PEP provides the critical piece that will allow the Python numerical community to finally reach consensus on a standard duck type for all array-like objects, which is a necessary precondition to ever adding a numerical array type to the stdlib.

Compatibility considerations

Currently, the only legal use of the @ token in Python code is at statement beginning in decorators. The new operators are both infix; the one place they can never occur is at statement beginning. Therefore, no existing code will be broken by the addition of these operators, and there is no possible parsing ambiguity between decorator-@ and the new operators.

Another important kind of compatibility is the mental cost paid by users to update their understanding of the Python language after this change, particularly for users who do not work with matrices and thus do not benefit. Here again, @ has minimal impact: even comprehensive tutorials and references will only need to add a sentence or two to fully document this PEP's changes for a non-numerical audience.

Intended usage details

This section is informative, rather than normative -- it documents the consensus of a number of libraries that provide array- or matrix-like objects on how @ will be implemented.

This section uses the numpy terminology for describing arbitrary multidimensional arrays of data, because it is a superset of all other commonly used models. In this model, the shape of any array is represented by a tuple of integers. Because matrices are two-dimensional, they have len(shape) == 2, while 1d vectors have len(shape) == 1, and scalars have shape == (), i.e., they are "0 dimensional". Any array contains prod(shape) total entries. Notice that prod(()) == 1_ (for the same reason that sum(()) == 0); scalars are just an ordinary kind of array, not a special case. Notice also that we distinguish between a single scalar value (shape == (), analogous to 1), a vector containing only a single entry (shape == (1,), analogous to [1]), a matrix containing only a single entry (shape == (1, 1), analogous to [[1]]), etc., so the dimensionality of any array is always well-defined. Other libraries with more restricted representations (e.g., those that support 2d arrays only) might implement only a subset of the functionality described here.

.. _prod(()) == 1: https://en.wikipedia.org/wiki/Empty_product

Semantics

The recommended semantics for @ for different inputs are:

  • 2d inputs are conventional matrices, and so the semantics are obvious: we apply conventional matrix multiplication. If we write arr(2, 3) to represent an arbitrary 2x3 array, then arr(2, 3) @ arr(3, 4) returns an array with shape (2, 4).

  • 1d vector inputs are promoted to 2d by prepending or appending a '1' to the shape, the operation is performed, and then the added dimension is removed from the output. The 1 is always added on the "outside" of the shape: prepended for left arguments, and appended for right arguments. The result is that matrix @ vector and vector @ matrix are both legal (assuming compatible shapes), and both return 1d vectors; vector @ vector returns a scalar. This is clearer with examples.

    • arr(2, 3) @ arr(3, 1) is a regular matrix product, and returns an array with shape (2, 1), i.e., a column vector.

    • arr(2, 3) @ arr(3) performs the same computation as the previous (i.e., treats the 1d vector as a matrix containing a single column, shape = (3, 1)), but returns the result with shape (2,), i.e., a 1d vector.

    • arr(1, 3) @ arr(3, 2) is a regular matrix product, and returns an array with shape (1, 2), i.e., a row vector.

    • arr(3) @ arr(3, 2) performs the same computation as the previous (i.e., treats the 1d vector as a matrix containing a single row, shape = (1, 3)), but returns the result with shape (2,), i.e., a 1d vector.

    • arr(1, 3) @ arr(3, 1) is a regular matrix product, and returns an array with shape (1, 1), i.e., a single value in matrix form.

    • arr(3) @ arr(3) performs the same computation as the previous, but returns the result with shape (), i.e., a single scalar value, not in matrix form. So this is the standard inner product on vectors.

    An infelicity of this definition for 1d vectors is that it makes @ non-associative in some cases ((Mat1 @ vec) @ Mat2 != Mat1 @ (vec @ Mat2)). But this seems to be a case where practicality beats purity: non-associativity only arises for strange expressions that would never be written in practice; if they are written anyway then there is a consistent rule for understanding what will happen (Mat1 @ vec @ Mat2 is parsed as (Mat1 @ vec) @ Mat2`, just like `a - b - c); and, not supporting 1d vectors would rule out many important use cases that do arise very commonly in practice. No-one wants to explain to new users why to solve the simplest linear system in the obvious way, they have to type (inv(A) @ b[:, np.newaxis]).flatten() instead of inv(A) @ b, or perform an ordinary least-squares regression by typing solve(X.T @ X, X @ y[:, np.newaxis]).flatten() instead of solve(X.T @ X, X @ y). No-one wants to type (a[np.newaxis, :] @ b[:, np.newaxis])[0, 0]` instead of `a @ b every time they compute an inner product, or (a[np.newaxis, :] @ Mat @ b[:, np.newaxis])[0, 0]` for general quadratic forms instead of `a @ Mat @ b. In addition, sage and sympy (see below) use these non-associative semantics with an infix matrix multiplication operator (they use *), and they report that they haven't experienced any problems caused by it.

  • For inputs with more than 2 dimensions, we treat the last two dimensions as being the dimensions of the matrices to multiply, and 'broadcast' across the other dimensions. This provides a convenient way to quickly compute many matrix products in a single operation. For example, arr(10, 2, 3) @ arr(10, 3, 4) performs 10 separate matrix multiplies, each of which multiplies a 2x3 and a 3x4 matrix to produce a 2x4 matrix, and then returns the 10 resulting matrices together in an array with shape (10, 2, 4). The intuition here is that we treat these 3d arrays of numbers as if they were 1d arrays of matrices, and then apply matrix multiplication in an elementwise manner, where now each 'element' is a whole matrix. Note that broadcasting is not limited to perfectly aligned arrays; in more complicated cases, it allows several simple but powerful tricks for controlling how arrays are aligned with each other; see for details. (In particular, it turns out that when broadcasting is taken into account, the standard scalar * matrix product is a special case of the elementwise multiplication operator *.)

    If one operand is >2d, and another operand is 1d, then the above rules apply unchanged, with 1d->2d promotion performed before broadcasting. E.g., arr(10, 2, 3) @ arr(3) first promotes to arr(10, 2, 3) @ arr(3, 1), then broadcasts the right argument to create the aligned operation arr(10, 2, 3) @ arr(10, 3, 1), multiplies to get an array with shape (10, 2, 1), and finally removes the added dimension, returning an array with shape (10, 2). Similarly, arr(2) @ arr(10, 2, 3) produces an intermediate array with shape (10, 1, 3), and a final array with shape (10, 3).

  • 0d (scalar) inputs raise an error. Scalar * matrix multiplication is a mathematically and algorithmically distinct operation from matrix @ matrix multiplication, and is already covered by the elementwise * operator. Allowing scalar @ matrix would thus both require an unnecessary special case, and violate TOOWTDI.

Adoption

We group existing Python projects which provide array- or matrix-like types based on what API they currently use for elementwise and matrix multiplication.

Projects which currently use * for elementwise multiplication, and function/method calls for matrix multiplication:

The developers of the following projects have expressed an intention to implement @ on their array-like types using the above semantics:

  • numpy
  • pandas
  • blaze
  • theano

The following projects have been alerted to the existence of the PEP, but it's not yet known what they plan to do if it's accepted. We don't anticipate that they'll have any objections, though, since everything proposed here is consistent with how they already do things:

  • pycuda
  • panda3d

Projects which currently use * for matrix multiplication, and function/method calls for elementwise multiplication:

The following projects have expressed an intention, if this PEP is accepted, to migrate from their current API to the elementwise-*, matmul-@ convention (i.e., this is a list of projects whose API fragmentation will probably be eliminated if this PEP is accepted):

  • numpy (numpy.matrix)
  • scipy.sparse
  • pyoperators
  • pyviennacl

The following projects have been alerted to the existence of the PEP, but it's not known what they plan to do if it's accepted (i.e., this is a list of projects whose API fragmentation may or may not be eliminated if this PEP is accepted):

  • cvxopt

Projects which currently use * for matrix multiplication, and which don't really care about elementwise multiplication of matrices:

There are several projects which implement matrix types, but from a very different perspective than the numerical libraries discussed above. These projects focus on computational methods for analyzing matrices in the sense of abstract mathematical objects (i.e., linear maps over free modules over rings), rather than as big bags full of numbers that need crunching. And it turns out that from the abstract math point of view, there isn't much use for elementwise operations in the first place; as discussed in the Background section above, elementwise operations are motivated by the bag-of-numbers approach. So these projects don't encounter the basic problem that this PEP exists to address, making it mostly irrelevant to them; while they appear superficially similar to projects like numpy, they're actually doing something quite different. They use * for matrix multiplication (and for group actions, and so forth), and if this PEP is accepted, their expressed intention is to continue doing so, while perhaps adding @ as an alias. These projects include:

  • sympy
  • sage

Implementation details

New functions operator.matmul and operator.__matmul__ are added to the standard library, with the usual semantics.

A corresponding function PyObject* PyObject_MatrixMultiply(PyObject *o1, PyObject *o2) is added to the C API.

A new AST node is added named MatMult, along with a new token ATEQUAL and new bytecode opcodes BINARY_MATRIX_MULTIPLY and INPLACE_MATRIX_MULTIPLY.

Two new type slots are added; whether this is to PyNumberMethods or a new PyMatrixMethods struct remains to be determined.

Rationale for specification details

Choice of operator

Why @ instead of some other spelling? There isn't any consensus across other programming languages about how this operator should be named ; here we discuss the various options.

Restricting ourselves only to symbols present on US English keyboards, the punctuation characters that don't already have a meaning in Python expression context are: @, backtick, $, !, and ?. Of these options, @ is clearly the best; ! and ? are already heavily freighted with inapplicable meanings in the programming context, backtick has been banned from Python by BDFL pronouncement (see PEP 3099), and $ is uglier, even more dissimilar to * and \cdot, and has Perl/PHP baggage. $ is probably the second-best option of these, though.

Symbols which are not present on US English keyboards start at a significant disadvantage (having to spend 5 minutes at the beginning of every numeric Python tutorial just going over keyboard layouts is not a hassle anyone really wants). Plus, even if we somehow overcame the typing problem, it's not clear there are any that are actually better than @. Some options that have been suggested include:

  • U+00D7 MULTIPLICATION SIGN: A × B
  • U+22C5 DOT OPERATOR: A ⋅ B
  • U+2297 CIRCLED TIMES: A ⊗ B
  • U+00B0 DEGREE: A ° B

What we need, though, is an operator that means "matrix multiplication, as opposed to scalar/elementwise multiplication". There is no conventional symbol with this meaning in either programming or mathematics, where these operations are usually distinguished by context. (And U+2297 CIRCLED TIMES is actually used conventionally to mean exactly the wrong things: elementwise multiplication -- the "Hadamard product" -- or outer product, rather than matrix/inner product like our operator). @ at least has the virtue that it looks like a funny non-commutative operator; a naive user who knows maths but not programming couldn't look at A * B versus A × B, or A * B versus A ⋅ B, or A * B versus A ° B and guess which one is the usual multiplication, and which one is the special case.

Finally, there is the option of using multi-character tokens. Some options:

  • Matlab and Julia use a .* operator. Aside from being visually confusable with *, this would be a terrible choice for us because in Matlab and Julia, * means matrix multiplication and .* means elementwise multiplication, so using .* for matrix multiplication would make us exactly backwards from what Matlab and Julia users expect.

  • APL apparently used +.×, which by combining a multi-character token, confusing attribute-access-like . syntax, and a unicode character, ranks somewhere below U+2603 SNOWMAN on our candidate list. If we like the idea of combining addition and multiplication operators as being evocative of how matrix multiplication actually works, then something like +* could be used -- though this may be too easy to confuse with *+, which is just multiplication combined with the unary + operator.

  • PEP 211 suggested ~*. This has the downside that it sort of suggests that there is a unary * operator that is being combined with unary ~, but it could work.

  • R uses %*% for matrix multiplication. In R this forms part of a general extensible infix system in which all tokens of the form %foo% are user-defined binary operators. We could steal the token without stealing the system.

  • Some other plausible candidates that have been suggested: >< (= ascii drawing of the multiplication sign ×); the footnote operator [*] or |*| (but when used in context, the use of vertical grouping symbols tends to recreate the nested parentheses visual clutter that was noted as one of the major downsides of the function syntax we're trying to get away from); ^*.

So, it doesn't matter much, but @ seems as good or better than any of the alternatives:

  • It's a friendly character that Pythoneers are already used to typing in decorators, but the decorator usage and the math expression usage are sufficiently dissimilar that it would be hard to confuse them in practice.

  • It's widely accessible across keyboard layouts (and thanks to its use in email addresses, this is true even of weird keyboards like those in phones).

  • It's round like * and \cdot.

  • The mATrices mnemonic is cute.

  • The swirly shape is reminiscent of the simultaneous sweeps over rows and columns that define matrix multiplication

  • Its asymmetry is evocative of its non-commutative nature.

  • Whatever, we have to pick something.

Precedence and associativity

There was a long discussion about whether @ should be right- or left-associative (or even something more exotic ). Almost all Python operators are left-associative, so following this convention would be the simplest approach, but there were two arguments that suggested matrix multiplication might be worth making right-associative as a special case:

First, matrix multiplication has a tight conceptual association with function application/composition, so many mathematically sophisticated users have an intuition that an expression like R S x proceeds from right-to-left, with first S transforming the vector x, and then R transforming the result. This isn't universally agreed (and not all number-crunchers are steeped in the pure-math conceptual framework that motivates this intuition ), but at the least this intuition is more common than for other operations like :math:2 \cdot 3 \cdot 4 which everyone reads as going from left-to-right.

Second, if expressions like Mat @ Mat @ vec appear often in code, then programs will run faster (and efficiency-minded programmers will be able to use fewer parentheses) if this is evaluated as Mat @ (Mat @ vec)` then if it is evaluated like `(Mat @ Mat) @ vec.

However, weighing against these arguments are the following:

Regarding the efficiency argument, empirically, we were unable to find any evidence that Mat @ Mat @ vec type expressions actually dominate in real-life code. Parsing a number of large projects that use numpy, we found that when forced by numpy's current funcall syntax to choose an order of operations for nested calls to dot, people actually use left-associative nesting slightly more often than right-associative nesting . And anyway, writing parentheses isn't so bad -- if an efficiency-minded programmer is going to take the trouble to think through the best way to evaluate some expression, they probably should write down the parentheses regardless of whether they're needed, just to make it obvious to the next reader that they order of operations matter.

In addition, it turns out that other languages, including those with much more of a focus on linear algebra, overwhelmingly make their matmul operators left-associative. Specifically, the @ equivalent is left-associative in R, Matlab, Julia, IDL, and Gauss. The only exceptions we found are Mathematica, in which a @ b @ c would be parsed non-associatively as dot(a, b, c), and APL, in which all operators are right-associative. There do not seem to exist any languages that make @ right-associative and * left-associative. And these decisions don't seem to be controversial -- I've never seen anyone complaining about this particular aspect of any of these other languages, and the left-associativity of * doesn't seem to bother users of the existing Python libraries that use * for matrix multiplication. So, at the least we can conclude from this that making @ left-associative will certainly not cause any disasters. Making @ right-associative, OTOH, would be exploring new and uncertain ground.

And another advantage of left-associativity is that it is much easier to learn and remember that @ acts like *, than it is to remember first that @ is unlike other Python operators by being right-associative, and then on top of this, also have to remember whether it is more tightly or more loosely binding than *. (Right-associativity forces us to choose a precedence, and intuitions were about equally split on which precedence made more sense. So this suggests that no matter which choice we made, no-one would be able to guess or remember it.)

On net, therefore, the general consensus of the numerical community is that while matrix multiplication is something of a special case, it's not special enough to break the rules, and @ should parse like * does.

(Non)-Definitions for built-in types

No __matmul__ or __matpow__ are defined for builtin numeric types (float, int, etc.) or for the numbers.Number hierarchy, because these types represent scalars, and the consensus semantics for @ are that it should raise an error on scalars.

We do not -- for now -- define a __matmul__ method on the standard memoryview or array.array objects, for several reasons. Of course this could be added if someone wants it, but these types would require quite a bit of additional work beyond __matmul__ before they could be used for numeric work -- e.g., they have no way to do addition or scalar multiplication either! -- and adding such functionality is beyond the scope of this PEP. In addition, providing a quality implementation of matrix multiplication is highly non-trivial. Naive nested loop implementations are very slow and shipping such an implementation in CPython would just create a trap for users. But the alternative -- providing a modern, competitive matrix multiply -- would require that CPython link to a BLAS library, which brings a set of new complications. In particular, several popular BLAS libraries (including the one that ships by default on OS X) currently break the use of multiprocessing . Together, these considerations mean that the cost/benefit of adding __matmul__ to these types just isn't there, so for now we'll continue to delegate these problems to numpy and friends, and defer a more systematic solution to a future proposal.

There are also non-numeric Python builtins which define __mul__ (str, list, ...). We do not define __matmul__ for these types either, because why would we even do that.

Non-definition of matrix power

Earlier versions of this PEP also proposed a matrix power operator, @@, analogous to **. But on further consideration, it was decided that the utility of this was sufficiently unclear that it would be better to leave it out for now, and only revisit the issue if -- once we have more experience with @ -- it turns out that @@ is truly missed.

Rejected alternatives to adding a new operator

Over the past few decades, the Python numeric community has explored a variety of ways to resolve the tension between matrix and elementwise multiplication operations. PEP 211 and PEP 225, both proposed in 2000 and last seriously discussed in 2008 , were early attempts to add new operators to solve this problem, but suffered from serious flaws; in particular, at that time the Python numerical community had not yet reached consensus on the proper API for array objects, or on what operators might be needed or useful (e.g., PEP 225 proposes 6 new operators with unspecified semantics). Experience since then has now led to consensus that the best solution, for both numeric Python and core Python, is to add a single infix operator for matrix multiply (together with the other new operators this implies like @=).

We review some of the rejected alternatives here.

Use a second type that defines mul as matrix multiplication: As discussed above (Background: What's wrong with the status quo?), this has been tried this for many years via the numpy.matrix type (and its predecessors in Numeric and numarray). The result is a strong consensus among both numpy developers and developers of downstream packages that numpy.matrix should essentially never be used, because of the problems caused by having conflicting duck types for arrays. (Of course one could then argue we should only define __mul__ to be matrix multiplication, but then we'd have the same problem with elementwise multiplication.) There have been several pushes to remove numpy.matrix entirely; the only counter-arguments have come from educators who find that its problems are outweighed by the need to provide a simple and clear mapping between mathematical notation and code for novices (see Transparent syntax is especially crucial for non-expert programmers). But, of course, starting out newbies with a dispreferred syntax and then expecting them to transition later causes its own problems. The two-type solution is worse than the disease.

Add lots of new operators, or add a new generic syntax for defining infix operators: In addition to being generally un-Pythonic and repeatedly rejected by BDFL fiat, this would be using a sledgehammer to smash a fly. The scientific python community has consensus that adding one operator for matrix multiplication is enough to fix the one otherwise unfixable pain point. (In retrospect, we all think PEP 225 was a bad idea too -- or at least far more complex than it needed to be.)

Add a new @ (or whatever) operator that has some other meaning in general Python, and then overload it in numeric code: This was the approach taken by PEP 211, which proposed defining @ to be the equivalent of itertools.product. The problem with this is that when taken on its own terms, it's pretty clear that itertools.product doesn't actually need a dedicated operator. It hasn't even been deemed worth of a builtin. (During discussions of this PEP, a similar suggestion was made to define @ as a general purpose function composition operator, and this suffers from the same problem; functools.compose isn't even useful enough to exist.) Matrix multiplication has a uniquely strong rationale for inclusion as an infix operator. There almost certainly don't exist any other binary operations that will ever justify adding any other infix operators to Python.

Add a .dot method to array types so as to allow "pseudo-infix" A.dot(B) syntax: This has been in numpy for some years, and in many cases it's better than dot(A, B). But it's still much less readable than real infix notation, and in particular still suffers from an extreme overabundance of parentheses. See Why should matrix multiplication be infix?_ above.

Use a 'with' block to toggle the meaning of * within a single code block: E.g., numpy could define a special context object so that we'd have:

c = a * b   # element-wise multiplication
with numpy.mul_as_dot:
    c = a * b  # matrix multiplication

However, this has two serious problems: first, it requires that every array-like type's __mul__ method know how to check some global state (numpy.mul_is_currently_dot or whatever). This is fine if a and b are numpy objects, but the world contains many non-numpy array-like objects. So this either requires non-local coupling -- every numpy competitor library has to import numpy and then check numpy.mul_is_currently_dot on every operation -- or else it breaks duck-typing, with the above code doing radically different things depending on whether a and b are numpy objects or some other sort of object. Second, and worse, with blocks are dynamically scoped, not lexically scoped; i.e., any function that gets called inside the with block will suddenly find itself executing inside the mul_as_dot world, and crash and burn horribly -- if you're lucky. So this is a construct that could only be used safely in rather limited cases (no function calls), and which would make it very easy to shoot yourself in the foot without warning.

Use a language preprocessor that adds extra numerically-oriented operators and perhaps other syntax: (As per recent BDFL suggestion: ) This suggestion seems based on the idea that numerical code needs a wide variety of syntax additions. In fact, given @, most numerical users don't need any other operators or syntax; it solves the one really painful problem that cannot be solved by other means, and that causes painful reverberations through the larger ecosystem. Defining a new language (presumably with its own parser which would have to be kept in sync with Python's, etc.), just to support a single binary operator, is neither practical nor desirable. In the numerical context, Python's competition is special-purpose numerical languages (Matlab, R, IDL, etc.). Compared to these, Python's killer feature is exactly that one can mix specialized numerical code with code for XML parsing, web page generation, database access, network programming, GUI libraries, and so forth, and we also gain major benefits from the huge variety of tutorials, reference material, introductory classes, etc., which use Python. Fragmenting "numerical Python" from "real Python" would be a major source of confusion. A major motivation for this PEP is to reduce fragmentation. Having to set up a preprocessor would be an especially prohibitive complication for unsophisticated users. And we use Python because we like Python! We don't want almost-but-not-quite-Python.

Use overloading hacks to define a "new infix operator" like dot, as in a well-known Python recipe: (See: ) Beautiful is better than ugly. This is... not beautiful. And not Pythonic. And especially unfriendly to beginners, who are just trying to wrap their heads around the idea that there's a coherent underlying system behind these magic incantations that they're learning, when along comes an evil hack like this that violates that system, creates bizarre error messages when accidentally misused, and whose underlying mechanisms can't be understood without deep knowledge of how object oriented systems work.

Use a special "facade" type to support syntax like arr.M * arr: This is very similar to the previous proposal, in that the .M attribute would basically return the same object as arr *dot would, and thus suffers the same objections about 'magicalness'. This approach also has some non-obvious complexities: for example, while arr.M * arr must return an array, arr.M * arr.M and arr * arr.M must return facade objects, or else arr.M * arr.M * arr and arr * arr.M * arr will not work. But this means that facade objects must be able to recognize both other array objects and other facade objects (which creates additional complexity for writing interoperating array types from different libraries who must now recognize both each other's array types and their facade types). It also creates pitfalls for users who may easily type arr * arr.M or arr.M * arr.M and expect to get back an array object; instead, they will get a mysterious object that throws errors when they attempt to use it. Basically with this approach users must be careful to think of .M* as an indivisible unit that acts as an infix operator -- and as infix-operator-like token strings go, at least *dot* is prettier looking (look at its cute little ears!).

Source: https://peps.python.org/pep-0465/

Linked PEP 697 — Limited C API for Extending Opaque Types

Abstract

Add Limited C API support for extending some types with opaque data by allowing code to only deal with data specific to a particular (sub)class.

This mechanism is required to be usable with PyHeapTypeObject.

This PEP does not propose allowing to extend non-dynamically sized variable sized objects such as tuple or int due to their different memory layout and perceived lack of demand for doing so. This PEP leaves room to do so in the future via the same mechanism if ever desired.

Motivation

The motivating problem this PEP solves is attaching C-level state to custom types --- i.e. metaclasses (subclasses of python:type).

This is often needed in “wrappers” that expose another type system (e.g. C++, Java, Rust) as Python classes. These typically need to attach information about the “wrapped” non-Python class to the Python type object.

This should be possible to do in the Limited API, so that the language wrappers or code generators can be used to create Stable ABI extensions. (See PEP 652 for the benefits of providing a stable ABI.)

Extending type is an instance of a more general problem: extending a class while maintaining loose coupling – that is, not depending on the memory layout used by the superclass. (That's a lot of jargon; see Rationale for a concrete example of extending list.)

Rationale

Extending opaque types

In the Limited API, most structs are opaque: their size and memory layout are not exposed, so they can be changed in new versions of CPython (or alternate implementations of the C API).

This means that the usual subclassing pattern -- making the struct used for instances of the base type be the first element of the struct used for instances of the derived type -- does not work. To illustrate with code, the example from the tutorial extends PyListObject (python:list) using the following struct:

 typedef struct {
     PyListObject list;
     int state;
 } SubListObject;

This won't compile in the Limited API, since PyListObject is opaque (to allow changes as features and optimizations are implemented).

Instead, this PEP proposes using a struct with only the state needed in the subclass, that is:

 typedef struct {
     int state;
 } SubListState;

 // (or just `typedef int SubListState;` in this case)

The subclass can now be completely decoupled from the memory layout (and size) of the superclass.

This is possible today. To use such a struct:

  • when creating the class, use PyListObject->tp_basicsize + sizeof(SubListState) as PyType_Spec.basicsize;
  • when accessing the data, use PyListObject->tp_basicsize as the offset into the instance (PyObject*).

However, this has disadvantages:

  • The base's basicsize may not be properly aligned, causing issues on some architectures if not mitigated. (These issues can be particularly nasty if alignment changes in a new release.)
  • PyTypeObject.tp_basicsize is not exposed in the Limited API, so extensions that support Limited API need to use PyObject_GetAttrString(obj, "__basicsize__"). This is cumbersome, and unsafe in edge cases (the Python attribute can be overridden).
  • Variable-size objects are not handled (see Extending variable-size objects_ below).

To make this easy (and even best practice for projects that choose loose coupling over maximum performance), this PEP proposes an API to:

  1. During class creation, specify that SubListState should be “appended” to PyListObject, without passing any additional details about list. (The interpreter itself gets all necessary info, like tp_basicsize, from the base).

    This will be specified by a negative PyType_Spec.basicsize: -sizeof(SubListState).

  2. Given an instance, and the subclass PyTypeObject*, get a pointer to the SubListState. A new function, PyObject_GetTypeData, will be added for this.

The base class is not limited to PyListObject, of course: it can be used to extend any base class whose instance struct is opaque, unstable across releases, or not exposed at all -- including python:type (PyHeapTypeObject) or third-party extensions (for example, NumPy arrays ).

For cases where no additional state is needed, a zero basicsize will be allowed: in that case, the base's tp_basicsize will be inherited. (This currently works, but lacks explicit documentation and tests.)

The tp_basicsize of the new class will be set to the computed total size, so code that inspects classes will continue working as before.

Extending variable-size objects

Additional considerations are needed to subclass variable-sized objects while maintaining loose coupling: the variable-sized data can collide with subclass data (SubListState in the example above).

Currently, CPython doesn't provide a way to prevent such collisions. So, the proposed mechanism of extending opaque classes (negative base->tp_itemsize) will fail by default.

We could stop there, but since the motivating type --- PyHeapTypeObject --- is variable sized, we need a safe way to allow subclassing it. A bit of background first:

Variable-size layouts .....................

There are two main memory layouts for variable-sized objects.

In types such as int or tuple, the variable data is stored at a fixed offset. If subclasses need additional space, it must be added after any variable-sized data:

PyTupleObject: ┌───────────────────┬───┬───┬╌╌╌╌┐ │ PyObject_VAR_HEAD │var. data │ └───────────────────┴───┴───┴╌╌╌╌┘

tuple subclass: ┌───────────────────┬───┬───┬╌╌╌╌┬─────────────┐ │ PyObject_VAR_HEAD │var. data │subclass data│ └───────────────────┴───┴───┴╌╌╌╌┴─────────────┘

In other types, like PyHeapTypeObject, variable-sized data always lives at the end of the instance's memory area:

heap type: ┌───────────────────┬──────────────┬───┬───┬╌╌╌╌┐ │ PyObject_VAR_HEAD │Heap type data│var. data │ └───────────────────┴──────────────┴───┴───┴╌╌╌╌┘

type subclass: ┌───────────────────┬──────────────┬─────────────┬───┬───┬╌╌╌╌┐ │ PyObject_VAR_HEAD │Heap type data│subclass data│var. data │ └───────────────────┴──────────────┴─────────────┴───┴───┴╌╌╌╌┘

The first layout enables fast access to the items array. The second allows subclasses to ignore the variable-sized array (assuming they use offsets from the start of the object to access their data).

Since this PEP focuses on PyHeapTypeObject, it proposes an API to allow subclassing for the second variant. Support for the first can be added later as an API-compatible change (though your PEP author doubts it'd be worth the effort).

Extending classes with the PyHeapTypeObject-like layout ...........................................................

This PEP proposes a type flag, Py_TPFLAGS_ITEMS_AT_END, which will indicate the PyHeapTypeObject-like layout. This can be set in two ways:

  • the superclass can set the flag, allowing subclass authors to not care about the fact that itemsize is involved, or
  • the new subclass sets the flag, asserting that the author knows the superclass is suitable (but perhaps hasn't been updated to use the flag yet).

This flag will be necessary to extend a variable-sized type using negative basicsize.

An alternative to a flag would be to require subclass authors to know that the base uses a compatible layout (e.g. from documentation). A past version of this PEP proposed a new PyType_Slot for it. This turned out to be hard to explain, and goes against the idea of decoupling the subclass from the base layout.

The new flag will be used to allow safely extending variable-sized types: creating a type with spec->basicsize < 0 and base->tp_itemsize > 0 will require the flag.

Additionally, this PEP proposes a helper function to get the variable-sized data of a given instance, if it uses the new Py_TPFLAGS_ITEMS_AT_END flag. This hides the necessary pointer arithmetic behind an API that can potentially be adapted to other layouts in the future (including, potentially, a VM-managed layout).

Big picture ...........

To make it easier to verify that all cases are covered, here's a scary-looking big-picture decision tree.

Note: The individual cases are easier to explain in isolation (see the Note: [reference implementation](Reference Implementation_) for draft docs).

  • spec->basicsize > 0: No change to the status quo. (The base class layout is known.)

  • spec->basicsize == 0: (Inheriting the basicsize)

    • base->tp_itemsize == 0: The item size is set to spec->tp_itemsize. (No change to status quo.)

    • base->tp_itemsize > 0: (Extending a variable-size class)

      • spec->itemsize == 0: The item size is inherited. (No change to status quo.)
      • spec->itemsize > 0: The item size is set. (This is hard to use safely, but it's CPython's current behavior.)
  • spec->basicsize < 0: (Extending the basicsize)

    • base->tp_itemsize == 0: (Extending a fixed-size class)

      • spec->itemsize == 0: The item size is set to 0.
      • spec->itemsize > 0: Fail. (We'd need to add an ob_size, which is only possible for trivial types -- and the trivial layout must be known.)
    • base->tp_itemsize > 0: (Extending a variable-size class)

      • spec->itemsize == 0: (Inheriting the itemsize)

        • Py_TPFLAGS_ITEMS_AT_END used: itemsize is inherited.
        • Py_TPFLAGS_ITEMS_AT_END not used: Fail. (Possible conflict.)
      • spec->itemsize > 0: Fail. (Changing/extending the item size can't be done safely.)

Setting spec->itemsize < 0 is always an error. This PEP does not propose any mechanism to extend tp->itemsize rather than just inherit it.

Relative member offsets

One more piece of the puzzle is PyMemberDef.offset. Extensions that use a subclass-specific struct (SubListState above) will get a way to specify “relative” offsets (offsets based from this struct) rather than “absolute” ones (based off the PyObject struct).

One way to do it would be to automatically assume “relative” offsets when creating a class using the new API. However, this implicit assumption would be too surprising.

To be more explicit, this PEP proposes a new flag for “relative” offsets. At least initially, this flag will serve only as a check against misuse (and a hint for reviewers). It must be present if used with the new API, and must not be used otherwise.

Specification

In the code blocks below, only function headers are part of the specification. Other code (the size/offset calculations) are details of the initial CPython implementation, and subject to change.

Relative basicsize

The basicsize member of PyType_Spec will be allowed to be zero or negative. In that case, its absolute value will specify how much extra storage space instances of the new class require, in addition to the basicsize of the base class. That is, the basicsize of the resulting class will be:

type->tp_basicsize = _align(base->tp_basicsize) + _align(-spec->basicsize);

where _align rounds up to a multiple of alignof(max_align_t).

When spec->basicsize is zero, basicsize will be inherited directly instead, i.e. set to base->tp_basicsize without aligning. (This already works; explicit tests and documentation will be added.)

On an instance, the memory area specific to a subclass -- that is, the “extra space” that subclass reserves in addition its base -- will be available through a new function, PyObject_GetTypeData. In CPython, this function will be defined as:

void *
PyObject_GetTypeData(PyObject *obj, PyTypeObject *cls) {
    return (char *)obj + _align(cls->tp_base->tp_basicsize);
}

Another function will be added to retrieve the size of this memory area:

Py_ssize_t
PyType_GetTypeDataSize(PyTypeObject *cls) {
    return cls->tp_basicsize - _align(cls->tp_base->tp_basicsize);
}

The result may be higher than requested by -basicsize. It is safe to use all of it (e.g. with memset).

The new *Get* functions come with an important caveat, which will be pointed out in documentation: They may only be used for classes created using negative PyType_Spec.basicsize. For other classes, their behavior is undefined. (Note that this allows the above code to assume cls->tp_base is not NULL.)

Inheriting itemsize

When spec->itemsize is zero, tp_itemsize will be inherited from the base. (This already works; explicit tests and documentation will be added.)

A new type flag, Py_TPFLAGS_ITEMS_AT_END, will be added. This flag can only be set on types with non-zero tp_itemsize. It indicates that the variable-sized portion of an instance is stored at the end of the instance's memory.

The default metatype (PyType_Type) will set this flag.

A new function, PyObject_GetItemData, will be added to access the memory reserved for variable-sized content of types with the new flag. In CPython it will be defined as:

void *
PyObject_GetItemData(PyObject *obj) {
    if (!PyType_HasFeature(Py_TYPE(obj), Py_TPFLAGS_ITEMS_AT_END) {
        <fail with TypeError>
    }
    return (char *)obj + Py_TYPE(obj)->tp_basicsize;
}

This function will initially not be added to the Limited API.

Extending a class with positive base->itemsize using negative spec->basicsize will fail unless Py_TPFLAGS_ITEMS_AT_END is set, either on the base or in spec->flags. (See Extending variable-size objects_ for a full explanation.)

Extending a class with positive spec->itemsize using negative spec->basicsize will fail.

Relative member offsets

In types defined using negative PyType_Spec.basicsize, the offsets of members defined via Py_tp_members must be relative to the extra subclass data, rather than the full PyObject struct. This will be indicated by a new flag in PyMemberDef.flags: Py_RELATIVE_OFFSET.

In the initial implementation, the new flag will be redundant. It only serves to make the offset's changed meaning clear, and to help avoid mistakes. It will be an error to not use Py_RELATIVE_OFFSET with negative basicsize, and it will be an error to use it in any other context (i.e. direct or indirect calls to PyDescr_NewMember, PyMember_GetOne, PyMember_SetOne).

CPython will adjust the offset and clear the Py_RELATIVE_OFFSET flag when initializing a type. This means that:

  • the created type's tp_members will not match the input definition's Py_tp_members slot, and
  • any code that reads tp_members will not need to handle the flag.

List of new API

The following new functions/values are proposed.

These will be added to the Limited API/Stable ABI:

  • void * PyObject_GetTypeData(PyObject *obj, PyTypeObject *cls)
  • Py_ssize_t PyType_GetTypeDataSize(PyTypeObject *cls)
  • Py_TPFLAGS_ITEMS_AT_END flag for PyTypeObject.tp_flags
  • Py_RELATIVE_OFFSET flag for PyMemberDef.flags

These will be added to the public C API only:

  • void *PyObject_GetItemData(PyObject *obj)

Backwards Compatibility

No backwards compatibility concerns are known.

Assumptions

The implementation assumes that an instance's memory between type->tp_base->tp_basicsize and type->tp_basicsize offsets “belongs” to type (except variable-length types). This is not documented explicitly, but CPython up to version 3.11 relied on it when adding __dict__ to subclasses, so it should be safe.

Security Implications

None known.

How to Teach This

The initial implementation will include reference documentation and a What's New entry, which should be enough for the target audience -- authors of C extension libraries.

Reference Implementation

A reference implementation is in the extend-opaque branch in the encukou/cpython GitHub repo.

Possible Future Enhancements

Alignment & Performance

The proposed implementation may waste some space if instance structs need smaller alignment than alignof(max_align_t). Also, dealing with alignment makes the calculation slower than it could be if we could rely on base->tp_basicsize being properly aligned for the subtype.

In other words, the proposed implementation focuses on safety and ease of use, and trades space and time for it. If it turns out that this is a problem, the implementation can be adjusted without breaking the API:

  • The offset to the type-specific buffer can be stored, so PyObject_GetTypeData effectively becomes (char *)obj + cls->ht_typedataoffset, possibly speeding things up at the cost of an extra pointer in the class.
  • Then, a new PyType_Slot can specify the desired alignment, to reduce space requirements for instances.

Other layouts for variable-size types

A flag like Py_TPFLAGS_ITEMS_AT_END could be added to signal the “tuple-like” layout described in Extending variable-size objects_, and all mechanisms this PEP proposes could be adapted to support it. Other layouts could be added as well. However, it seems there'd be very little practical benefit, so it's just a theoretical possibility.

Rejected Ideas

Instead of a negative spec->basicsize, a new PyType_Spec flag could've been added. The effect would be the same to any existing code accessing these internals without up to date knowledge of the change as the meaning of the field value is changing in this situation.

Source: https://peps.python.org/pep-0697/

Linked PEP 387 — Backwards Compatibility Policy

Abstract

This PEP outlines Python's backwards compatibility policy.

Rationale

As one of the most used programming languages today , the Python core language and its standard library play a critical role in millions of applications and libraries. This is fantastic. However, it means the development team must be very careful not to break this existing 3rd party code with new releases.

This PEP takes the perspective that "backwards incompatibility" means preexisting code ceases to comparatively function after a change. It is acknowledged that this is not a concrete definition, but the expectation is people in general understand what is meant by "backwards incompatibility", and if they are unsure they may ask the Python development team and/or steering council for guidance.

Backwards Compatibility Rules

This policy applies to all public APIs. These include:

  • Syntax and behavior of these constructs as defined by the reference manual.

  • The C-API.

  • Function, class, module, attribute, and method names and types.

  • Given a set of arguments, the return value, side effects, and raised exceptions of a function. This does not preclude changes from reasonable bug fixes.

  • The position and expected types of arguments and returned values.

  • Behavior of classes with regards to subclasses: the conditions under which overridden methods are called.

  • Documented exceptions and the semantics which lead to their raising.

  • Exceptions commonly raised in EAFP scenarios.

Others are explicitly not part of the public API. They can change or be removed at any time in any way. These include:

  • Function, class, module, attribute, method, and C-API names and types that are prefixed by "_" (except special names).

  • Anything documented publicly as being private. Note that if something is not documented at all, it is not automatically considered private.

  • Imported modules (unless explicitly documented as part of the public API; e.g. importing the bacon module in the spam does not automatically mean spam.bacon is part of the public API unless it is documented as such).

  • Inheritance patterns of internal classes.

  • Test suites. (Anything in the Lib/test directory or test subdirectories of packages.)

  • Backward compatibility rules do not apply to any module or API that is explicitly documented as Provisional per PEP 411.

Basic policy for backwards compatibility

  • In general, incompatibilities should have a large benefit to breakage ratio, and the incompatibility should be easy to resolve in affected code. For example, adding an stdlib module with the same name as a third party package is generally not acceptable. Adding a method or attribute that conflicts with 3rd party code through inheritance, however, is likely reasonable.

  • Unless it is going through the deprecation process below, the behavior of an API must not change in an incompatible fashion between any two consecutive releases. Python's yearly release process (PEP 602) means that the deprecation period must last at least two years.

  • Similarly a feature cannot be removed without notice between any two consecutive releases.

  • For changes that are unable to raise a deprecation warning, consult with the steering council.

  • The steering council may grant exceptions to this policy. In particular, they may shorten the required deprecation period for a feature. Exceptions are only granted for extreme situations such as dangerously broken or insecure features or features no one could reasonably be depending on (e.g., support for completely obsolete platforms).

Soft Deprecation

A soft deprecation can be used when using an API which should no longer be used to write new code, but it remains safe to continue using it in existing code. The API remains documented and tested, but will not be developed further (no enhancement).

The main difference between a "soft" and a (regular) "hard" deprecation is that the soft deprecation does not imply scheduling the removal of the deprecated API.

Another difference is that a soft deprecation does not issue a warning: it's only mentioned in the documentation, whereas usually a "hard" deprecation issues a DeprecationWarning warning at runtime. The documentation of a soft deprecation should explain why the API should be avoided, and if possible propose a replacement.

If the decision is made to deprecate (in the regular sense) a feature that is currently soft deprecated, the deprecation must follow the Backwards Compatibility Rules_ (i.e., there is no exception because the feature is already soft deprecated).

Making Incompatible Changes

Making an incompatible change is a gradual process performed over several releases:

  1. Discuss the change. Depending on the degree of incompatibility, this could be on Discourse , the issue tracker , or in an appropriate workgroup or SIG. If the discussion reaches consensus a PEP or similar document may be written. Hopefully users of the affected API will pipe up to comment.

  2. Add a warning to the current main branch. If behavior is changing, the API may gain a new function or method to perform the new behavior; old usage should raise the warning. If an API is being removed, simply warn whenever it is entered. DeprecationWarning is the usual warning category to use, but PendingDeprecationWarning may be used in special cases where the old and new versions of the API will coexist for many releases . The warning message should include the release the incompatibility is expected to become the default and a link to an issue that users can post feedback to. When feasible, also change typeshed to add the @deprecated decorator (see PEP 702) to the deprecated API, so that users of static type checkers have another way to learn about the deprecation.

    For C API, a compiler warning generated by the Py_DEPRECATED macro is also acceptable.

  3. Wait for the warning to appear in at least two minor Python versions of the same major version, or one minor version in an older major version (e.g., for a warning in Python 3.10.0, you either wait until at least Python 3.12 or Python 4.0 to make the change). It is preferred, though, to wait 5 years before removal (e.g., warn starting in Python 3.10, removal in 3.15; this happens to coincide with the current lifetime of a minor release of Python).

    • If the expected maintenance overhead and security risk of the deprecated behavior is small (e.g. an old function is reimplemented in terms of a new, more general one), it can stay indefinitely (or until the situation changes).

    • If the deprecated feature is replaced by a new one, it should generally be removed only after the last Python version without the new feature reaches end of support.

  4. See if there's any feedback. Users not involved in the original discussions may comment now after seeing the warning. Perhaps reconsider.

  5. The behavior change or feature removal may now be made default or permanent having reached the declared version. Remove the old version and warning.

  6. If a warning cannot be provided to users, consult with the steering council.

Changelog

  • 2025-Jan-27: Updated to prefer a 5-year deprecation period before removal.
  • 2023-Nov-14: Added @deprecated decorator per PEP 702.
  • 2023-Jul-03: Added the Soft Deprecation section, as discussed in https://discuss.python.org/t/27957.
  • 2023-Jun-26: Multiple smaller updates and clarifications, discussed in https://discuss.python.org/t/22042.
  • 2022-Apr-04: Added explicit notes to ask the Steering Council in several exceptional cases.
  • 2021-Apr-16: Clarified how long a warning must be emitted before a change can be made.
  • 2020-Jul-20: Initial accepted version.

Source: https://peps.python.org/pep-0387/