Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

python - Is there another way to generically control code flow without the use of eval/dictionary?

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]()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...