Home > Blockchain >  Cython: Generic function interfacing functions based on call signature
Cython: Generic function interfacing functions based on call signature

Time:03-14

Basically, want to write two functions, then use a third generic function which purely selects which of the two original functions to call with the given arguments based on the input arguments given. eg

cdef fun1(int a):
    #do something

cdef fun1(float a):
    #do something

#roughly stealing syntax from fortran (this is the part I don't know how to do)
interface generic_function:
    function fun1
    function fun2


#Calling the functions
cdef int a = 2
cdef float b = 1.3
generic_function(a) #runs fun1
generic_function(b) #runs fun2

Obviously I could do this with if statements, but that doesn't appear efficient to me. Any and all help is appreciated, cheers.

CodePudding user response:

This can be done with [fused types] (https://cython.readthedocs.io/en/latest/src/userguide/fusedtypes.html)

ctypedef fused int_or_float:
    int
    float

cdef generic_function(int_or_float a):
    if int_or_float is int:
        fun1(a)
    else:
        fun2(a)

The if statement is evaluated when Cython compiles the functions (you can verify this by looking at the generated c code) so is not a performance issue.

  • Related