15

I try to use eval() in a local scope of a function. However it always evaluate in the global scope.

Self contained examples:

1- This code works:

var1 = 1
var2 = 2
var3 = 3    
myDict = dict((name, eval(name)) for name in ["var1",
                                              "var2",
                                              "var3"])
print(myDict["var1"])

2- Throws NameError for lvar1

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

3- Same outcome as 2.

def test2():
    lvar1 = 1
    lvar2 = 2
    lvar3 = 3
    myDict = dict((name, eval(name), locals()) for name in ["lvar1",
                                                            "lvar2",
                                                            "lvar3"])
    print(myDict["lvar1"])
5
  • 5
    Perhaps a more important question here is do you really need eval?
    – Joost
    Apr 14, 2016 at 7:48
  • 1
    @cjahangir That was a ¯\_(ツ)_/¯ suggestion
    – Adib
    Apr 14, 2016 at 7:54
  • @Adib, it works in my computer
    – cjahangir
    Apr 14, 2016 at 7:54
  • @joost I tried to use eval() only in testing fixtures for pytest. So it would not be a security hole, and you are right I found an other way around, but I am still interested how to do it. Because must be reason why python has this bult-in
    – atevm
    Apr 14, 2016 at 7:56
  • @cjahangir There is no any difference between "string" and 'string' in python, what is your python interpreter?
    – atevm
    Apr 14, 2016 at 8:02

2 Answers 2

17

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()
2
  • Thanks. It's probably not relevant in this special case, but this way locals are interpreted as globals (because second parameter of eval)? How to specifiy them as locals? eval(name, locals=scope) seems not to work. Jun 27, 2021 at 13:30
  • 2
    @SearchSpace, The 3rd parameter of eval is locals. So eval(expression_you_want_to_evaluate, {}, scope) will give you what you want if I interpreted your comment correctly. docs.python.org/3/library/functions.html#eval
    – falsetru
    Jun 27, 2021 at 15:53
7

First of all it's important to read this:

The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace. If the globals dictionary is present and lacks ‘__builtins__’, the current globals are copied into globals before expression is parsed. This means that expression normally has full access to the standard __builtin__ module and restricted environments are propagated. If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed in the environment where eval() is called. The return value is the result of the evaluated expression`.

To start with it is important to note that a generator expression has its own scope(true for a dict-comprehension as well), hence it has its own locals() dictionary.

  1. This worked because in global scope both globals() and locals() dict points to the same dictionary hence the dict constructor can access those variables.

  2. Here we are again calling eval() with no globals() and locals() dict hence it ends up using the global scope and its own local scope(which is empty) and there are no such variable available in any of these scopes.

  3. Remember generators have their own scope so calling locals() here barely makes any difference, it's an empty dict.

Solution:

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

This worked because we captured test1's locals() in a variable and then used that dictionary inside of the dictionary comprehension, so it now has access to those variables.

2
  • Thank you for the explanation! This is baffling! If I understood this right, what you're saying is that within the dict() command, it only takes into account the global variables, which is why it excludes all variables within a function since it's local? (which is why we have to specify the scope?)
    – Adib
    Apr 14, 2016 at 8:11
  • 2
    Consider a generator expression as a new function scope with its own set of locals, test1 has its own separate locals. Apr 14, 2016 at 8:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.