473,434 Members | 1,791 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,434 software developers and data experts.

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 1111
tr***********@yahoo.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***********@yahoo.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***********@yahoo.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***********@yahoo.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
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. ...
7
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
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...
8
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...
8
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...
5
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...
6
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...
0
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...
3
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...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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...
0
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,...
1
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...
0
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...
0
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,...
0
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...
0
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.