Search code examples
pythonevalgeneric-programming

Can a generic function using eval be of any use?


I know, that eval() is evil.

I'm sure there are much better ways.

This is just a general question of approaching a problem.

What do you think about using eval() in order to make a function more generic?

In a very simple example, it could look like this:

def generic_eval_func(a, operator, b):
    return eval('a '+operator+' b')    

if __name__ == '__main__':
    a = 6
    b = 7
    print generic_eval_func(a, '<', b)

I have not used such a function, yet.

But every now and then it pops into my mind when thinking about how to make functions more generic.

Instead of having two functions subtract(a,b) add(a, b) there would be one function operation(a, '+', b) or operation(a, '-', b) or operation(a, '<', b).

I'm really not sure about it.


Solution

  • you can use the operator if you are interested in simple arithmetic operations

    from functools import reduce  # Python 3
    import operator
    
    print(reduce(operator.__sub__, (6,7)) )
    print(reduce(operator.__add__, [6,7]) ) # you can pass a list as well.
    

    for other operator like < I guess you better go with lambda functions