Reputation: 893
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
Upvotes: 10
Views: 5718
Reputation: 94
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)
Upvotes: 2