Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use a fused type that is not a function argument?

Tags:

python

cython

Consider the following cython snippet:

ctypedef fused number:
    int
    double

cdef void some_function(void *in_, void *out):
    cdef number *fin = <number *> in_
    cdef number *fout = <number *> out
    if number is int:
        fout[0] = fin[0] + fin[1]
    else:
        fout[0] = fin[0] * fin[1]

Trying to cythonize this throws:

Invalid use of fused types, type cannot be specialized

One way of working around this is adding the fused type to the function's signature:

cdef void some_function(void *in_, void *out, number *dummy):
...
etc.

This will translate fine, but is extremely ugly and unsatisfactory.

Is there a better way?

like image 478
Paul Panzer Avatar asked Oct 28 '25 09:10

Paul Panzer


1 Answers

My understanding of the Cython code is very limited, but I found no evidence that it is possible to define a fused function without at least one fused type in its arguments.

For example in FusedNode.py it says:

This node replaces a function with fused arguments.

I was not able to find any tests with fused types only inside of a function in the test suite and as you well know there is nothing about it in the documentation.

Naturally, absence of a proof isn't a proof of absence. I hope somebody will prove me wrong. In the meantime I would use your work around with a slight adjustment - I would pick the type via indexing rather then really passing a variable:

%%cython
cdef void some_function(number *dummy=NULL):
    if number is int:
        print("I'm int")
    else:
        print("I'm float")

def call_it():
    some_function[double]() #picking via the type indexing 

For def functions one could (mis)use typed memory views:

%%cython 
def other_function(number[:] dummy=None):
    if number is int:
        print("I'm int")
    else:
        print("I'm float")

and now:

import cython
other_function[cython.int]()
like image 151
ead Avatar answered Oct 31 '25 13:10

ead



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!