Frank Millman a écrit ce jeudi 24 février 2011 09:48 dans
<mailman.366.1298537346.1189.python-> :
> Hi all
>
> I know that the use of 'eval' is discouraged because of the dangers of
> executing untrusted code.
>
> Here is a variation that seems safe to me, but I could be missing
> something.
>
> I have a class, and the class has one or more methods which accept various
> arguments and return a result.
>
> I want to accept a method name and arguments in string form, and 'eval' it
> to get the result.
>
> Assume I have an instance called my_inst, and a method called 'calc_area',
> with arguments w and h.
>
> 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.
I'd do it that way:
>>> class My_Class(object):
.... def calc_area(self, a, b):
.... return a*b
....
>>> my_inst = My_Class()
>>> my_string = 'calc_area(100, 200)'
>>> my_func_and_args = my_string.split('(')
>>> my_func = my_func_and_args.pop(0)
>>> my_args = my_func_and_args[0].strip(')')
>>> my_args = my_args.split(',')
>>> my_args = [int(arg) for arg in my_args]
>>> if hasattr(my_inst, my_func):
.... getattr(my_inst,my_func)(*my_args)
....
20000
And no eval is ever performed.
--
Web Dreamer
|