On 5/30/07, Steve Howell showell30@yahoo.com wrote:
--- Steven Bethard steven.bethard@gmail.com wrote:
def rowexpr(expr):
... def evaluate(row): ... d = dict(row) ... d.update(globals()) ... exec '__result__ = ' + expr in d ... return d['__result__'] ... return evaluate ...
[snip]
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:
Not horribly slow.
3.4 seconds on my box for 10000 calls
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
You can get the syntax error a little earlier (at the time of the rowexpr() call) by using compile()::
def rowexpr(expr):
... code = compile('__result__ = ' + expr, '<rowexpr>', 'exec') ... def evaluate(row): ... d = dict(globals()) ... d.update(row) ... exec code in d ... return d['__result__'] ... return evaluate ...
def convert_to_euros(amt):
... return amt / 2 ...
x = rowexpr('convert_to_euros(salary)') row = dict(salary=50000) print x(row)
25000
rowexpr('convert_to_euros(salary) if dept = "foo" else 0')
Traceback (most recent call last): File "<interactive input>", line 1, in <module> File "<interactive input>", line 2, in rowexpr File "<rowexpr>", line 1 __result__ = convert_to_euros(salary) if dept = "foo" else 0 ^ SyntaxError: invalid syntax
STeVe