Transforming a str to an operator

Duke Normandin dukeofperl at ml1.net
Fri Aug 28 10:23:16 EDT 2009


On Fri, 28 Aug 2009, Ben Finney wrote:

> Duke Normandin <dukeofperl at ml1.net> writes:
>
> > Hey....
> >
> > I'm a Python noob....
> >
> > So far so good!
> >
> > I've written the following:
> >
> > num1 = raw_input('Enter the first number: ')
> > num2 = raw_input('Enter the second number: ')
> > op = raw_input('Select one of the following [+-*/]: ')
> > print 'The answer is: ', int(num1), eval(op), int(num2)
> >                                     ^^^^^^^^
> >
> > How do I convert the contents of "op" from a string to an actual
> > arithmetic operator? eval() does not seem to be the answer. TIA!
>
> In general, ‘eval’ on unsanitised input is not the answer.

Agreed! If I were to expose "eval" to the 'net, I would have some
input error checking and "type" checks to insure that only integers
and valid operators were being input.

>
> I would use the following approach:
>
>     import operator
>
>     op_funcs = {
>         '+': operator.add,
>         '-': operator.sub,
>         '*': operator.mul,
>         '/': operator.div,
>         }
>
>     num_1 = int(raw_input('Enter the first number: '))
>     num_2 = int(raw_input('Enter the second number: '))
>     op_prompt = (
>         "Select an operator "
>         + "[" + "".join(s for s in op_funcs.keys()) + "]"
>         + ": ")
>     op_symbol = raw_input(op_prompt)
>     op_func = op_funcs[op_symbol]
>     print 'The answer is: ', op_func(num_1, num_2)
>
> This has several advantages:
>
> * The input isn't evaluated directly as code.
>
> * The operator symbols are specified in one place, the ‘op_funcs’
>   mapping; if you want to change the set of possible operators, you just
>   change it there.
>
> * If the input results in an operator that's not defined, it won't
>   attempt to perform it; instead, a simple KeyError will result when
>   trying to find the corresponding operator function.

Cool! Something useful to study...

Thanks for the input!
-- 
duke


More information about the Python-list mailing list