Is this a safe use of eval?

Nobody nobody at nowhere.com
Fri Feb 25 00:15:27 EST 2011


On Thu, 24 Feb 2011 15:24:51 +0200, Frank Millman wrote:

> Thanks, Christian. I had a look at that recipe, but I must say that Paul's 
> suggestion is much simpler -
> 
>    from ast import literal_eval
>    method_name = 'calc_area'
>    args = literal_eval('(100,200)')
>    result = getattr(my_inst, method_name)(*args)
> 
> In my case the arguments are all strings or integers, so it looks as if this 
> approach should be safe. Do you see any problem with it?

Only that you may need a fairly recent version of the ast module; the
first attempt at literal_eval was a bit too ... literal, e.g. it couldn't
handle negative numbers (Python doesn't have negative integer literals;
evaluating "-10" applies the negation operator to the integer 10).





More information about the Python-list mailing list