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

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -