Problem using eval () with cython

I tried to speed up some code and then tried to compile the class and function using cython

and WOW! I haven't rated it yet, but it looks at least 10 times faster.

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

However, I cannot get eval () to work.

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

I compile this into the 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.

+4
source share
3 answers

This is because eval unable to examine the environment to find a . Use the locals function to pass the environment to it.

 def thefirst(a): return eval('1+2+a', locals()) 
+6
source

You can get away with cython.inline:

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

However, watch out for memory usage in Python runtime in this case. Each individual expression that is compiled and loaded takes up some memory. It can add up if you do it a lot.

+3
source

Hmm, I would have thought that eval would be bad for performance anyway. What is your actual use case?

-1
source

Source: https://habr.com/ru/post/1306187/


All Articles