I want to use lambda expression with cython but it is not working with cpdef. The error says that it is not yet supported, but cython changeleg says that lambda expressions are supported.
%%cython
cimport numpy as np
import numpy as np
cdef foo():
a = np.random.randint(1,10,10)
b = sorted(a, key = lambda x: x%np.pi) #Compiles
return(b)
cpdef goo():
a = np.random.randint(1,10,10)
b = sorted(a) #Compiles
return(b)
cpdef hoo():
a = np.random.randint(1,10,10)
b = sorted(a, key = lambda x: x%np.pi) #Compile time error
return(b)
Error compiling Cython file:
------------------------------------------------------------
...
cpdef goo():
a = np.random.randint(1,10,10)
b = sorted(a)
return(b)
cpdef hoo():
^
------------------------------------------------------------
/********/.cache/ipython/cython/_cython_magic_63378538fa4250ed3135e0289d6af7a0.pyx:14:6: closures inside cpdef functions not yet supported
Is it indeed the case that lambda expressions are not supported or am I missing something?
Python version 3.5.5; Cython version: 0.24
A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression.
This only about closures inside cpdef methods. If you do not define any function inside cpdef function, i.e closures, this would work. Lambda expression is just a functions, but with specific syntax. Try this.
def sort_key(x):
return x%np.pi
cpdef hoo():
a = np.random.randint(1,10,10)
b = sorted(a, key = sort_key)
return(b)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With