python - Isn't using eval() with a dictionary a better way in this case? -


the 2 functions below perform arithmetic operation on 2 integers , return integer result.

i've heard lot eval() being bad use because can cause many problems. taking @ code i've written below, seems eval() spares many lines of code, right?

def dict_calculate(operation, num1, num2):     operations = {'add': '+', 'subtract': '-', 'multiply': '*', 'divide': '//'}     return eval(str(num1) + operations[operation] + str(num2))  def conditional_calculate(operation, num1, num2):     if operation == 'add':         return num1 + num2     if operation == 'subtract':         return num1 - num2     if operation == 'multiply':         return num1 * num2     if operation == 'divide':         return num1 // num2  if __name__ == "__main__":     x = 10     y = 5      print(str(dict_calculate('add', x, y)) + ', ', end='')     print(str(dict_calculate('subtract', x, y)) + ', ', end='')     print(str(dict_calculate('multiply', x, y)) + ', ', end='')     print(str(dict_calculate('divide', x, y)))      print(str(conditional_calculate('add', x, y)) + ', ', end='')     print(str(conditional_calculate('subtract', x, y)) + ', ', end='')     print(str(conditional_calculate('multiply', x, y)) + ', ', end='')     print(str(conditional_calculate('divide', x, y))) 

outputs same both functions

15, 5, 50, 2 15, 5, 50, 2 

isn't eval best use in type of case? if not, there better way eval() achieve same type of code-efficiency?

thanks lot.

you can this:

import operator def dict_calculate(operation, num1, num2):     operations = {'add': operator.add,                   'subtract': operator.sub,                   'multiply': operator.mul,                   'divide': operator.floordiv}     return operations[operation](num1, num2) 

if don't want import module, can this:

def dict_calculate(operation, num1, num2):     operations = {'add': '__add__',                   'subtract': '__sub__',                   'multiply': '__mul__',                   'divide': '__floordiv__'}     return getattr(num1, operations[operation])(num2) 

Comments

Popular posts from this blog

php - How to add and update images or image url in Volusion using Volusion API -

javascript - jQuery UI Splitter/Resizable for unlimited amount of columns -

javascript - IE9 error '$'is not defined -