473,785 Members | 2,255 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Name bindings for inner functions.

The following code:

def functions():
l=list()
for i in range(5):
def inner():
return i
l.append(inner)
return l
print [f() for f in functions()]
returns [4,4,4,4,4], rather than the hoped for [0,1,2,3,4]. I presume
this is something to do with the variable i getting re-bound every time
we go through the loop, or something, but I'm not sure how to fix this.
I've found the ability in python to create functions on the fly and
store and index them for later use incredibly powerful, so it'd be nice
to get past this little roadblock.

Oct 28 '06 #1
4 1124
tr***********@y ahoo.com wrote:
The following code:

def functions():
l=list()
for i in range(5):
def inner():
return i
l.append(inner)
return l
print [f() for f in functions()]
returns [4,4,4,4,4], rather than the hoped for [0,1,2,3,4]. I presume
this is something to do with the variable i getting re-bound every time
we go through the loop, or something, but I'm not sure how to fix this.
The problem is that "i" inside the function is indeed
the same variable for all the functions (the one you're
using for looping).

If you want a different variable for each function
you can use the somewhat ugly but idiomatic

def functions():
l=list()
for i in range(5):
def inner(i=i):
return i
l.append(inner)
return l

this way every function will have its own "i" variable,
that is initialized with the value of the loop variable
when executing the "def" statement.

Andrea
Oct 28 '06 #2
Thanks, that's exactly what I needed.
Andrea Griffini wrote:
tr***********@y ahoo.com wrote:
The following code:

def functions():
l=list()
for i in range(5):
def inner():
return i
l.append(inner)
return l
print [f() for f in functions()]
returns [4,4,4,4,4], rather than the hoped for [0,1,2,3,4]. I presume
this is something to do with the variable i getting re-bound every time
we go through the loop, or something, but I'm not sure how to fix this.

The problem is that "i" inside the function is indeed
the same variable for all the functions (the one you're
using for looping).

If you want a different variable for each function
you can use the somewhat ugly but idiomatic

def functions():
l=list()
for i in range(5):
def inner(i=i):
return i
l.append(inner)
return l

this way every function will have its own "i" variable,
that is initialized with the value of the loop variable
when executing the "def" statement.

Andrea
Oct 29 '06 #3
tr***********@y ahoo.com wrote:
The following code:

def functions():
l=list()
for i in range(5):
def inner():
return i
l.append(inner)
return l
print [f() for f in functions()]
returns [4,4,4,4,4], rather than the hoped for [0,1,2,3,4]. I presume
this is something to do with the variable i getting re-bound every time
we go through the loop
free variables bind to *names*, not objects. all your functions will
refer to the name "i" in "function"' s scope, which is bound to a 4 when
the loop has finished.

you can use the default argument mechanism to explicitly bind to an
object instead of a name:

def functions():
l=list()
for i in range(5):
def inner(i=i):
return i
l.append(inner)
return l

</F>

Oct 29 '06 #4
Andrea Griffini wrote:
tr***********@y ahoo.com wrote:
>The following code:

def functions():
l=list()
for i in range(5):
def inner():
return i
l.append(inner)
return l
print [f() for f in functions()]
returns [4,4,4,4,4], rather than the hoped for [0,1,2,3,4]. I presume
this is something to do with the variable i getting re-bound every time
we go through the loop, or something, but I'm not sure how to fix this.


The problem is that "i" inside the function is indeed
the same variable for all the functions (the one you're
using for looping).

If you want a different variable for each function
you can use the somewhat ugly but idiomatic

def functions():
l=list()
for i in range(5):
def inner(i=i):
return i
l.append(inner)
return l

this way every function will have its own "i" variable,
that is initialized with the value of the loop variable
when executing the "def" statement.

Andrea
Yet another way to skin the same cat, maybe even less ugly, depending on taste.

def make_inner(i):
def inner():
return i
return inner

def functions():
return [make_inner(i) for i in range(5)]

print [f() for f in functions()]

James

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Oct 29 '06 #5

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

Similar topics

4
2211
by: Phil Thompson | last post by:
Riverbank Computing is pleased to announce the release of PyQt v3.14 available from http://www.riverbankcomputing.co.uk/. Changes since the last release include support for QScintilla v1.5. PyQt is a comprehensive set of Qt bindings for the Python programming language and supports the same platforms as Qt. Like Qt, PyQt is available under the GPL (for UNIX, Linux and MacOS/X), a commercial license (for Windows, UNIX, Linux and...
7
2421
by: max(01)* | last post by:
hi. is there a way to define a class method which prints the instance name? e.g.: >>> class class_1: .... def myName(self): .... ????what should i do here???? ....
6
22535
by: Martin | last post by:
I'd like to be able to get the name of an object instance from within a call to a method of that same object. Is this at all possible? The example below works by passing in the name of the object instance (in this case 'myDog'). Of course it would be better if I could somehow know from within write() that the name of the object instance was 'myDog' without having to pass it as a parameter. //////////////////////////////// function...
8
19601
by: Andrew McNab | last post by:
Hi folks, I have a problem with an MS Access SQL query which is being used in an Access Report, and am wondering if anyone can help. Basically, my query (shown below) gets some records from a couple of tables in my database using INNER JOINS and the WHERE clause to specify the required constraints. However, I also want to read two fields from a *single* record from a table called 'Locations' and then apply one of these field's values...
8
1517
by: olov.johansson | last post by:
Hi, given two nested functions: function outer() { function inner() { } } Is it determined by the ECMAScript standard that inner should be a property of outer, thus a "document.write(outer.inner);" on the global
5
1880
by: engsolnorm | last post by:
I'm playing with a sudoku GUI...just to learn more about python. I've made 81 'cells'...actually small canvases Part of my scheme to write the cells (all 81 of them in the gui) to a file (using the the SAVE callback/button), then restore the gui cells from the contents of the saved file, which depends on knowing the "name" of the cell with the focus, or one (or more) which have a number. The print shows .9919624.9990312, but this...
6
6542
by: blue875 | last post by:
A tale of two queries: One query looks like this, and runs fine. We'll call this the "Customer1 query": SELECT Customer1 overall.*, IIf(IsNull(.),0,1) AS IsField, IIf(IsNull(.),0,1) AS IsStaff FROM ( LEFT JOIN ON .=.) LEFT JOIN
0
1240
by: Matteo Bertini | last post by:
#### PyQt3Support - Python bindings for Qt3Support #### http://www.develer.com/oss/PyQt3Support #### What is this? PyQt3Support is an extension to PyQt4 that adds bindings to Qt's Qt3Support library for usage from the Python language. This is very helpful to migrate existing PyQt3 applications to PyQt4.
3
4244
by: from.future.import | last post by:
Hi, I encountered garbage collection behaviour that I didn't expect when using a recursive function inside another function: the definition of the inner function seems to contain a circular reference, which means it is only collected by the mark-and-sweep collector, not by reference counting. Here is some code that demonstrates it: === def outer():
0
9645
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
9481
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10155
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...
0
9954
tracyyun
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8979
agi2029
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7502
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
6741
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5513
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4054
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

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.