Question about ast.literal_eval

Frank Millman frank at chagford.com
Mon May 20 04:15:49 EDT 2013


On 20/05/2013 09:55, Carlos Nepomuceno wrote:
> ----------------------------------------
>>>
>>> Why don't you use eval()?
>>>
>>
>> Because users can create their own columns, with their own constraints.
>> Therefore the string is user-modifiable, so it cannot be trusted.
>
> I understand your motivation but I don't know what protection ast.literal_eval() is offering that eval() doesn't.
>

Quoting from the manual -

"Safely evaluate an expression node or a string containing a Python 
expression. The string or node provided may only consist of the 
following Python literal structures: strings, bytes, numbers, tuples, 
lists, dicts, sets, booleans, and None."

The operative word is 'safely'. I don't know the details, but it 
prevents the kinds of exploits that can be carried out by malicious code 
using eval().

I believe it is the same problem as SQL injection, which is solved by 
using parameterised queries.

Frank





More information about the Python-list mailing list