Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe use of eval() or alternatives - python

I'm always weary of using eval in any language but I can't think of a better way to do 2 things. From everything I've read evAl is evIl (that was bad). Any thoughts are appreciated. I have module with a dictionary that either calls a function or sets an attribute depending on how you call it from another module

module Config
some_dict = {1: ["desc 1", "callfunction1()"], 
  2: ["desc2", "setattr(object, "attribute", "the fun things"]} 

etc

module other
try:
  i = int(input())
  eval(Config.some_dict[i][1])
except ValueError:
  print("nope")

I'm just wondering if there is a safer way to do this.
Also if I'm trying to debug while the program is running:

try:
  eval(input())
except:
  pass

Is this acceptable or pythonic or is there a better way? I'm new to python (I run mostly JSL so everything is done with eval(parse()).

like image 625
Faller Avatar asked Dec 05 '25 03:12

Faller


1 Answers

There is a much better way: Use first-class functions.

def func2():
    setattr(object, "attribute", "the fun things")

some_dict = {
    1: ["desc 1", callfunction1],
    2: ["desc2", func2]
}

i = int(input())
Config.some_dict[i][1]()

The clutter can be reduced using lambda or partial, if you're comfortable with them. That said, your existing solution isn't as bad as many uses of eval, because it doesn't evaluate arbitrary user input but rather hard-coded strings. It's just plain unnecessary, pretty slow, and ugly.

And for debugging, there are dedicated debuggers. They work better than an ad-hoc eval-loop.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!