英文:
alternative to use eval python eval-used / W0123
问题
You can achieve the same result without using eval by directly accessing the values from the dictionaries and executing functions like this:
import os
d1 = {
    "a": "test"
}
cmd_dict = {
    "cmd1": d1['a'],
    "cmd2": os.getcwd()
}
value = cmd_dict['cmd1']
print(value)
This eliminates the need for eval and should resolve the pylint error W0123.
英文:
d1 = {
        "a": "test"
    }
    
    cmd_dict = {
        "cmd1": "d1['a']",
        "cmd2 : "os.getcwd()"
    }
value = eval(md_dict['cmd1]) 
print(value)
Not i will get the value as test.
I am getting pylint error W0123 becasue i am using eval.
is there any way to perform the same without using eval.
答案1
得分: 1
将函数放入你的字典中,然后你可以像调用任何其他函数一样调用它们。不需要使用eval():
import os
d1 = {}
    
cmd_dict = {
    "cmd1": lambda: d1['a'],
    "cmd2": os.getcwd,
}
d1['a'] = 'test'
value = cmd_dict['cmd1']()
print(value)  # test
请注意,lambda 创建了一个小的匿名函数,当调用它时,它将评估并返回d1['a'];延迟评估(你不需要使用eval()来完成)是为什么它返回test,即使该值在创建cmd_dict之后设置在d1中的原因。
英文:
Put functions in your dictionary, and you can simply call them like any other function.  No eval() needed:
import os
d1 = {}
    
cmd_dict = {
    "cmd1": lambda: d1['a'],
    "cmd2" : os.getcwd,
}
d1['a'] = 'test'
value = cmd_dict['cmd1']()
print(value)  # test
Note that lambda creates a small anonymous function that will evaluate and return d1['a'] when it's called; the delayed evaluation (which, again, you do not need eval() to do) is why it returns test even though that value is set in d1 after cmd_dict has been created.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论