tags:

views:

66

answers:

2

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.

+3  A: 

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())
Dietrich Epp
That did the trick, thanks
Peter Stewart
A: 

Hmm, I'd think eval would be fairly bad for performance in any case. What is your actual use case?

SamB
The program generates random expressions and then selects amongst them for fitness in equaling a given expression. (genetic programming) So I have expressiongs like "(2/((3*(x+4)-5)/6))", sometimes 100 to 150 terms long. Eval() is pretty handy there. But I'm a beginner and I can learn from any suggestions.
Peter Stewart