6.3. Performance CModules

6.3.1. Code

Przykład kodu w C wykorzystującego C modules:

#include <Python.h>

/* Implementation */

static PyObject* say_hello(PyObject* self, PyObject* args) {
    const char* name;

    if (!PyArg_ParseTuple(args, "s", &name))
        return NULL;

    printf("Hello %s!\n", name);
    Py_RETURN_NONE;
}

static PyObject* version(PyObject* self) {
    return Py_BuildValue("s", "Version 1.0");
}


/* Python Binding Definitions */

static PyMethodDef HelloMethods[] = {
     {"say_hello", say_hello, METH_VARARGS, "Greet somebody."},
     {"version", (PyCFunction)version, METH_NOARGS, "returns the version"},
     {NULL, NULL, 0, NULL}
};

static struct PyModuleDef hello = {
    PyModuleDef_HEAD_INIT,
    "hello",                        /* name of module */
    "",                                     /* module documentation, may be NULL */
    -1,                                     /* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */
    HelloMethods
};

PyMODINIT_FUNC PyInit_hello(void) {
    return PyModule_Create(&hello);
}

6.3.2. Compile

setup.py:

>>> import sys
>>> from distutils.core import setup, Extension
>>>
>>> print('Building for Python 3')
Building for Python 3
>>> module = Extension('hello', sources = ['mylib-cmodules.c'])
>>>
>>> setup(
...     name = 'hello',
...     version='1.0',
...     description = 'Ehlo World!',
...     ext_modules = [module])  

Execute:

$ python setup.py build
$ cd build/lib*
$ python

Run:

>>> import hello  
>>>
>>>
>>> hello.say_hello('José Jiménez')  
José Jiménez

6.3.3. Assignments

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: C Modules
# - Difficulty: medium
# - Lines: 10
# - Minutes: 13

# %% English
# 1. Create C Module with function `factorial` that calculates factorial of a number
# 2. Using C Modules compile function to Python module
# 3. Run doctests - all must succeed

# %% Polish
# 1. Stwórz moduł C z funkcją `factorial` obliczającą silnię liczby
# 2. Wykorzystując C Modules skompiluj funkcję do modułu Pythona
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
"""