Is this a safe use of eval?

Paul Rubin at nospam.invalid
Thu Feb 24 09:58:37 CET 2011

"Frank Millman" <frank at> writes:
> I then receive my_string  = 'calc_area(100, 200)'.
>>>> result = eval('my_inst.{0}'.format(my_string))
> This will only work if the string contains a valid method name with
> valid arguments.
> Can anyone see anything wrong with this?

Um, yes.  What are valid arguments?  Are you going to eval them?

If they can only be literals, maybe you could use something like

   from ast import literal_eval
   method_name = 'calc_area'
   args = literal_eval('(100,200)')
   result = getattr(my_inst, method_name)(*args)

but even that is risky in a hostile data environment.

More information about the Python-list mailing list