Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any type for function in Cython?

Is there any way to tell Cython compiler that param is function. Something like

  cpdef float calc_class_re(list data, func callback)
like image 609
xander27 Avatar asked Jan 02 '13 14:01

xander27


People also ask

Does Cython use type hints?

Cython uses type hints (although mostly its own peculiar breed of them) to generate C code from Python, and the mypyc project uses Python's native type hinting to do the same.

Is Cython object oriented?

Cython is fast at the same time provides flexibility of being object-oriented, functional, and dynamic programming language. One of the key aspects of Cython include optional static type declarations which comes out of the box.

Why is Cython faster?

Cython allows native C functions, which have less overhead than Python functions when they are called, and therefore execute faster.

What is Nogil?

The nogil function annotation declares that it is safe to call the function without the GIL. It is perfectly allowed to execute it while holding the GIL. The function does not in itself release the GIL if it is held by the caller.


1 Answers

Should be self-explanatory..? :)

# Define a new type for a function-type that accepts an integer and
# a string, returning an integer.
ctypedef int (*f_type)(int, str)

# Extern a function of that type from foo.h
cdef extern from "foo.h":
    int do_this(int, str)

# Passing this function will not work.
cpdef int do_that(int a, str b):
    return 0

# However, this will work.
cdef int do_stuff(int a, str b):
    return 0

# This functio uses a function of that type. Note that it cannot be a
# cpdef function because the function-type is not available from Python.
cdef void foo(f_type f):
    print f(0, "bar")

# Works:
foo(do_this)   # the externed function
foo(do_stuff)  # the cdef function

# Error:
# Cannot assign type 'int (int, str, int __pyx_skip_dispatch)' to 'f_type'
foo(do_that)   # the cpdef function
like image 188
Niklas R Avatar answered Oct 08 '22 22:10

Niklas R