Yet another attempt at a safe eval() call

Oscar Benjamin oscar.j.benjamin at gmail.com
Sun Jan 6 19:08:07 EST 2013


On 6 January 2013 15:12, Grant Edwards <invalid at invalid.invalid> wrote:
> On 2013-01-05, Oscar Benjamin <oscar.j.benjamin at gmail.com> wrote:
>> On 4 January 2013 15:53, Grant Edwards <invalid at invalid.invalid> wrote:
>>> On 2013-01-04, Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:
>>>> On Thu, 03 Jan 2013 23:25:51 +0000, Grant Edwards wrote:
>>>>
>>>> * But frankly, you should avoid eval, and write your own mini-integer
>>>>   arithmetic evaluator which avoids even the most remote possibility
>>>>   of exploit.
>>>
>>> That's obviously the "right" thing to do.  I suppose I should figure
>>> out how to use the ast module.
>>
>> Someone has already created a module that does this called numexpr. Is
>> there some reason why you don't want to use that?
>
> 1) I didn't know about it, and my Googling didn't find it.
>
> 2) It's not part of the standard library, and my program needs to be
>    distributed as a single source file.

That's an unfortunate restriction. It also won't be possible to reuse
the code from numexpr (for technical rather than legal reasons).
Perhaps asteval will be more helpful in that sense.

Otherwise presumably the shunting-yard algorithm comes out a little
nicer in Python than in C (it would be useful if something like this
were available on PyPI as a pure Python module):
http://en.wikipedia.org/wiki/Shunting_yard_algorithm#C_example


Oscar



More information about the Python-list mailing list