Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble using eval() with cython

Tags:

python

cython

I was trying to speed up some code, and then I tried compiling a class and a function using cython

and WOW! I havn't measured it yet but it looks at least 10x faster.

I first looked at cython just two days ago, I'm very impressed!

However, I can't get eval() to work.

def thefirst(int a):
    d = eval('1+2+a')
    return d

I compile this to module1.pyd file and call it with the python file:

from module1 import thefirst
x = thefirst(2)
print x

This returns:

NameError: name 'a' is not defined.

All help is appreciated.

like image 749
Peter Stewart Avatar asked Dec 29 '22 21:12

Peter Stewart


2 Answers

This is because eval has no way of examining the environment to find a. Use the locals function to pass it the environment.

def thefirst(a):
    return eval('1+2+a', locals())
like image 100
Dietrich Epp Avatar answered Dec 31 '22 11:12

Dietrich Epp


You may get away with cython.inline:

http://wiki.cython.org/enhancements/inline

However, keep an eye on your Python runtime's memory usage in this case. Each distinct expression that gets compiled and loaded takes up some memory. This may add up if you do this a lot.

like image 25
Stefan Behnel Avatar answered Dec 31 '22 12:12

Stefan Behnel