Skip to content

Cannot use custom extension types in C extensions for free-threading python #126267

@shinyano

Description

@shinyano

Bug report

Bug description:

Python3.13t seems to be unable to use C extensions which use new extension types?

According to chapter 2.1. The Basics in official guide, I wrote 3 files: custom.c, pyproject.toml and setup.py which were identical to the code provided in this tutorial.

In the same location I executed D:\python3.13\python3.13t.exe -m pip install . The extension got installed successfully but when I executed import custom in python3.13t.exe, Python just exited without any output or errors:

C:\Users\zhang>python3.13t
Python 3.13.0 experimental free-threading build (tags/v3.13.0:60403a5, Oct  7 2024, 09:53:29) [MSC v.1941 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import custom

C:\Users\zhang>

Then I tried pip install with stable version of 3.13, and successfully imported custom module:

C:\Users\zhang>D:\python3.13\python.exe
Python 3.13.0 (tags/v3.13.0:60403a5, Oct  7 2024, 09:38:07) [MSC v.1941 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import custom
>>> ^Z

C:\Users\zhang>

I'm using Windows11 and Python3.13, setuptools==75.2.0. The complete code is as follows:

custom.c:

// custom.c

#define PY_SSIZE_T_CLEAN
#include <Python.h>

typedef struct {
    PyObject_HEAD
    /* Type-specific fields go here. */
} CustomObject;

static PyTypeObject CustomType = {
    .ob_base = PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "custom.Custom",
    .tp_doc = PyDoc_STR("Custom objects"),
    .tp_basicsize = sizeof(CustomObject),
    .tp_itemsize = 0,
    .tp_flags = Py_TPFLAGS_DEFAULT,
    .tp_new = PyType_GenericNew,
};

static PyModuleDef custommodule = {
    .m_base = PyModuleDef_HEAD_INIT,
    .m_name = "custom",
    .m_doc = "Example module that creates an extension type.",
    .m_size = -1,
};

PyMODINIT_FUNC
PyInit_custom(void)
{
    PyObject *m;
    if (PyType_Ready(&CustomType) < 0) 
        return NULL;

    m = PyModule_Create(&custommodule);
    if (m == NULL)
        return NULL;

    if (PyModule_AddObjectRef(m, "Custom", (PyObject *) &CustomType) < 0) {
        Py_DECREF(m);
        return NULL;
    }

    return m;
}

pyproject.toml:

[build-system]
requires = ["setuptools"]
build-backend = "setuptools.build_meta"

[project]
name = "custom"
version = "1"

setup.py:

from setuptools import Extension, setup
setup(ext_modules=[Extension("custom", ["custom.c"])])

CPython versions tested on:

3.13

Operating systems tested on:

Windows

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions