Friday, October 9, 2009

Closures in Python and JavaScript

Here is a program written in Python:
def clo():
a = 3
def geta():
return a
def seta(newa):
a = newa
return [geta, seta]

closure = clo()
closure[1](5)
print(closure[0]())
And here is the same program written in JavaScript:
function clo() {
var a = 3;
function geta() {
return a;
}
function seta(newa) {
a = newa;
}
return [geta, seta];
}

closure = clo()
closure[1](5)
print(closure[0]())
Here is the output of running the Python program:
tuba:~ litherum$ python --version
Python 2.5.1
tuba:~ litherum$ python test.py
3
And here is the output of running the JavaScript program:
tuba:~ litherum$ java -jar Downloads/rhino1_7R2/js.jar test.js
5
Here are a couple observations of this:

  • Both languages printed out a value, so clearly both of them use closures

  • Python printed out the original value of a, so it appears that it creates a new closure for each function invocation.

  • JavaScript printed out the new value of a, so it appears that the closure is consistent across function invocations

I just noticed this and thought that it's fairly interesting food for thought.

No comments:

Post a Comment