Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda expression in cython function

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

like image 491
Manish Goel Avatar asked Apr 26 '18 12:04

Manish Goel


People also ask

What is lambda expression in Python?

A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression.


1 Answers

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)
like image 193
Кирилл Солодских Avatar answered Sep 27 '22 20:09

Кирилл Солодских