0

I wrote a server that accepts requests and performs tasks.

  • Each task is represented by a function.
  • Each request has the name of the task.

I want to make a reference to the relevant functions by the name of the task that found in the request. I saw that it works fine using eval() and even if I implement it through a dictionary but is there another generic way to control the flow of the code?

def din():
    print("din")

def david():
    print("david")

request = {"TestName": "din"}

# option 1: eval
test_to_run = request['TestName']

eval(f"{test_to_run}()")

# option 2: dict
my_dict = {"din": din, "david": david}

my_dict[test_to_run]()
  • I mean, sure, you *could* use `if test_to_run == "foo": foo() elif test_to_run == "bar": bar() ...` – juanpa.arrivillaga Dec 30 '20 at 11:30
  • Functions are also objects and can be set as values of a dictionary so why not just do `funcs = {"foo": din, "bar": david}` then `f = funcs['foo']` followed by `f()`? –  Dec 30 '20 at 11:46

1 Answers1

0

No, not really. In my opinion the 'Request' map is the safer of the two options, because it makes it impossible to run arbitrary code through 'eval', which could be unsafe.

Joe Todd
  • 814
  • 6
  • 13