How is correct use of eval()

Nobody nobody at nowhere.com
Tue Oct 12 03:35:28 CEST 2010


On Tue, 12 Oct 2010 01:26:25 +0100, Nobody wrote:

>>> What is correct way to use this function?
>> 
>> To not use it in the first place if at all possible (use int(),
>> float(), getattr(), etc. instead,
> 
> Use read(). Oh wait, Python doesn't have that. Because parsing literals
> and executing code are like totally the same thing.

Oh, look what's "new in version 2.6":

	> ast.literal_eval("7")
	7
	> ast.literal_eval("7") == 7
	True

ast.literal_eval(node_or_string)

    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, numbers, tuples, lists,
    dicts, booleans, and None. 

    This can be used for safely evaluating strings containing Python
    expressions from untrusted sources without the need to parse the
    values oneself. 

I'm guessing that I'm not the only person who hasn't noticed this until
now.




More information about the Python-list mailing list