Hello.
I am writing a PEP to describe how I'd like to "resurrect" and maintain
the Stable ABI & Limited API going forward. I assume this'll be my main
focus for CPython in 2021.
I'm not as far along as I hoped to be at the end of 2020, but I guess
it's time to request comments.
If you have any thoughts, arguments or improvements I'd be happy to hear
them!
I'm including the text below; a rendered and forkable/pull-request-able
version is at https://github.com/encukou/abi3/blob/main/PEP.rst
Have a great start of 2021!
---
PEP: 9999
Title: Maintaining the Stable ABI
Author: Petr Viktorin <encukou(a)gmail.com>
Discussions-To:
Status: Draft
Type: Standards Track
Content-Type: text/x-rst
Created: 08-Dec-2020
Abstract
========
[A short (~200 word) description of the technical issue being addressed.]
XXX: Abstract should be written last
Motivation
==========
:pep:`384` defined a limited API and stable ABI, which allows extenders and
embedders of CPython to compile extension modules that are binary-compatible
with any subsequent version of 3.x.
In theory, this brings many advantages:
* A module can be built only once per platform and support multiple versions
of Python, reducing time, power and maintainer attention needed for
builds.
* Binary wheels using the stable ABI work with new versions of CPython
throughout the pre-release period, and can be tested in environments
where
building from source is not practical.
As a welcome side effect of the stable ABI's hiding of implementation
details
is that it is becoming a viable target for alternate Python implementations
that need to implement (parts of) the C API.
However, in hindsignt, PEP 384 and its implementation has several issues:
* There is no process keep the ABI up to date.
* Contents of the limited API are not listed explicitly, making it unclear
if a particular member (e.g. function, structure) is a part of it.
* There is no way to deprecate parts of the limited API.
This PEP defines the limited API more clearly and introducess process
designed to make the API more useful.
Additionally, PEP 384 defines a *limited API* as a way to build against the
stable ABI.
This PEP defines the limited API more robustly.
Rationale
=========
This PEP contains a lot of clarifications and definitions, but just one big
technical change: the stable ABI will be explicitly listed in
a human-maintained “manifest” file.
There have been efforts to collect such lists automatically, e.g. by
scanning
the symbols exported from Python.
This might seem to be easier to maintain by our volunteer team.
However, designing a future-proof API is not a trivial task.
The cost of updating an explicit manifest is small compared
to the overall work that should go into changing API that will need to
be suppported forever (or until Python 3 reaches
end of life, if that comes sooner).
This PEP proposes automatically generating things *from* the manifest:
initially documentation and DLL contents, with later possibilities
for also automating tests.
Stable ABI vs. Limited API
==========================
:pep:`384` and this document deal with the *Limited API* and the *Stable
ABI*,
two related but distinct concepts.
This section clarifies what they mean and defines some of their semantics
(either pre-existing or newly proposed here).
The word “Extensions” is used as a shorthand for all code that uses the
Python API, e.g. extension modules or software that embeds Python.
Stable ABI
----------
The CPython *Stable ABI* is a promise that extensions built with a specific
Cpython version will be usable with any newer interpreter of the same major
version, on the same platform and with the same compiler & settings.
For example, a extension built with CPython 3.10 Stable ABI will be
usable with
CPython 3.11, 3.12, and so on, but not necessarily with 4.0.
The Stable ABI is not generally forward-compatible: an extension built and
tested with CPython 3.10 will not generally be compatible with CPython 3.9.
.. note::
For example, starting in Python 3.10, the `Py_tp_doc` slot may be set to
`NULL`, while in older versions, a `NULL` value will likely crash the
interpreter.
The Stable ABI trades performance for its stability.
For example, many functions in the stable ABI are available as faster macros
to extensions that are built for a specific CPython version.
Future Python sversions may deprecate some members of the Stable ABI.
Such members will still work, but may suffer from issues like reduced
performance or, in the most extreme cases, memory/resource leaks.
Limited API
-----------
Stable ABI guarantee holds for extensions compiled from code that restricts
itself to the *Limited API*, a subset of CPython's C API.
The limited API is used when preprocessor macro `Py_LIMITED_API` is defined
to either `3` or the current `PYTHON_API_VERSION`.
The Limited API is not guaranteed to be *stable*.
In the future, parts of the limited API may be deprecated.
They may even be removed, as long as the *stable ABI* is kept
stable and Python's general backwards compatibility policy, :pep:`387`,
is followed.
.. note::
For example, a function declaration might be removed from public header
files but kept in the library.
This is currently a possibility for the future; this PEP does not to
propose
a concrete process for deprecations and removals.
The goal is for the limited API to cover everything needed to interact
with the interpreter.
There main reasons to not include a public API in the limited subset
should be that it needs implementation details that change between CPython
versions, like struct memory layouts, for performance reasons.
The limited API is not limited to CPython; other implementations are
encouraged to implement it and help drive its design.
Specification
=============
To make the stable ABI more useful and stable, the following changes
are proposed.
Stable ABI Manifest
-------------------
All members of the stable ABI – functions, typedefs, structs, struct fields,
data values etc. – will be explicitly listed in a single "manifest" file,
along with the Limited API version they were added in.
Struct fields that users of the stable ABI are allowed to access will be
listed explicitly.
Members that are not part of the Limited API, but are part of the Stable ABI
(e.g. ``PyObject.ob_type``, which is accessible by the ``Py_TYPE`` macro),
will be annotated as such.
Notes saying “Part of the stable ABI” will be added to Python's
documentation
automatically, in a way similar to the notes on functions that return
borrowed
references.
Source for the Windows shared library `python3.dll` will be generated
from the
stable ABI definition.
The format of the manifest will be subject to change whenever needed.
It should be consumed only by scripts in the CPython repository.
If a more public list is needed, a script can be added to generate it.
Contents of the Stable ABI
--------------------------
The initial stable ABI manifest will include:
* The Stable ABI specified in :pep:`384`.
* All functions listed in ``PC/python3dll.c``.
* All structs (struct typedefs) which these functions return or take as
arguments. (Fields of such structs will not necessarily be added.)
* New type slots, such as ``Py_am_aiter``.
* The type flags ``Py_TPFLAGS_DEFAULT``, ``Py_TPFLAGS_BASETYPE``,
``Py_TPFLAGS_HAVE_GC``, ``Py_TPFLAGS_METHOD_DESCRIPTOR``.
* The calling conventions ``METH_*`` (except deprecated ones).
* All API needed by macros is the stable ABI (usually annotated as not being
part of the limited API).
Additional items may be aded to the initial manifest according to
the checklist below.
Testing the Stable ABI
----------------------
An automatically generated test module will be added to ensure that all
members
of the stable ABI are available at compile time
For each function in the stable ABI, a test will be added that calls the
function using `ctypes`. (Where calling is not practical, such as with
functions related to intepreter initialization and shutdown, the test will
only look the function up.)
This should prevent regressions when a function is converted to a macro,
which keeps the same API but breaks the ABI.
An check will be added to ensure all functions in the stable ABI are tested
this way.
Changing the Limited API
------------------------
A checklist for changing the limited API, including new members (structs,
functions or values), will be added to the `Devguide`_.
The checklist will 1) mention best practices and common pitfalls in Python
C API design and 2) guide the developer around the files that need
changing and
scripts that need running when the limited API is changed.
Below is the initial proposal for the checklist. After the PEP is accepted,
see the Devguide for the current version.
Note that the checklist applies to new additions; not the existing
limited API.
Design considerations:
* Make sure the change does not break the Stable ABI of any version of
Python
since 3.5.
* Make sure no exposed names are private (i.e. begin with an underscore).
* Make sure the new API is well documented.
* Make sure the types of all parameters and return values of the added
function(s) and all fields of the added struct(s) are be part of the
limited API (or standard C).
* Make sure the new API and its intended use follows standard C, not just
features of currently suppoerted platforms.
* Do not cast a function pointer to ``void*`` (a data pointer) or
vice versa.
* Make sure the new API follows reference counting conventions.
(Following them
makes the API easier to reason about, and easier use in other Python
implementations.)
* Do not return borrowed references from functions.
* Do not steal references to function arguments.
* Make sure the ownership rules and lifetimes of all applicable struct
fields,
arguments and return values are well defined.
* Think about ease of use for the user. (In C, ease of use itself is not
very
important; what *is* important is reducing boilerplate code needed to
use the
API. Bugs like to hide in boiler plates.)
* If a function will be often called with specific value for an argument,
consider making it default (assumed when ``NULL`` is passed in).
* Think about future extensions: for example, if it's possible that future
Python versions will need to add a new field to your struct,
how will that be done?
* Make as few assumptions as possible about details that might change in
future CPython versions or differ across C API implementations:
* The GIL
* Garbage collection
* Layout of PyObject and other structs
If following these guidelines would hurt performance, add a fast function
(or macro) to the non-limited API and a stable equivalent to the limited
API.
If anything is unclear, or you have a good reason to break the guidelines,
consider discussing the change at the `capi-sig`_ mailing list.
.. _capi-sig: https://mail.python.org/mailman3/lists/capi-sig.python.org/
Procedure:
* Move the declaration to a header file directly under ``Include/`` and
``#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03yy0000``
(with the ``yy`` corresponding to Python version).
* Make an entry in the stable ABI list. (XXX: mention filename)
* For functions, add a test that calls the function using ctypes
(XXX: mention filename).
* Regenerate the autogenerated files. (XXX: specific instructions)
Advice for Extenders and Embedders
----------------------------------
The following notes will be added to documentation.
Extension authors should test with all Python versions they support,
and preferably build with the lowest such version.
Compiling with ``Py_LIMITED_API`` defined is *not* a guarantee that your
code
conforms to the limited API or the stable ABI.
It only covers definitions, but an API also includes other issues,
such as expected semantics.
Examples of issues that ``Py_LIMITED_API`` does not guard against are:
* Calling a function with invalid arguments
* An function that started accepting ``NULL`` values for an argument
in Python 3.9 will fail if ``NULL`` is passed to it under Python 3.8.
Only testing with 3.8 (or lower versions) will uncover this issue.
* Some structs include a few fields that are part of the stable ABI and
other
fields that aren't.
``Py_LIMITED_API`` does not filter out such “private” fields.
* Using something that is not documented as part of the stable ABI,
but exposed even with ``Py_LIMITED_API`` defined.
Despite the team's best efforts, such issues may happen.
Backwards Compatibility
=======================
The PEP aims at full compatibility with the existing stable ABI and limited
API, but defines them terms more explicitly.
It might not be consistent with some interpretations of what the existing
stable ABI/limited API is.
Security Implications
=====================
None known.
How to Teach This
=================
Technical documentation will be provided.
It will be aimed at experienced users familiar with C.
Reference Implementation
========================
None so far.
Rejected Ideas
==============
While this PEP acknowledges that parts of the limited API might be
deprecated
or removed in the future, a process to do this is not in scope, and is left
to a possible future PEP.
Open Issues
===========
None so far.
References
==========
Copyright
=========
This document is placed in the public domain or under the
CC0-1.0-Universal license, whichever is more permissive.
.. _Devguide: https://devguide.python.org/
..
Local Variables:
mode: indented-text
indent-tabs-mode: nil
sentence-end-double-space: t
fill-column: 70
coding: utf-8
End:
Hello,
Several people asked me to put the long-term effort re. PEPs 489 and 573
in words, so I've written a document that I'd like to submit as an
informational PEP and/or a HOWTO.
A rendered version is available at: https://hackmd.io/@encukou/module-state
It's in Markdown: I've gotten so used to MD that translating to ReST
once sounds easier than drafting in ReST.
If you have a HackMD account and would like to co-author or fix typos
directly, I can give you access.
Isolating Extension Modules
===========================
Abstract
--------
Traditionally, state of Python extension modules was kept in C `static`
variables, which have process-wide scope.
This document describes problems of such per-process state, and efforts
to make per-module state, a better default, possible and easy to use.
The document also describes how to switch to per-module state where
possible.
The switch involves allocating space for that state, switching from
static types to heap types, and—perhaps most importantly—accessing
per-module state from code.
About this document
-------------------
This document does not introduce any changes: those should be done in
their own PEPs (or issues, if small enough).
Rather, it covers the motivation behind an effort that spans multiple
releases.
Once support is reasonably complete, the text can be moved to a
[HOWTO](https://docs.python.org/3/howto/index.html) in the documentation.
Meanwhile, in the spirit of documentation-driven development, gaps in
the text show where to focus the effort.
Whenever the document mentions *extension modules*, the advice also
applies to *built-in* modules, such as the C parts of the standard library.
The standard library is expected to switch to per-module state early.
PEPs related to this effort are:
* PEP 384 -- *Defining a Stable ABI*, which added C API for creating
heap types
* PEP 489 -- *Multi-phase extension module initialization*
* PEP 573 -- *Module State Access from C Extension Methods*
This document is concerned with Python's public C API.
Nothing is specific to CPython.
Motivation
----------
An *interpreter* is the context in which Python code runs. It contains
configuration (e.g. the import path) and runtime state (e.g. the set of
imported modules).
Python supports running multiple interpreters in one process.
There are two cases to think about. Users may run interpreters:
* in sequence, with several `Py_InitializeEx`/`Py_FinalizeEx` cycles, and
* in parallel, managing “sub-interpreters” using
`Py_NewInterpreter`/`Py_EndInterpreter`.
Both cases (and combinations of them) would be most useful when
embedding Python within a library.
Libraries generally shouldn't make assumptions about the application
that uses them, which includes assumptions about a process-wide “main
Python interpreter”.
Currently, CPython doesn't handle this use case well.
Many extension modules (and even some stdlib modules) use *per-process*
global state, because C `static` variables are extremely easy to use.
Thus, data that should be specific to an interpreter ends up being
shared between interpreters.
Unless the extension developer is careful, it is very easy to introduce
edge cases that lead to crashes when a module is loaded in more than one
interpreter.
Unfortunately, *per-interpreter* state is not easy to achieve: extension
authors tend to not keep multiple interpreters in mind when developing,
and it is currently cumbersome to test the behavior.
Rationale for Per-module State
------------------------------
Instead of focusing on per-interpreter state, Python's C API is evolving
to better support the more granular *per-module* state.
By default, C-level data will be attached to a *module object*.
Each interpreter will then create its own module object, keeping data
separate.
For testing the isolation, multiple module objects can even be loaded in
a single interpreter.
Per-module state provides an easy way to think about lifetime and
resource ownership: the extension module author will set up when a
module object is created, and clean up when it's freed.
In this regard, a module is just like any other `PyObject *`; there are
no “on interpreter shutdown” hooks to think about (or forget about).
### Easy-to-use Module State as a Goal
It is currently cumbersome or impossible to do everything the C API
offers while keeping modules isolated.
Enabled by PEP 384, changes in PEPs 489 and 573 (and future planned
ones) aim to first make it *possible* to build modules this way, and
then to make it *easy* to write new modules this way and to convert old
ones, so that it can become a natural default.
Even if per-module state becomes the default, there will be use cases
for different levels of encapsulation: per-process, per-interpreter,
per-thread or per-task state.
The goal is to treat these as exceptional cases: extension authors will
need to think more carefully about them.
### Non-goals: Speedups and the GIL
There is some effort to speed up CPython by making the GIL per-interpreter.
While isolating interpreters helps that effort, defaulting to per-module
state will be beneficial even if no speed-up is achieved.
How to make modules safe with multiple interpreters
---------------------------------------------------
There are many ways to correctly support multiple interpreters in
extension modules.
The rest of this text describes the preferred way to write such a
module, or convert an existing module.
Note that support is a work in progress; the API for some features your
module needs might not yet be ready.
A full example module is (XXX currently available in [a fork on
GitHub](https://github.com/encukou/cpython/blob/xxlimited-facelift/Modules/…;
later it should be in the CPython source tree).
### Isolated Module Objects
The key point to keep in mind when developing an extension module is
that several module objects can be created from a single shared library.
For example:
```pycon
>>> import sys
>>> import binascii
>>> old_binascii = binascii
>>> del sys.modules['binascii']
>>> import binascii # create a new module object
>>> old_binascii == binascii
False
```
As a rule of thumb, the two modules should be completely independent.
All objects and state specific to the module should be encapsulated
within the module object, not shared with other module objects, and
cleaned up when the module object is deallocated.
Exceptions are possible (see “Managing global state” below) but they
will need more thought and attention to edge cases than code that
follows this rule of thumb.
While some modules could do with less stringent restrictions, isolated
modules make it easier to set clear expectations (and guidelines) that
work across a variety of use cases.
### Surprising Edge Cases
Note that isolated modules do create some surprising edge cases.
Most notably, each module object will typically not share its classes
and exceptions with other similar modules.
Continuing from the example above, note that `old_binascii.Error` and
`binascii.Error` are separate objects.
In the following code, the exception is *not* caught:
```pycon
>>> old_binascii.Error == binascii.Error
False
>>> try:
... old_binascii.unhexlify(b'qwertyuiop')
... except binascii.Error:
... print('boo')
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
binascii.Error: Non-hexadecimal digit found
```
This is expected.
Notice that pure-Python modules behave the same way: it is a part of how
Python works.
The goal is to make extension modules safe at the C level, not to make
hacks (like mutating `sys.modules` or sharing objects across
interpreters) behave intuitively.
### Managing Global State
Sometimes, state of a Python module is not specific to that module, but
to the entire process (or something else “more global” than a module).
For example:
* The `readline` module provides access to *the* terminal.
* A module running on a circuit board wants to control *the* on-board LED.
In these cases, the Python module should provide *access* to the global
state, rather than *own* it.
If possible, write the module so that multiple copies of it can access
the state independently (along with other libraries, whether for Python
or other languages).
If that is not possible, consider explicit locking.
If it is necessary to use process-global state, the simplest way to
avoid issues with multiple interpreters is to explicitly prevent a
module from being loaded more than once per process—see “An Opt-Out
Method” below.
### Managing Per-module state
To use per-module state, use [multi-phase extension module
initialization](https://docs.python.org/3/c-api/module.html#multi-phase-ini…
introduced in PEP 489.
This signals that your module supports multiple interpreters correctly.
Set `PyModuleDef.m_size` to a positive number to request that many bytes
of storage local to the module.
Usually, this will be set to the size of some module-specific `struct`,
which can store all of the module's C-level state.
In particular, it is where you should put pointers to classes (including
exceptions) and settings (e.g. `csv.field_size_limit`) which the C code
needs to function.
> [Note]
> Another option is to store state in the module's `__dict__`, but you
must avoid crashing when users modify `__dict__` from Python code.
> This means error- and type-checking at the C level, which is easy to
get wrong and hard to test sufficiently.
If the module state includes `PyObject` pointers, the module object must
hold references to those objects and implement module-level hooks
`m_traverse`, `m_clear`, `m_free`.
These work like `tp_traverse`, `tp_clear`, `tp_free` of a class.
Adding them will require some work and make the code longer; this is the
price for modules which can be unloaded cleanly.
An example of a module with per-module state is (XXX currently available
in [a fork on
GitHub](https://github.com/encukou/cpython/blob/xxlimited-facelift/Modules/…;
later it should be in the CPython source tree), with module
initialization is at the bottom of the file.
### Opt-Out: Limiting to One Module Object per Process
A non-negative `PyModuleDef.m_size` signals that a module supports
multiple interpreters correctly.
If this is not yet the case for your module, you can explicitly make
your module loadable only once per process.
Raising an exception is better than mysteriously crashing in C code!
For example:
```c
static int loaded = 0;
static int
exec_module(PyObject* module)
{
if (loaded) {
PyErr_SetString(PyExc_ImportError,
"cannot load module more than once per process");
return -1;
}
loaded = 1;
... // rest of initialization
}
```
When your module becomes ready, you can remove this check.
### Module state access from functions
Accessing the state from module-level functions is straightforward.
Functions get the module object as their first argument; for extracting
the state there is `PyModule_GetState`:
```c
static PyObject *
func(PyObject *module, PyObject *args)
{
my_struct *state = (my_struct*)PyModule_GetState(module);
if (state == NULL) {
return NULL;
}
... // rest of logic
}
```
(Note that `PyModule_GetState` may return NULL without seting an
exception if there is no module state, i.e. `PyModuleDef.m_size` was
zero. In your own module, you're in control of `m_size`, so this is easy
to prevent.)
### Heap types
Traditionally, types defined in C code were static, that is, `static
PyTypeObject` structures defined directly in code and initialized using
`PyType_Ready()`.
Such types are necessarily shared across the process.
Sharing them between module objects requires paying attention to any
state they own or access. To limit the possible issues, static types are
immutable at the Python level: for example, you can't set
`str.myattribute = 123`.
> [Note]
> Sharing truly immutable objects between interpreters is fine, as long
as they don't provide access to mutable objects.
> But, every Python object has a mutable implementation detail: the
reference count.
> Changes to the refcount are guarded by the GIL.
> Thus, code that shares any Python objects across interpreters
implicitly depends on CPython's current, process-wide GIL.
An alternative to static types is *heap-allocated types*, or heap types
for short.
These correspond more closely to classes created by Python’s `class`
statement.
Heap types can be created by filling a `PyType_Spec` structure, a
description or “blueprint” of a class, and calling
`PyType_FromModuleAndSpec()` to construct a new class object.
> [note]
> Other functions, like `PyType_FromSpec()`, can also create heap types,
> but `PyType_FromModuleAndSpec()` associates the module with the
class, granting access
> to the module state to methods.
The class should generally be stored in *both* the module state (for
safe access from C) and the module's `__dict__` (for access from Python
code).
### Module State Access from Classes
If you have a type object defined with `PyType_FromModuleAndSpec()`,
call `PyType_GetModule` to get the associated module, then
`PyModule_GetState` to get the module's state.
These steps can be combined with `PyType_GetModuleState` to save typing
some tedious error-handling boilerplate:
```c
my_struct *state = (my_struct*)PyType_GetModuleState(type);
if (state === NULL) {
return NULL;
}
```
### Module State Access from Regular Methods
Accessing the module-level state from methods of a class is somewhat
more complicated, but possible thanks to changes introduced in PEP 573.
To get the state, you need to first get the *defining class*, and then
get the module state from it.
The largest roadblock is getting *the class a method was defined in*, or
that method's “defining class” for short.
The defining class can have a reference to the module it is part of.
It is important to not confuse the defining class with `Py_TYPE(self)`.
If the method is called on a *subclass* of your type, `Py_TYPE(self)`
will refer to that subclass, which may be defined in different module
than yours.
In the following Python example, the defining class of the method
`Base.get_defining_class` is `Base`, even if `type(self) == Sub`:
```python
class Base:
def get_defining_class(self):
return __class__
class Sub(Base):
pass
```
To get its “defining class”, a method must use the `METH_METHOD |
METH_FASTCALL | METH_KEYWORDS` [calling
convention](https://docs.python.org/3.9/c-api/structures.html?highlight=met…
and the corresponding [PyCMethod
signature](https://docs.python.org/3.9/c-api/structures.html#c.PyCMethod):
```c
PyObject *PyCMethod(
PyObject *self, // object the method was called on
PyTypeObject *defining_class, // defining class
PyObject *const *args, // C array of arguments
Py_ssize_t nargs, // length of "args"
PyObject *kwnames) // NULL, or dict of keyword arguments
```
Once you have the defining class, call `PyType_GetModuleState` to get
the state of its associated module.
For example:
```c
static PyObject *
example_method(PyObject *self,
PyTypeObject *defining_class,
PyObject *const *args,
Py_ssize_t nargs,
PyObject *kwnames)
{
my_struct *state = (my_struct*)PyType_GetModuleState(defining_class);
if (state === NULL) {
return NULL;
}
... // rest of logic
}
PyDoc_STRVAR(example_method_doc, "...");
static PyMethodDef my_methods[] = {
{"example_method",
(PyCFunction)(void(*)(void))example_method,
METH_METHOD|METH_FASTCALL|METH_KEYWORDS,
example_method_doc}
{NULL},
}
```
Open Issues
-----------
Several issues around per-module state and heap types are still open.
Discussions about improving the situation are best held on the [capi-sig
mailing list](https://mail.python.org/mailman3/lists/capi-sig.python.org/).
### Module State Access from Slot Methods, Getters and Setters
Currently (as of Python 3.9), there is no API to access the module state
from:
* slot methods (meaning type slots, such as `tp_new`, `nb_add` or
`tp_iternext`)
* getters and setters defined with `tp_getset`
### Type Checking
Currently (as of Python 3.9), there is no good API to write `Py*_Check`
functions (like `PyUnicode_Check` exists for `str`, a static type) for
heap types.
This check ensures whether instances have a particular C layout.
### Metaclasses
Currently (as of Python 3.9), there is no good API to specify the
*metaclass* of a heap type, that is, the `ob_type` field of the type object.
### Per-Class scope
It is also not possible to attach state to *types*.
While `PyHeapTypeObject` is a variable-size object (`PyVarObject`), but
its variable-size storage is currently consumed by slots.
There will also be issues if several classes in an inheritance hierarchy
need state.
Copyright
---------
This document is placed in the public domain or under the
CC0-1.0-Universal license, whichever is more permissive.
..
Local Variables:
mode: indented-text
indent-tabs-mode: nil
sentence-end-double-space: t
fill-column: 70
coding: utf-8
End:
Hi,
I wrote a new script which adds Python 3.10 support to your C
extensions without losing Python 3.6 support:
https://github.com/pythoncapi/pythoncapi_compat
For example, it replaces "op->ob_type" with "Py_TYPE(op)" and replaces
"frame->f_back" with "_PyFrame_GetBackBorrow(frame)".
It relies on the pythoncapi_compat.h header file that I wrote to
implement Python 3.9 and Python 3.10 on old Python versions. Examples:
Py_NewRef() and PyThreadState_GetFrame().
The _PyFrame_GetBackBorrow() function doesn't exist in the Python C
API, it's only provided by pythoncapi_compat.h to ease the migration
of C extensions. I advise you to replace _PyFrame_GetBackBorrow()
(borrowed reference) with PyFrame_GetBack() (strong reference). The
PyFrame_GetBack() function was added to Python 3.9 and
pythoncapi_compat.h provides it on older Python versions.
This project is related to my PEP 620 "Hide implementation details
from the C API" which tries to make the C API more abstract to later
allow to implement new optimization in CPython and to make other
Python implementations like PyPy faster when running C extensions.
This project only targets extension modules written in C by using
directly the "Python.h" API. I advise you to use Cython or HPy to no
longer be bothered with incompatible C API changes at every Python
release ;-)
* https://cython.org/
* https://hpy.readthedocs.io/
I hope that my script will facilitate migration of C extensions to HPy.
Victor
--
Night gathers, and now my watch begins. It shall not end until my death.