alternative to use eval python eval-used / W0123

huangapple go评论64阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年6月1日 13:40:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76378948.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定