Consider this (rather pointless) javascript code:
function make_closure() {
var x = 123, y = 456;
return function(varname) { return eval(varname) }
}
closure = make_closure()
closure("x") // 123
closure("y") // 456
The function returned from make_closure doesn’t contain any references to scope variables, but still is able to return their values when called.
Is there a way to do the same in python?
def make_closure():
x = 123
return lambda varname: ...no "x" here...
closure = make_closure()
print closure("x") # 123
In other words, how to write a closure that would “know” about variables in defining scope without mentioning them explicitly?
This is probably the closest thing to an exact equivalent:
Ultimately, your problem isn’t that x wasn’t captured by your local closure, but that your local scope wasn’t passed into eval.
See http://docs.python.org/library/functions.html#eval for details on the eval function.
It probably goes without saying that this is not a very Pythonic thing to do. You almost never actually want to call eval in Python; if you think you do, step back and rethink your larger design. But when you do need to use it, you need to understand how it’s different from Javascript eval. It’s ultimately more powerful—it can be used to simulate dynamic scoping, or as a simplified version of exec, or to evaluate code in any arbitrarily-constructed environment—but that also means it’s trickier.