[Python-ideas] proposal to add rowexpr as a keyword
Steven Bethard
steven.bethard at gmail.com
Thu May 31 07:38:40 CEST 2007
On 5/30/07, Steve Howell <showell30 at yahoo.com> wrote:
> --- Steven Bethard <steven.bethard at 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:
>
> 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
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
--
I'm not *in*-sane. Indeed, I am so far *out* of sane that you appear a
tiny blip on the distant coast of sanity.
--- Bucky Katt, Get Fuzzy
More information about the Python-ideas
mailing list