Question about ast.literal_eval

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon May 20 04:15:59 EDT 2013


On Mon, 20 May 2013 10:55:35 +0300, Carlos Nepomuceno wrote:

> I understand your motivation but I don't know what protection
> ast.literal_eval() is offering that eval() doesn't.

eval will evaluate any legal Python expression:


py> eval("__import__('os').system('echo Mwahaha! Now you are pwned!') or 42")
Mwahaha! And now you are pwned!
42


ast.literal_eval() does exactly what the name says: it will evaluate any 
legal Python LITERAL, including ints, floats, lists, dicts and strings,
but not arbitrary expressions.


py> ast.literal_eval('123')
123
py> ast.literal_eval('[123, None, "spam"]')
[123, None, 'spam']



-- 
Steven



More information about the Python-list mailing list