Skip to content

Commit

Permalink
Fix Python 3.12 compatibility
Browse files Browse the repository at this point in the history
Summary:
use the C API patched in 3.12 in D52642782 when compiling for 3.12 instead of the no-longer-available `_Py_PackageContext` symbol.
also stop using `_PyImport_FindExtensionObject` in favor of the public `PyImport_GetModule`.

Reviewed By: zsol

Differential Revision: D52643539

fbshipit-source-id: a1955f93fd565a7891cc6160cbd1760a83319eb4
  • Loading branch information
itamaro authored and facebook-github-bot committed Jan 12, 2024
1 parent 5139ee3 commit a8481f3
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions prelude/python/tools/static_extension_utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,13 @@ namespace {
static PyObject* _create_module(PyObject* self, PyObject* spec) {
PyObject* name;
PyObject* mod;
const char* oldcontext;

name = PyObject_GetAttrString(spec, "name");
if (name == nullptr) {
return nullptr;
}

// TODO private api usage
mod = _PyImport_FindExtensionObject(name, name);
mod = PyImport_GetModule(name);
if (mod || PyErr_Occurred()) {
Py_DECREF(name);
Py_XINCREF(mod);
Expand All @@ -58,7 +56,15 @@ static PyObject* _create_module(PyObject* self, PyObject* spec) {

PyObject* modules = nullptr;
PyModuleDef* def;
oldcontext = _Py_PackageContext;

#if PY_VERSION_HEX >= 0x030C0000
// Use our custom Python 3.12 C-API to call the statically linked module init
// function
mod = _Ci_PyImport_CallInitFuncWithContext(namestr.c_str(), initfunc);
#else
// In Python 3.10 (and earlier) we need to handle package context swapping
// ourselves
const char* oldcontext = _Py_PackageContext;
_Py_PackageContext = namestr.c_str();
if (_Py_PackageContext == nullptr) {
_Py_PackageContext = oldcontext;
Expand All @@ -67,6 +73,7 @@ static PyObject* _create_module(PyObject* self, PyObject* spec) {
}
mod = initfunc();
_Py_PackageContext = oldcontext;
#endif
if (mod == nullptr) {
Py_DECREF(name);
return nullptr;
Expand Down

0 comments on commit a8481f3

Please sign in to comment.