Hi all,
consider the following small example:
"""
Small test to try to understand a strange subtlety with closures
"""
def outer(nmax):
aa = []
for n in range(nmax):
def a(y):
return (y,n)
print 'Closure and cell id:',id(a.func_closure),\
id(a.func_closure[0])
aa.append(a)
return aa
print 'Closure creation.'
nmax = 3
aa = outer(nmax)
print
print 'Closure use.'
for n in range(nmax):
print '%s:%s' % (n,aa[n]('hello'))
################## EOF #################
If I run this, I get:
planck[test]python debug_closures.py
Closure creation.
Closure and cell id: 1075998828 1075618940
Closure and cell id: 1075999052 1075618940
Closure and cell id: 1075999084 1075618940
Closure use.
0:('hello', 2)
1:('hello', 2)
2:('hello', 2)
My confusion arises from the printout after 'closure use'. I was expecting that
each new function 'a' created inside the loop in 'outer' would capture the
value of n, therefore my expectation was to see a printout like:
0:('hello', 0)
1:('hello', 1)... etc.
However, what happens is a bit different. As can be seen from the printouts
of 'Closure and cell id', in each pass of the loop a new closure is created,
but it reuses the *same* cell object every time. For this reason, all the
closures end up sharing the scope with the values determined by the *last*
iteration of the loop.
This struck me as counterintuitive, but I couldn't find anything in the
official docs indicating what the expected behavior should be. Any
feedback/enlightenment would be welcome. This problem appeared deep inside a
complicated code and it took me almost two days to track down what was going
on...
Cheers,
f 2 1234
Fernando Perez schrieb:
Hi all,
consider the following small example:
"""
Small test to try to understand a strange subtlety with closures
"""
def outer(nmax):
aa = []
for n in range(nmax):
def a(y):
return (y,n)
print 'Closure and cell id:',id(a.func_closure),\
id(a.func_closure[0])
aa.append(a)
return aa
print 'Closure creation.'
nmax = 3
aa = outer(nmax)
print
print 'Closure use.'
for n in range(nmax):
print '%s:%s' % (n,aa[n]('hello'))
################## EOF #################
If I run this, I get:
planck[test]python debug_closures.py
Closure creation.
Closure and cell id: 1075998828 1075618940
Closure and cell id: 1075999052 1075618940
Closure and cell id: 1075999084 1075618940
Closure use.
0:('hello', 2)
1:('hello', 2)
2:('hello', 2)
My confusion arises from the printout after 'closure use'. I was expecting that
each new function 'a' created inside the loop in 'outer' would capture the
value of n, therefore my expectation was to see a printout like:
0:('hello', 0)
1:('hello', 1)... etc.
However, what happens is a bit different. As can be seen from the printouts
of 'Closure and cell id', in each pass of the loop a new closure is created,
but it reuses the *same* cell object every time. For this reason, all the
closures end up sharing the scope with the values determined by the *last*
iteration of the loop.
This struck me as counterintuitive, but I couldn't find anything in the
official docs indicating what the expected behavior should be. Any
feedback/enlightenment would be welcome. This problem appeared deep inside a
complicated code and it took me almost two days to track down what was going
on...
It's a FAQ. The reason is that the created closures don't capture the
_value_, but the _name_. Plus of course the locals()-dictionary outside
the function a to perform the lookup of that name. Which has the value
bound to it in the last iteration.
Common cure for this is to create an a-local name that shadows the outer
variable and is simultaneously bound to the desired value:
def outer(nmax):
aa = []
for n in range(nmax):
foo = 'bar'
def a(y,n=n):
bar = foo
return (y,n)
print 'Closure and cell id:',id(a.func_closure),\
id(a.func_closure[0])
aa.append(a)
return aa
print 'Closure creation.'
nmax = 3
aa = outer(nmax)
print
print 'Closure use.'
for n in range(nmax):
print '%s:%s' % (n,aa[n]('hello'))
Notice the foo/bar - that was necessary to actually create a closure at
all (to keep your printing working), as python statically checks if
there needs one to be.
Diez
Diez B. Roggisch wrote:
It's a FAQ. The reason is that the created closures don't capture the
_value_, but the _name_. Plus of course the locals()-dictionary outside
the function a to perform the lookup of that name. Which has the value
bound to it in the last iteration.
Common cure for this is to create an a-local name that shadows the outer
variable and is simultaneously bound to the desired value:
Many thanks (also to JP) for the clear explanation. Greatly appreciated.
Cheers,
f This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Alexander May |
last post by:
When I define a function in the body of a loop, why doesn't the function
"close" on the loop vairable? See example below.
Thanks,
Alex
C:\Documents and Settings\Alexander May>python
Python...
|
by: Charles Krug |
last post by:
List:
I've a module that's not doing what I expect. My guess is that I don't
quite understand the scoping rules the way I should.
I have an object that's costly to create. My thought was to...
|
by: NevilleDNZ |
last post by:
Can anyone explain why "begin B: 123" prints, but 456 doesn't?
$ /usr/bin/python2.3 x1x2.py
begin A:
Pre B: 123 456
begin B: 123
Traceback (most recent call last):
File "x1x2.py", line 13,...
|
by: Chad |
last post by:
The following question stems from Static vs Dynamic scoping article in
wikipedia.
http://en.wikipedia.org/wiki/Scope_(programming)#Static_versus_dynamic_scoping
Using this sites example, if I...
|
by: stef mientki |
last post by:
hello,
I've thought many times I finally understood the import / namespace rules,
but again I'm totally lost :-(
This is my library file
# Module lib_test.py
X = 1
|
by: Khookie |
last post by:
Woah... is it just me or do C programmers don't bother talking about
how cool C can be (compared to Lisp, Haskell, etc.) - functionally
speaking?
// Lexical scoping - via nested functions...
|
by: Joshua Kugler |
last post by:
I am trying to use lamdba to generate some functions, and it is not working
the way I'd expect. The code is below, followed by the results I'm
getting. More comments below that.
patterns = (...
|
by: Jeff |
last post by:
I have a question about closures. Take for example the addBehavior
method below from the Low Pro library
Event.addBehavior = function(rules) {
var ab = this.addBehavior;
Object.extend(ab.rules,...
|
by: Aaron \Castironpi\ Brady |
last post by:
Hello all,
To me, this is a somewhat unintuitive behavior. I want to discuss the
parts of it I don't understand.
.... f= lambda: n
....
9
9
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM).
In this month's session, the creator of the excellent VBE...
|
by: MeoLessi9 |
last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
|
by: DolphinDB |
last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation.
Take...
|
by: Aftab Ahmad |
last post by:
Hello Experts!
I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
|
by: Aftab Ahmad |
last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below.
Dim IE As Object
Set IE =...
|
by: ryjfgjl |
last post by:
ExcelToDatabase: batch import excel into database automatically...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: ArrayDB |
last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
|
by: PapaRatzi |
last post by:
Hello,
I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
| |