Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Templated STL containers as argument to function in cython

Tags:

python

cython

I have written a function in cython that will search a STL vector of strings for a given string and return true if it is found, false otherwise. Performance is very important here! I would ideally like to have a templated function to do the same thing so I don't have to write a function for each data type. I am sure this is possible but I don't know the cython syntax for templated functions. (I know how to do it in c++)

from libcpp cimport bool
from libcpp.string cimport string
from libcpp.vector cimport vector
from cython.operator cimport dereference as deref, preincrement as inc

cpdef bool is_in_vector(string a, vector[string] v):
    cdef vector[string].iterator it = v.begin()
    while it != v.end():
        if deref(it) == a:
            return True
        #Increment iterator
        inc(it)
    return False

Can anyone give me a hand?

like image 711
ibell Avatar asked Nov 04 '22 11:11

ibell


1 Answers

Use Fused Types.

Example:

cimport cython

ctypedef fused any:
    string
    cython.int

cpdef bool is_in_vector(string a, vector[any] v)

Or this way:

ctypedef fused vector_t:
    vector[string]
    vector[cython.int]

cpdef bool is_in_vector(string a, vector_t v)
like image 145
Czarek Tomczak Avatar answered Nov 08 '22 06:11

Czarek Tomczak