简体   繁体   中英

Python Eval executing environment

I do not understand what environment a eval or exec statement executes in. You can pass both global and local scopes to them but I don't quite understand what this means. Does python create an anonymous module for them, and if that is the case how do the global and local scope differ?

Does it run it like it was an anonymous function? If that was the case the global and local scopes would make more sense to me, although would you still need to call global var to prevent python from making a local variable on assignment?

And here is some code to show what I am actually trying to do.

# module level vars
result = ''

allowed_builtins = {"__builtins__":{'int':int, 'str':str, 'range':range, 'dir':dir,
                                    'zip':zip
},
                    "result":result}

In class

def _exec(self, answer, function_name, input):
    global result
    exec_string = answer + '\n'
    exec_string += 'global result; result = %s(%s)' % (function_name, input)
    exec exec_string in allowed_builtins, {}

    return result

I would like the var result in my scope to be able to be set from within the eval/exec's scope.

The "local" dictionary is where all names are being set during an exec or eval ; the "global" one is used for lookup of names not found in the "local" one, but names aren't set there unless you're exec ing code that includes a global statement.

No module object is created intrinsically by either eval or exec , nor is any function object, anonymous or otherwise (again, of course: unless you exec statements such as def , etc).

Edit : for example, given the OP's code, and assuming _exec is a free-standing function since the OP's giving no class where it could live, add at the end:

print 'one: %r' % _exec(None, '"foo"', 'range', 7)
print 'two: %r' % allowed_builtins['result']

and you'll see this output:

one: ''
two: [0, 1, 2, 3, 4, 5, 6]

the result in the __dict__ of the current module is of course not affected (how could it conceivably be , since that dict is never passed to the exec in question?!) -- the allowed_builtins dictionary is of course the one affected, since it's the dict passed as the "global dictionary" and there is a global statement in the string being exec uted!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM