473,663 Members | 2,933 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

When Closure get external variable's value?

What will the following piece of code print? (10 or 15)

def testClosure(max Index) :

def closureTest():
return maxIndex

maxIndex += 5

return closureTest()

print testClosure(10)

My question is when the closure function gets value for maxindex? Run
time or compile time?

Thanks.

Dec 18 '06 #1
11 3020
It will print 15. The closure gets the value at run time.

Could we treat closure as part of the external function and it shares
the local variable with its holder function?

Dec 18 '06 #2
Huayang Xia kirjoitti:
It will print 15. The closure gets the value at run time.

Could we treat closure as part of the external function and it shares
the local variable with its holder function?
I don't quite get what you are trying to tell us but if you think that
in your example code:

def testClosure(max Index) :

def closureTest():
return maxIndex

maxIndex += 5

return closureTest()

print testClosure(10)

you are returning a callable function you are all wrong. This can be
easily seen by:
>>type(testClos ure(10))
15
<type 'int'>

The mistake is that you shouldn't return closureTest() but closureTest
instead. The correct way would be:
>>def testClosure2(ma xIndex):
def closureTest():
return maxIndex
maxIndex += 5
return closureTest
>>f2 = testClosure2(10 )
<function closureTest at 0x00D82530>
>>type(f2)
<type 'function'>
>>print f2()
15

Cheers,
Jussi
Dec 18 '06 #3
Thanks for the clarification.

But my question is:

When does the closure get the value of the maxIndex in the following
code snippet?

def testClosure(max Index) :

def closureTest():
return maxIndex

maxIndex += 5

return closureTest()

print testClosure(10)
I thought it should be 10 instead of 15. That was wrong.

After several tests, I found maxIndex is, though, local to
testClosure() but is external to the closureTest(). closureTest() gets
the value of maxIndex at run time. So that it's 15 instead of 10. The
following snippet will verify that further:

def testClosure1(ls t):

def closureTest():
lst.append(lst[-1]+1)

lst.append(lst[-1]+1)
return closureTest()

alist = [1]
testClosure1(al ist)
alist.append(3)
testClosure1(al ist)

The 'lst' in function testClosure1() and the closure closureTest() are
same thing as alist. So everything is dynamic. Variable's value is
determined at run time.

Dec 19 '06 #4
Huayang Xia wrote:
When does the closure get the value of the maxIndex in the following
code snippet?

def testClosure(max Index) :

def closureTest():
return maxIndex

maxIndex += 5

return closureTest()

print testClosure(10)
I thought it should be 10 instead of 15. That was wrong.
free variables in an inner scope bind to variables in the outer scope,
not objects.

if you want to bind to objects, use explicit binding:

def closureTest(max Index=maxIndex) :
return maxIndex

</F>

Dec 19 '06 #5
That is a really concise and precise answer. Thanks.

So the object binding can only happen explicitly at the closure
declaration argument list(non-free variable).

On Dec 19, 10:37 am, Fredrik Lundh <fred...@python ware.comwrote:
Huayang Xia wrote:
When does the closure get the value of the maxIndex in the following
code snippet?
def testClosure(max Index) :
def closureTest():
return maxIndex
maxIndex += 5
return closureTest()
print testClosure(10)
I thought it should be 10 instead of 15. That was wrong.free variables in an inner scope bind to variables in the outer scope,
not objects.

if you want to bind to objects, use explicit binding:

def closureTest(max Index=maxIndex) :
return maxIndex

</F>
Dec 19 '06 #6
In <11************ **********@t46g 2000cwa.googleg roups.com>, Huayang Xia
wrote:
That is a really concise and precise answer. Thanks.

So the object binding can only happen explicitly at the closure
declaration argument list(non-free variable).
That's no declaration that's a definition and it happens at runtime! It's
executed every time the outer function is called and executed and creates
a function object.

As far as I can see you don't create a closure BTW. You are *calling*
that inner function and return the *result* of that call.

Ciao,
Marc 'BlackJack' Rintsch
Dec 19 '06 #7
I'm confused. What is the definition of closure.

I'm not sure if it's correct, I get the definition from wikipedia:

"A closure typically comes about when one function is declared entirely
within the body of another, and the inner function refers to local
variables of the outer function. At runtime, when the outer function
executes, a closure is formed. It consists of the inner function's code
and references to any variables in the outer function's scope that the
closure needs."

I agree it is not declaration, it's definition. However it's closure
based on the above definition. It uses free variable. Or you mean it's
a closure only when the outer function returns it and be exposed to
external world?

