-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
annoymodule.cc
638 lines (536 loc) · 20.2 KB
/
annoymodule.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
// Copyright (c) 2013 Spotify AB
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
#include "annoylib.h"
#include "kissrandom.h"
#include "Python.h"
#include "structmember.h"
#include <exception>
#if defined(_MSC_VER) && _MSC_VER == 1500
typedef signed __int32 int32_t;
#else
#include <stdint.h>
#endif
#if defined(USE_AVX512)
#define AVX_INFO "Using 512-bit AVX instructions"
#elif defined(USE_AVX128)
#define AVX_INFO "Using 128-bit AVX instructions"
#else
#define AVX_INFO "Not using AVX instructions"
#endif
#if defined(_MSC_VER)
#define COMPILER_INFO "Compiled using MSC"
#elif defined(__GNUC__)
#define COMPILER_INFO "Compiled on GCC"
#else
#define COMPILER_INFO "Compiled on unknown platform"
#endif
#define ANNOY_DOC (COMPILER_INFO ". " AVX_INFO ".")
#if PY_MAJOR_VERSION >= 3
#define IS_PY3K
#endif
#ifndef Py_TYPE
#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
#endif
#ifdef IS_PY3K
#define PyInt_FromLong PyLong_FromLong
#endif
#ifdef ANNOYLIB_MULTITHREADED_BUILD
typedef AnnoyIndexMultiThreadedBuildPolicy AnnoyIndexThreadedBuildPolicy;
#else
typedef AnnoyIndexSingleThreadedBuildPolicy AnnoyIndexThreadedBuildPolicy;
#endif
template class AnnoyIndexInterface<int32_t, float>;
class HammingWrapper : public AnnoyIndexInterface<int32_t, float> {
// Wrapper class for Hamming distance, using composition.
// This translates binary (float) vectors into packed uint64_t vectors.
// This is questionable from a performance point of view. Should reconsider this solution.
private:
int32_t _f_external, _f_internal;
AnnoyIndex<int32_t, uint64_t, Hamming, Kiss64Random, AnnoyIndexThreadedBuildPolicy> _index;
void _pack(const float* src, uint64_t* dst) const {
for (int32_t i = 0; i < _f_internal; i++) {
dst[i] = 0;
for (int32_t j = 0; j < 64 && i*64+j < _f_external; j++) {
dst[i] |= (uint64_t)(src[i * 64 + j] > 0.5) << j;
}
}
};
void _unpack(const uint64_t* src, float* dst) const {
for (int32_t i = 0; i < _f_external; i++) {
dst[i] = (src[i / 64] >> (i % 64)) & 1;
}
};
public:
HammingWrapper(int f) : _f_external(f), _f_internal((f + 63) / 64), _index((f + 63) / 64) {};
bool add_item(int32_t item, const float* w, char**error) {
vector<uint64_t> w_internal(_f_internal, 0);
_pack(w, &w_internal[0]);
return _index.add_item(item, &w_internal[0], error);
};
bool build(int q, int n_threads, char** error) { return _index.build(q, n_threads, error); };
bool unbuild(char** error) { return _index.unbuild(error); };
bool save(const char* filename, bool prefault, char** error) { return _index.save(filename, prefault, error); };
void unload() { _index.unload(); };
bool load(const char* filename, bool prefault, char** error) { return _index.load(filename, prefault, error); };
float get_distance(int32_t i, int32_t j) const { return _index.get_distance(i, j); };
void get_nns_by_item(int32_t item, size_t n, int search_k, vector<int32_t>* result, vector<float>* distances) const {
if (distances) {
vector<uint64_t> distances_internal;
_index.get_nns_by_item(item, n, search_k, result, &distances_internal);
distances->insert(distances->begin(), distances_internal.begin(), distances_internal.end());
} else {
_index.get_nns_by_item(item, n, search_k, result, NULL);
}
};
void get_nns_by_vector(const float* w, size_t n, int search_k, vector<int32_t>* result, vector<float>* distances) const {
vector<uint64_t> w_internal(_f_internal, 0);
_pack(w, &w_internal[0]);
if (distances) {
vector<uint64_t> distances_internal;
_index.get_nns_by_vector(&w_internal[0], n, search_k, result, &distances_internal);
distances->insert(distances->begin(), distances_internal.begin(), distances_internal.end());
} else {
_index.get_nns_by_vector(&w_internal[0], n, search_k, result, NULL);
}
};
int32_t get_n_items() const { return _index.get_n_items(); };
int32_t get_n_trees() const { return _index.get_n_trees(); };
void verbose(bool v) { _index.verbose(v); };
void get_item(int32_t item, float* v) const {
vector<uint64_t> v_internal(_f_internal, 0);
_index.get_item(item, &v_internal[0]);
_unpack(&v_internal[0], v);
};
void set_seed(uint64_t q) { _index.set_seed(q); };
bool on_disk_build(const char* filename, char** error) { return _index.on_disk_build(filename, error); };
};
// annoy python object
typedef struct {
PyObject_HEAD
int f;
AnnoyIndexInterface<int32_t, float>* ptr;
} py_annoy;
static PyObject *
py_an_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) {
py_annoy *self = (py_annoy *)type->tp_alloc(type, 0);
if (self == NULL) {
return NULL;
}
const char *metric = NULL;
static char const * kwlist[] = {"f", "metric", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|s", (char**)kwlist, &self->f, &metric))
return NULL;
if (!metric) {
// This keeps coming up, see #368 etc
PyErr_WarnEx(PyExc_FutureWarning, "The default argument for metric will be removed "
"in future version of Annoy. Please pass metric='angular' explicitly.", 1);
self->ptr = new AnnoyIndex<int32_t, float, Angular, Kiss64Random, AnnoyIndexThreadedBuildPolicy>(self->f);
} else if (!strcmp(metric, "angular")) {
self->ptr = new AnnoyIndex<int32_t, float, Angular, Kiss64Random, AnnoyIndexThreadedBuildPolicy>(self->f);
} else if (!strcmp(metric, "euclidean")) {
self->ptr = new AnnoyIndex<int32_t, float, Euclidean, Kiss64Random, AnnoyIndexThreadedBuildPolicy>(self->f);
} else if (!strcmp(metric, "manhattan")) {
self->ptr = new AnnoyIndex<int32_t, float, Manhattan, Kiss64Random, AnnoyIndexThreadedBuildPolicy>(self->f);
} else if (!strcmp(metric, "hamming")) {
self->ptr = new HammingWrapper(self->f);
} else if (!strcmp(metric, "dot")) {
self->ptr = new AnnoyIndex<int32_t, float, DotProduct, Kiss64Random, AnnoyIndexThreadedBuildPolicy>(self->f);
} else {
PyErr_SetString(PyExc_ValueError, "No such metric");
return NULL;
}
return (PyObject *)self;
}
static int
py_an_init(py_annoy *self, PyObject *args, PyObject *kwargs) {
// Seems to be needed for Python 3
const char *metric = NULL;
int f;
static char const * kwlist[] = {"f", "metric", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|s", (char**)kwlist, &f, &metric))
return (int) NULL;
return 0;
}
static void
py_an_dealloc(py_annoy* self) {
delete self->ptr;
Py_TYPE(self)->tp_free((PyObject*)self);
}
static PyMemberDef py_annoy_members[] = {
{(char*)"f", T_INT, offsetof(py_annoy, f), 0,
(char*)""},
{NULL} /* Sentinel */
};
static PyObject *
py_an_load(py_annoy *self, PyObject *args, PyObject *kwargs) {
char *filename, *error;
bool prefault = false;
if (!self->ptr)
return NULL;
static char const * kwlist[] = {"fn", "prefault", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|b", (char**)kwlist, &filename, &prefault))
return NULL;
if (!self->ptr->load(filename, prefault, &error)) {
PyErr_SetString(PyExc_IOError, error);
free(error);
return NULL;
}
Py_RETURN_TRUE;
}
static PyObject *
py_an_save(py_annoy *self, PyObject *args, PyObject *kwargs) {
char *filename, *error;
bool prefault = false;
if (!self->ptr)
return NULL;
static char const * kwlist[] = {"fn", "prefault", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|b", (char**)kwlist, &filename, &prefault))
return NULL;
if (!self->ptr->save(filename, prefault, &error)) {
PyErr_SetString(PyExc_IOError, error);
free(error);
return NULL;
}
Py_RETURN_TRUE;
}
PyObject*
get_nns_to_python(const vector<int32_t>& result, const vector<float>& distances, int include_distances) {
PyObject* l = PyList_New(result.size());
for (size_t i = 0; i < result.size(); i++)
PyList_SetItem(l, i, PyInt_FromLong(result[i]));
if (!include_distances)
return l;
PyObject* d = PyList_New(distances.size());
for (size_t i = 0; i < distances.size(); i++)
PyList_SetItem(d, i, PyFloat_FromDouble(distances[i]));
PyObject* t = PyTuple_New(2);
PyTuple_SetItem(t, 0, l);
PyTuple_SetItem(t, 1, d);
return t;
}
bool check_constraints(py_annoy *self, int32_t item, bool building) {
if (item < 0) {
PyErr_SetString(PyExc_IndexError, "Item index can not be negative");
return false;
} else if (!building && item >= self->ptr->get_n_items()) {
PyErr_SetString(PyExc_IndexError, "Item index larger than the largest item index");
return false;
} else {
return true;
}
}
static PyObject*
py_an_get_nns_by_item(py_annoy *self, PyObject *args, PyObject *kwargs) {
int32_t item, n, search_k=-1, include_distances=0;
if (!self->ptr)
return NULL;
static char const * kwlist[] = {"i", "n", "search_k", "include_distances", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "ii|ii", (char**)kwlist, &item, &n, &search_k, &include_distances))
return NULL;
if (!check_constraints(self, item, false)) {
return NULL;
}
vector<int32_t> result;
vector<float> distances;
Py_BEGIN_ALLOW_THREADS;
self->ptr->get_nns_by_item(item, n, search_k, &result, include_distances ? &distances : NULL);
Py_END_ALLOW_THREADS;
return get_nns_to_python(result, distances, include_distances);
}
bool
convert_list_to_vector(PyObject* v, int f, vector<float>* w) {
if (PyObject_Size(v) == -1) {
char buf[256];
snprintf(buf, 256, "Expected an iterable, got an object of type \"%s\"", v->ob_type->tp_name);
PyErr_SetString(PyExc_ValueError, buf);
return false;
}
if (PyObject_Size(v) != f) {
char buf[128];
snprintf(buf, 128, "Vector has wrong length (expected %d, got %ld)", f, PyObject_Size(v));
PyErr_SetString(PyExc_IndexError, buf);
return false;
}
for (int z = 0; z < f; z++) {
PyObject *key = PyInt_FromLong(z);
PyObject *pf = PyObject_GetItem(v, key);
(*w)[z] = PyFloat_AsDouble(pf);
Py_DECREF(key);
Py_DECREF(pf);
}
return true;
}
static PyObject*
py_an_get_nns_by_vector(py_annoy *self, PyObject *args, PyObject *kwargs) {
PyObject* v;
int32_t n, search_k=-1, include_distances=0;
if (!self->ptr)
return NULL;
static char const * kwlist[] = {"vector", "n", "search_k", "include_distances", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Oi|ii", (char**)kwlist, &v, &n, &search_k, &include_distances))
return NULL;
vector<float> w(self->f);
if (!convert_list_to_vector(v, self->f, &w)) {
return NULL;
}
vector<int32_t> result;
vector<float> distances;
Py_BEGIN_ALLOW_THREADS;
self->ptr->get_nns_by_vector(&w[0], n, search_k, &result, include_distances ? &distances : NULL);
Py_END_ALLOW_THREADS;
return get_nns_to_python(result, distances, include_distances);
}
static PyObject*
py_an_get_item_vector(py_annoy *self, PyObject *args) {
int32_t item;
if (!self->ptr)
return NULL;
if (!PyArg_ParseTuple(args, "i", &item))
return NULL;
if (!check_constraints(self, item, false)) {
return NULL;
}
vector<float> v(self->f);
self->ptr->get_item(item, &v[0]);
PyObject* l = PyList_New(self->f);
for (int z = 0; z < self->f; z++) {
PyList_SetItem(l, z, PyFloat_FromDouble(v[z]));
}
return l;
}
static PyObject*
py_an_add_item(py_annoy *self, PyObject *args, PyObject* kwargs) {
PyObject* v;
int32_t item;
if (!self->ptr)
return NULL;
static char const * kwlist[] = {"i", "vector", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "iO", (char**)kwlist, &item, &v))
return NULL;
if (!check_constraints(self, item, true)) {
return NULL;
}
vector<float> w(self->f);
if (!convert_list_to_vector(v, self->f, &w)) {
return NULL;
}
char* error;
if (!self->ptr->add_item(item, &w[0], &error)) {
PyErr_SetString(PyExc_Exception, error);
free(error);
return NULL;
}
Py_RETURN_NONE;
}
static PyObject *
py_an_on_disk_build(py_annoy *self, PyObject *args, PyObject *kwargs) {
char *filename, *error;
if (!self->ptr)
return NULL;
static char const * kwlist[] = {"fn", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s", (char**)kwlist, &filename))
return NULL;
if (!self->ptr->on_disk_build(filename, &error)) {
PyErr_SetString(PyExc_IOError, error);
free(error);
return NULL;
}
Py_RETURN_TRUE;
}
static PyObject *
py_an_build(py_annoy *self, PyObject *args, PyObject *kwargs) {
int q;
int n_jobs = -1;
if (!self->ptr)
return NULL;
static char const * kwlist[] = {"n_trees", "n_jobs", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|i", (char**)kwlist, &q, &n_jobs))
return NULL;
bool res;
char* error;
Py_BEGIN_ALLOW_THREADS;
res = self->ptr->build(q, n_jobs, &error);
Py_END_ALLOW_THREADS;
if (!res) {
PyErr_SetString(PyExc_Exception, error);
free(error);
return NULL;
}
Py_RETURN_TRUE;
}
static PyObject *
py_an_unbuild(py_annoy *self) {
if (!self->ptr)
return NULL;
char* error;
if (!self->ptr->unbuild(&error)) {
PyErr_SetString(PyExc_Exception, error);
free(error);
return NULL;
}
Py_RETURN_TRUE;
}
static PyObject *
py_an_unload(py_annoy *self) {
if (!self->ptr)
return NULL;
self->ptr->unload();
Py_RETURN_TRUE;
}
static PyObject *
py_an_get_distance(py_annoy *self, PyObject *args) {
int32_t i, j;
if (!self->ptr)
return NULL;
if (!PyArg_ParseTuple(args, "ii", &i, &j))
return NULL;
if (!check_constraints(self, i, false) || !check_constraints(self, j, false)) {
return NULL;
}
double d = self->ptr->get_distance(i,j);
return PyFloat_FromDouble(d);
}
static PyObject *
py_an_get_n_items(py_annoy *self) {
if (!self->ptr)
return NULL;
int32_t n = self->ptr->get_n_items();
return PyInt_FromLong(n);
}
static PyObject *
py_an_get_n_trees(py_annoy *self) {
if (!self->ptr)
return NULL;
int32_t n = self->ptr->get_n_trees();
return PyInt_FromLong(n);
}
static PyObject *
py_an_verbose(py_annoy *self, PyObject *args) {
int verbose;
if (!self->ptr)
return NULL;
if (!PyArg_ParseTuple(args, "i", &verbose))
return NULL;
self->ptr->verbose((bool)verbose);
Py_RETURN_TRUE;
}
static PyObject *
py_an_set_seed(py_annoy *self, PyObject *args) {
int q;
if (!self->ptr)
return NULL;
if (!PyArg_ParseTuple(args, "i", &q))
return NULL;
self->ptr->set_seed(q);
Py_RETURN_NONE;
}
static PyMethodDef AnnoyMethods[] = {
{"load", (PyCFunction)py_an_load, METH_VARARGS | METH_KEYWORDS, "Loads (mmaps) an index from disk."},
{"save", (PyCFunction)py_an_save, METH_VARARGS | METH_KEYWORDS, "Saves the index to disk."},
{"get_nns_by_item",(PyCFunction)py_an_get_nns_by_item, METH_VARARGS | METH_KEYWORDS, "Returns the `n` closest items to item `i`.\n\n:param search_k: the query will inspect up to `search_k` nodes.\n`search_k` gives you a run-time tradeoff between better accuracy and speed.\n`search_k` defaults to `n_trees * n` if not provided.\n\n:param include_distances: If `True`, this function will return a\n2 element tuple of lists. The first list contains the `n` closest items.\nThe second list contains the corresponding distances."},
{"get_nns_by_vector",(PyCFunction)py_an_get_nns_by_vector, METH_VARARGS | METH_KEYWORDS, "Returns the `n` closest items to vector `vector`.\n\n:param search_k: the query will inspect up to `search_k` nodes.\n`search_k` gives you a run-time tradeoff between better accuracy and speed.\n`search_k` defaults to `n_trees * n` if not provided.\n\n:param include_distances: If `True`, this function will return a\n2 element tuple of lists. The first list contains the `n` closest items.\nThe second list contains the corresponding distances."},
{"get_item_vector",(PyCFunction)py_an_get_item_vector, METH_VARARGS, "Returns the vector for item `i` that was previously added."},
{"add_item",(PyCFunction)py_an_add_item, METH_VARARGS | METH_KEYWORDS, "Adds item `i` (any nonnegative integer) with vector `v`.\n\nNote that it will allocate memory for `max(i)+1` items."},
{"on_disk_build",(PyCFunction)py_an_on_disk_build, METH_VARARGS | METH_KEYWORDS, "Build will be performed with storage on disk instead of RAM."},
{"build",(PyCFunction)py_an_build, METH_VARARGS | METH_KEYWORDS, "Builds a forest of `n_trees` trees.\n\nMore trees give higher precision when querying. After calling `build`,\nno more items can be added. `n_jobs` specifies the number of threads used to build the trees. `n_jobs=-1` uses all available CPU cores."},
{"unbuild",(PyCFunction)py_an_unbuild, METH_NOARGS, "Unbuilds the tree in order to allows adding new items.\n\nbuild() has to be called again afterwards in order to\nrun queries."},
{"unload",(PyCFunction)py_an_unload, METH_NOARGS, "Unloads an index from disk."},
{"get_distance",(PyCFunction)py_an_get_distance, METH_VARARGS, "Returns the distance between items `i` and `j`."},
{"get_n_items",(PyCFunction)py_an_get_n_items, METH_NOARGS, "Returns the number of items in the index."},
{"get_n_trees",(PyCFunction)py_an_get_n_trees, METH_NOARGS, "Returns the number of trees in the index."},
{"verbose",(PyCFunction)py_an_verbose, METH_VARARGS, ""},
{"set_seed",(PyCFunction)py_an_set_seed, METH_VARARGS, "Sets the seed of Annoy's random number generator."},
{NULL, NULL, 0, NULL} /* Sentinel */
};
static PyTypeObject PyAnnoyType = {
PyVarObject_HEAD_INIT(NULL, 0)
"annoy.Annoy", /*tp_name*/
sizeof(py_annoy), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)py_an_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
ANNOY_DOC, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
AnnoyMethods, /* tp_methods */
py_annoy_members, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)py_an_init, /* tp_init */
0, /* tp_alloc */
py_an_new, /* tp_new */
};
static PyMethodDef module_methods[] = {
{NULL} /* Sentinel */
};
#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"annoylib", /* m_name */
ANNOY_DOC, /* m_doc */
-1, /* m_size */
module_methods, /* m_methods */
NULL, /* m_reload */
NULL, /* m_traverse */
NULL, /* m_clear */
NULL, /* m_free */
};
#endif
PyObject *create_module(void) {
PyObject *m;
if (PyType_Ready(&PyAnnoyType) < 0)
return NULL;
#if PY_MAJOR_VERSION >= 3
m = PyModule_Create(&moduledef);
#else
m = Py_InitModule("annoylib", module_methods);
#endif
if (m == NULL)
return NULL;
Py_INCREF(&PyAnnoyType);
PyModule_AddObject(m, "Annoy", (PyObject *)&PyAnnoyType);
return m;
}
#if PY_MAJOR_VERSION >= 3
PyMODINIT_FUNC PyInit_annoylib(void) {
return create_module(); // it should return moudule object in py3
}
#else
PyMODINIT_FUNC initannoylib(void) {
create_module();
}
#endif
// vim: tabstop=2 shiftwidth=2