1

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.

rocksteady
  • 2,320
  • 5
  • 24
  • 40
  • I think this question is very likely to be closed as an opinion-based question because the first think that comes to my mind is an opinion. An mine is: No, I can't see any use for a generic function like this. – Bonifacio2 Jan 19 '18 at 14:48
  • It's not really opinion based though. It's a fact that using eval in this way incurs the exact same problems as using eval itself. So if you understand the evils of eval, you should understand the evils of sneakily embedding it in functions in attempts of making macros. As Alg_D's answer shows, there are much better ways to achieve what rocksteady desires. – Vincent Jan 19 '18 at 14:52
  • 1
    This would only apply to infix operators for which there is a small (fixed) set. All these operators can be accessed as functions with the [`operator`](https://docs.python.org/3/library/operator.html) library. What you have done is simply to re-create the functionality of `apply` (which was deemed unnecessary and depreciated) – Aaron Jan 19 '18 at 15:04

2 Answers2

3

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

Alg_D
  • 2,242
  • 6
  • 31
  • 63
1

My mind goes with this thread. You must have already read it, but... in your case, you want to know if there is a case where it could be useful for generic programming.

And... unfortunately, the answer is : If you can't prove at least one good use-case, it doesn't exist.

If you truly believe such a use-case for generic programming exists, then find one, and come show us (But I understand the question might be interesting to think about as a group, more than as an individual, but then, you might want to consider going on another site).

IMCoins
  • 3,149
  • 1
  • 10
  • 25