The code snippet was just for test purpose. My question was how the
free variable inside inner function (the closure) binds with object.
That was answered by Fredrik perfectly.

Dec 19 '06 #8
Huayang Xia a écrit :
I'm confused. What is the definition of closure.

I'm not sure if it's correct, I get the definition from wikipedia:

"A closure typically comes about when one function is declared entirely
within the body of another, and the inner function refers to local
variables of the outer function. At runtime, when the outer function
executes, a closure is formed. It consists of the inner function's code
and references to any variables in the outer function's scope that the
closure needs."
You skipped the first and most important sentence:
"In programming languages, a closure is a function that refers to free
variables in its lexical context."

IOW, a closure is a function that carry it's own environment. In the
following code, the function returned by make_adder is a closure :

def make_adder(addi ng):
def adder(num):
return num + adding
return adder
add_three = make_adder(3)
print add_three(4)
=7
I agree it is not declaration, it's definition. However it's closure
based on the above definition. It uses free variable.
Actually, it uses a variable defined in the enclosing scope. But as long
as it's also executed in the same enclosing scope, it's just a nested
function.
Or you mean it's
a closure only when the outer function returns it and be exposed to
external world?
Bingo.
Dec 19 '06 #9
Bruno Desthuilliers wrote:
>You skipped the first and most important sentence:
"In programming languages, a closure is a function that refers to free
variables in its lexical context."

IOW, a closure is a function that carry it's own environment.
in contrast to functions that don't know what environment they belong
to, you mean ? can you identify such a construct in Python ?

</F>

Dec 19 '06 #10

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

Similar topics

27
2103
by: Ted Lilley | last post by:
What I want to do is pre-load functions with arguments by iterating through a list like so: >>>class myclass: .... pass >>>def func(self, arg): .... print arg >>>mylist = >>>for item in mylist: .... setattr(myclass, item, lamdba self: func(self, item))
1
3235
by: mr_burns | last post by:
Hi, i was wondering if it is possible to load text into a string from an external text file. the reason is that i have a very large string and it is making my script very messy. also, is it possible to have some dynamic parts of the text from the text file? for example, if i load in a string and there is a part of it that inserts a value from a variable like the following: 'The number of people is ' + var_people_num;
2
2142
by: Harry Stangel | last post by:
Noble reader, My goal is to obtain the current time on the web server and display it in the client's browser. I want the server time displayed independent of the client's current clock setting, but use the client clock to refresh the displayed time every second. To compensate for drift, I want to periodically calibrate the page with the server time by refreshing the page, say every ten minutes or so. I have a servlet '/apps/clock'...
2
5318
by: f rom | last post by:
----- Forwarded Message ---- From: Josiah Carlson <jcarlson@uci.edu> To: f rom <etaoinbe@yahoo.com>; wxpython-users@lists.wxwidgets.org Sent: Monday, December 4, 2006 10:03:28 PM Subject: Re: 1>make_buildinfo.obj : error LNK2019: unresolved external symbol __imp__RegQueryValueExA@24 referenced in function _make_buildinfo2 Ask on python-list@python.org . - Josiah
0
1090
by: Gerard Brunick | last post by:
Consider: ### Function closure example def outer(s): .... def inner(): .... print s .... return inner .... 5
2
1215
by: Bob.Sidebotham | last post by:
If I run the following code: class path(object): def __init__(self, **subdirs): for name, path in subdirs.iteritems(): def getpath(): return path setattr(self, name, getpath) export = path(
0
1982
by: =?Utf-8?B?SlA=?= | last post by:
I have an application that uses Forms Authentication in connection with Active Directory for granting access to an application. When a user logs on with AD, it populates the AUTH_USER ServerVariable and I can then use: Request.ServerVeriables to retrieve the value of this variable or any other value in the ServerVariableCollection.
7
3150
by: howardk | last post by:
I'm writing some code that loads a number of images, using the standard mechanism of assigning a src url to a newly constructed Image object, thus invoking the image-load operation. On a successful load, an image.onload handler I've previously assigned will be called. Or should be at any rate. The problem is that I need to know inside the onload handler which particular image in the array invoked the handler. I'd be quite happy to know...
3
1685
by: disappearedng | last post by:
Hi everyone I am currently reading a book, and I don't seem to under the author, (Crockfold) when he says this: //Bad examples var add_the_handlers = function(nodes){ var i; for (i = 0; i < nodes.length; i += 1) { nodes.onclick = function(e){ alert(i);
0
8437
marktang
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8861
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8778
jinu1996
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8549
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 most users, this new feature is actually very convenient. If you want to control the update process,...
1
6187
isladogs
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4185
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4351
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2764
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2003
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.