....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.ExternalCa ll(self.name)
# The first test.
def CreateTests1(co unt):
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(co unt):
tests = []
for i in xrange(count):
t = CreateTest(i)
tests.append(t)
return tests
def CreateTest(inde x):
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() 3 1348
Tom Plunket wrote in news:cm******** *************** *********@4ax.c om in
comp.lang.pytho n:
...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(co unt):
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/
On 12 dic, 17:23, Tom Plunket <t...@fancy.org wrote:
...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(co unt):
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
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! This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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 philosophy but that is
the way things need to work for now here. The problem I'm having is
that it appears that the browsers (IE, mozilla and netscape) are...
|
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 an alternative
to pop-up windows in a web page. The code I have works (sort of).
The problem is that I can move these layers around when I move the...
|
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 = pSource;
this.req=new ActiveXObject("Msxml2.XMLHTTP"); //this.req != null
this.Process = MyProcess;
this.requestSuggestions =...
|
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)' works fine , but...
when I was trying:
I got "TypeError: 'list' object is not callable".
|
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 = function(event) {
| |
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 = "<form>...</form>";
|
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):
import new
precondition = new.function(f.func_code.co_consts,
|
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-
not-java.html) that in Python we can reduce code duplication for
overloaded functions by using closures.
I do not quite understand this. Let's say...
|
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: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in...
| |
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |