--- Steven Bethard firstname.lastname@example.org wrote:
... def evaluate(row): ... d = dict(row) ... d.update(globals()) ... exec '__result__ = ' + expr in d ... return d['__result__'] ... return evaluate ...
... return amt / 2 ...
x = rowexpr('convert_to_euros(salary)') row = dict(salary=50000) print x(row)
I tried it out with a slightly more involved expression.
x = rowexpr( 'convert_to_euros(salary) ' 'if dept == "foo" else 0') rows = [dict(dept='foo', salary=i) for i in range(10000)] transform = [x(row) for row in rows]
Here were my findings:
1) Not horribly slow.
3.4 seconds on my box for 10000 calls
2) I introduced a syntax error, and it was more clear than I thought it would be. It happens at runtime, of course, which is less than ideal, and it doesn't directly point me out to the line of code with the syntax error, but it does suggest the error:
File "sql.py", line 14, in <module> transform = [x(row) for row in rows] File "sql.py", line 5, in evaluate exec '__result__ = ' + expr in d File "<string>", line 1 __result__ = convert_to_euros(salary) if dept = "foo" else 0 ^ SyntaxError: invalid syntax
____________________________________________________________________________________ Don't get soaked. Take a quick peak at the forecast with the Yahoo! Search weather shortcut. http://tools.search.yahoo.com/shortcuts/#loc_weather