alternative to use eval python eval-used / W0123

211 Views Asked by At
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

There are 1 best solutions below

2
Samwise On

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.