Python: How can I run eval() in the local scope of a function -
i try use eval() in local scope of function. evaluate in global scope.
self contained examples:
1- code works:
var1 = 1 var2 = 2 var3 = 3 mydict = dict((name, eval(name)) name in ["var1", "var2", "var3"]) print(mydict["var1"])
2- throws nameerror
lvar1
def test1(): lvar1 = 1 lvar2 = 2 lvar3 = 3 mydict = dict((name, eval(name)) name in ["lvar1", "lvar2", "lvar3"]) print(mydict["lvar1"])
3- same outcome 2.
def test2(): lvar1 = 1 lvar2 = 2 lvar3 = 3 mydict = dict((name, eval(name), locals()) name in ["lvar1", "lvar2", "lvar3"]) print(mydict["lvar1"])
save result of locals()
(or vars()
) call return function's local scope. otherwise, locals()
inside generator expression return gen-expr's local scope.
def test3(): lvar1 = 1 lvar2 = 2 lvar3 = 3 scope = locals() mydict = dict((name, eval(name, scope)) name in [ "lvar1", "lvar2", "lvar3"]) print(mydict["lvar1"])
btw, dictionary creation not necessary:
mydict = locals() # or vars()
Comments
Post a Comment