Mastering Python Second Edition Release Code
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
import pathlib
|
||||
import setuptools
|
||||
|
||||
# Get the current directory
|
||||
PROJECT_PATH = pathlib.Path(__file__).parent
|
||||
|
||||
# Create the extension object with the references to the C source
|
||||
sum_of_squares = setuptools.Extension('sum_of_squares', sources=[
|
||||
# Get the relative path to sum_of_squares.c
|
||||
str(PROJECT_PATH / 'sum_of_squares.c'),
|
||||
])
|
||||
|
||||
|
||||
def build(setup_kwargs):
|
||||
setup_kwargs['ext_modules'] = [sum_of_squares]
|
||||
@@ -0,0 +1,7 @@
|
||||
import sys
|
||||
import pathlib
|
||||
|
||||
# Little hack to add the current directory to sys.path so we can
|
||||
# find the imports
|
||||
path = pathlib.Path(__file__).parent
|
||||
sys.path.append(str(path.resolve()))
|
||||
@@ -0,0 +1,16 @@
|
||||
[tool.poetry]
|
||||
name = "T_01_pyproject_extensions"
|
||||
version = "0.1.0"
|
||||
description = ""
|
||||
authors = ["Rick van Hattem <Wolph@wol.ph>"]
|
||||
build = "build_extension.py"
|
||||
|
||||
[tool.poetry.dependencies]
|
||||
python = "^3.10"
|
||||
|
||||
[tool.poetry.dev-dependencies]
|
||||
pytest = "^5.2"
|
||||
|
||||
[build-system]
|
||||
requires = ["poetry-core>=1.0.0"]
|
||||
build-backend = "poetry.core.masonry.api"
|
||||
@@ -0,0 +1,49 @@
|
||||
#include <Python.h>
|
||||
|
||||
static PyObject* sum_of_squares(PyObject *self, PyObject
|
||||
*args){
|
||||
/* Declare the variables */
|
||||
int n;
|
||||
int total = 0;
|
||||
|
||||
/* Parse the arguments */
|
||||
if(!PyArg_ParseTuple(args, "i", &n)){
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* The actual summing code */
|
||||
for(int i=0; i<n; i++){
|
||||
if((i * i) < n){
|
||||
total += i * i;
|
||||
}else{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/* Return the number but convert it to a Python object first
|
||||
*/
|
||||
return PyLong_FromLong(total);
|
||||
}
|
||||
|
||||
static PyMethodDef methods[] = {
|
||||
/* Register the function */
|
||||
{"sum_of_squares", sum_of_squares, METH_VARARGS,
|
||||
"Sum the perfect squares below n"},
|
||||
/* Indicate the end of the list */
|
||||
{NULL, NULL, 0, NULL},
|
||||
};
|
||||
|
||||
static struct PyModuleDef module = {
|
||||
PyModuleDef_HEAD_INIT,
|
||||
"sum_of_squares", /* Module name */
|
||||
NULL, /* Module documentation */
|
||||
-1, /* Module state, -1 means global. This parameter is
|
||||
for sub-interpreters */
|
||||
methods,
|
||||
};
|
||||
|
||||
/* Initialize the module */
|
||||
PyMODINIT_FUNC PyInit_sum_of_squares(void){
|
||||
return PyModule_Create(&module);
|
||||
}
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
__version__ = '0.1.0'
|
||||
@@ -0,0 +1,5 @@
|
||||
from t_01_pyproject_extensions import __version__
|
||||
|
||||
|
||||
def test_version():
|
||||
assert __version__ == '0.1.0'
|
||||
Reference in New Issue
Block a user