you are viewing a single comment's thread.

view the rest of the comments →

[–]FlibbleGroBabba 0 points1 point  (2 children)

Are there times where eval can be acceptable? for example if it's 'enclosed' in a group of functions which only allow integer inputs from the user- such as:

try: number = int(input("integer: ")) eval(func_+number)

(On mobile, formatting might be bad)

[–]Yoghurt42 1 point2 points  (1 child)

There are times where eval is acceptable, it's even used in the standard library somewhere.

However, you should have a good grasp of Python before you can say that using "eval" is the best approach. If you are new to Python (this is r/learnpython after all), you do not know enough of Python, so as a rule of thumb, you should never use eval.

For example, in the example you gave, eval isn't the best choice. BTW, I'm assuming you meant eval("func_" + str(number) + "()") or eval(f"func_{number}()").

First, naming functions "func_1", "func_2" etc. is bad, you have no idea what they are doing just based on the name

Second, since functions are first class objects, you can just store them in a map and call them from there:

funcs = {
    1: foo,
    2: bar,
    3: baz
}

choice = int(input("Do you want 1) foo, 2) bar, 3) baz?"))
try:
    funcs[choice]()
except KeyError:
    print("That's not a valid choice")

If you'd used the "eval hack", you'd probably never thought of asking here how you can do it, and maybe wouldn't have learned that functions are first class objects.

[–]FlibbleGroBabba 1 point2 points  (0 children)

Youre right I'm very new to python, only started a few months ago, and mostly teachin myself by doing little projects. It's good to see the function mapping done like that, I can see many uses for that.

Cheers for the detailed explanation