473,383 Members | 1,874 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

Problem understanding how closures work

....at least, I think that I'm having a problem understanding the way
closures work.

I'm trying to define a function for an object which will take certain
objects from the parent scope at the time that function is defined.
For some reason, if I do this function definition in a loop, the
locals given by that function (is this a closure?) are changed each
iteration of the loop, whereas if the function definition is isn't
looped over, I get the behavior I desire. Can anyone provide any
insight for me?

thanks,
-tom!

First, the output:

Test 1 doesn't work the way I would expect:
Test 4 says, "Test 0"
Test 4 says, "Test 1"
Test 4 says, "Test 2"
Test 4 says, "Test 3"
Test 4 says, "Test 4"

....but test 2 does?
Test 0 says, "Test 0"
Test 1 says, "Test 1"
Test 2 says, "Test 2"
Test 3 says, "Test 3"
Test 4 says, "Test 4"

Next, the program:

class Test:
def __init__(self, name):
self.name = name

def DoCall(self):
self.ExternalCall(self.name)

# The first test.
def CreateTests1(count):
tests = []
for i in xrange(count):
name = 'Test %d' % i
t = Test(name)
tests.append(t)

def ExCall(text):
print '%s says, "%s"' % (name, text)

t.ExternalCall = ExCall

return tests

# The second test.
def CreateTests2(count):
tests = []
for i in xrange(count):
t = CreateTest(i)
tests.append(t)
return tests

def CreateTest(index):
name = 'Test %d' % index
t = Test(name)

def ExCall(text):
print '%s says, "%s"' % (name, text)

t.ExternalCall = ExCall
return t

print 'Test 1 doesn\'t work the way I would expect:'
for t in CreateTests1(5):
t.DoCall()

print '\n...but test 2 does?'
for t in CreateTests2(5):
t.DoCall()
Dec 12 '06 #1
3 1344
Tom Plunket wrote in news:cm********************************@4ax.com in
comp.lang.python:
...at least, I think that I'm having a problem understanding the way
closures work.

I'm trying to define a function for an object which will take certain
objects from the parent scope at the time that function is defined.
For some reason, if I do this function definition in a loop, the
locals given by that function (is this a closure?) are changed each
iteration of the loop, whereas if the function definition is isn't
looped over, I get the behavior I desire. Can anyone provide any
insight for me?
Test 1 doesn't work the way I would expect:
Test 4 says, "Test 0"
Test 4 says, "Test 4"
def CreateTests1(count):
tests = []
for i in xrange(count):
name = 'Test %d' % i
t = Test(name)
tests.append(t)

def ExCall(text):
print '%s says, "%s"' % (name, text)

t.ExternalCall = ExCall

return tests
"name" in the above code is bound to a an entry in "CreateTests1"'s
locals, and ExCall has a (hidden) reference to that locals, so
by the time ExCall is finally called the value associated
with "name" has been replaced by (count - 1).

The solution (as always) is to add another level of indirection:

def create_tests( count ):
def make( arg ):
def ExCall( text ):
print arg, text
return ExCall

tests = []

for i in range( count ):
name = i
t = Test( name )
t.ExternalCall = make( name )

In the above, every call to make() creates a new frame (a new set
of locals) and binds the value of the passed in "name" to the
name "arg" in this new frame, it will be this value that is
eventually printed.

There is a trick with default arguments that lets you do
what you want with a bit less faffing about:
>>r = []
for i in range(10):
def f( i = i ):
print i
r.append( f )
>>for i in r:
i()

In this example the value of "i" is bound to the default argument
for the function "f" every time the def f() statments are executed.

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Dec 12 '06 #2
On 12 dic, 17:23, Tom Plunket <t...@fancy.orgwrote:
...at least, I think that I'm having a problem understanding the way
closures work.

I'm trying to define a function for an object which will take certain
objects from the parent scope at the time that function is defined.
def CreateTests1(count):
tests = []
for i in xrange(count):
name = 'Test %d' % i
t = Test(name)
tests.append(t)

def ExCall(text):
print '%s says, "%s"' % (name, text)

t.ExternalCall = ExCall

return tests
name, inside ExCall, is a free variable. Python builds a closure
including the string whose name is "name" in the enclosing scope. Not
the *value* which happens to have at this momment. When you execute
ExCall, the reference to name yields its last, current, value.
If you want "the value at the moment the function is created" you can
use a default argument:

def ExCall(text, name=name): ...

Your second test works because you don't modify "name" between the
original definition and its execution.

--
Gabriel Genellina

Dec 12 '06 #3
Rob Williscroft wrote:
"name" in the above code is bound to a an entry in "CreateTests1"'s
locals, and ExCall has a (hidden) reference to that locals, so
by the time ExCall is finally called the value associated
with "name" has been replaced by (count - 1).
Ah, I got it. Thanks. Thanks too to Gabriel.
-tom!
Dec 12 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Derek | last post by:
Hi, I've built a rather large CGI that dumps a lot of data and a fairly complex javascript app out to the client's browser. Granted this may be poor style according to someone web design...
8
by: rdlebreton | last post by:
Hi, Folks! I've been trying to develop my own version of these draggable layers and I have been limiting myself to IE6...for now. I have looked at some other examples to get ideas of creating...
3
by: Fabio Cavassini | last post by:
I'm new to JavaScript and this is annoying me. I have defined a "class" (JavaScript OO seems really strange to me...) in the following way: function StateSuggestions(pSource) { this.source =...
6
by: Dasn | last post by:
Hi, there. 'lines' is a large list of strings each of which is seperated by '\t' I wanna split each string into a list. For speed, using map() instead of 'for' loop. 'map(str.split, lines)'...
5
by: Leo Meyer | last post by:
Hello, somewhere I have read that JavaScript supports closures. Does someone know how to make them work? What I want to do is this: function f1(x, obj) { var eventhandler =...
4
by: Dan Michael Heggå | last post by:
Hi, I've working on inplace-editing. My problem is the following: This works in all browsers: myDiv.innerHTML = "<p>...</p>"; but this doesn't work in IE: myDiv.innerHTML =...
1
by: alain | last post by:
Hi, I have a problem with closures. I am trying to implement yet another design by contract decorator which would look like the following: <pre> def contract(f): def newf(*args, **kw):...
4
by: king kikapu | last post by:
Hi, i am trying, to no avail yet, to take a C#'s overloaded functions skeleton and rewrite it in Python by using closures. I read somewhere on the net (http://dirtsimple.org/2004/12/python-is-...
26
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
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.