MCPcopy Create free account
hub / github.com/bslatkin/effectivepython / dot_product

Function dot_product

example_code/item_096/my_extension2/dot_product.c:19–78  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

17#include "my_extension2.h"
18
19PyObject *dot_product(PyObject *self, PyObject *args)
20{
21 PyObject *left, *right;
22 if (!PyArg_ParseTuple(args, "OO", &left, &right)) {
23 return NULL;
24 }
25 PyObject *left_iter = PyObject_GetIter(left);
26 if (left_iter == NULL) {
27 return NULL;
28 }
29 PyObject *right_iter = PyObject_GetIter(right);
30 if (right_iter == NULL) {
31 Py_DECREF(left_iter);
32 return NULL;
33 }
34
35 PyObject *left_item = NULL;
36 PyObject *right_item = NULL;
37 PyObject *multiplied = NULL;
38 PyObject *result = PyLong_FromLong(0);
39
40 while (1) {
41 Py_CLEAR(left_item);
42 Py_CLEAR(right_item);
43 Py_CLEAR(multiplied);
44 left_item = PyIter_Next(left_iter);
45 right_item = PyIter_Next(right_iter);
46
47 if (left_item == NULL && right_item == NULL) {
48 break;
49 } else if (left_item == NULL || right_item == NULL) {
50 PyErr_SetString(PyExc_ValueError, "Arguments had unequal length");
51 break;
52 }
53
54 multiplied = PyNumber_Multiply(left_item, right_item);
55 if (multiplied == NULL) {
56 break;
57 }
58 PyObject *added = PyNumber_Add(result, multiplied);
59 if (added == NULL) {
60 break;
61 }
62 Py_CLEAR(result);
63 result = added;
64 }
65
66 Py_CLEAR(left_item);
67 Py_CLEAR(right_item);
68 Py_CLEAR(multiplied);
69 Py_DECREF(left_iter);
70 Py_DECREF(right_iter);
71
72 if (PyErr_Occurred()) {
73 Py_CLEAR(result);
74 return NULL;
75 }
76

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected