Python: How can I run eval() in the local scope of a function

Save the result of locals() (or vars()) call to return the function’s local scope. Otherwise, locals() inside the generator expression will return the gen-expr’s local scope.

def test3():
    lvar1 = 1
    lvar2 = 2
    lvar3 = 3
    scope = locals()
    myDict = dict((name, eval(name, scope)) for name in [
                  "lvar1", "lvar2", "lvar3"])
    print(myDict["lvar1"])

BTW, you don’t need an explicit comprehension to build that dict:

# copy() avoids quirky, unexpected updates if something else (like a debugger)
# accesses locals() or f_locals
myDict = locals().copy()  # or vars().copy()

Leave a Comment