473,405 Members | 2,300 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,405 software developers and data experts.

Function returns a function

Hello,

I want a "function factory" function in python. To do this I made a class like
such (this is for Tkinter, in case your wondering):

class FunctionMaker:
def __init__(self, avar, function, label)
self.var = avar
self.function = function
self.label = label
def __call__(self, e=None):
self.avar.set(self.label)
self.function()

It seems that it would make more sense to make this a function and add it to
the mixin I am writing. But I'm not quite sure how to do this without making
lambdas, which seem a little messy and also look to be on the brink of
deprecation (really not trying to start a lambda pro/con thread here).

Any ideas on how to do this with a regular function, or is the way I've done
it the pythonic choice?

James

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

http://www.jamesstroud.com/
Sep 6 '05 #1
6 1396
James Stroud <js*****@mbi.ucla.edu> writes:
Any ideas on how to do this with a regular function, or is the way I've done
it the pythonic choice?


I think you're trying to do something like this:

def FunctionMaker(avar, func, label):
def callback():
avar.set(label)
func()
return callback
Sep 6 '05 #2
Thank you Paul, this makes much more sense.

James

On Tuesday 06 September 2005 02:16 pm, Paul Rubin wrote:
* * def FunctionMaker(avar, func, label):
* * * *def callback():
* * * * * avar.set(label)
* * * * * func()
* * * *return callback


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

http://www.jamesstroud.com/
Sep 6 '05 #3
Paul Rubin wrote:

def FunctionMaker(avar, func, label):
def callback():
avar.set(label)
func()
return callback


I've seen this idiom a lot and I know _what_ it does..... but I can't
work _how_ it does it. How does the name binding work so that "avar" in
the returned function still references the object passed into the
(long-distant!) FunctionMaker() call?

Web pages / turotial ptrs etc gladly accepted.
Sep 7 '05 #4
Thus spake Gregory Bond (gn*@itga.com.au):
Paul Rubin wrote:

def FunctionMaker(avar, func, label):
def callback():
avar.set(label)
func()
return callback


I've seen this idiom a lot and I know _what_ it does.....
but I can't
work _how_ it does it. How does the name binding work so
that "avar" in
the returned function still references the object passed
into the
(long-distant!) FunctionMaker() call?

Web pages / turotial ptrs etc gladly accepted.


The lexical scope within which a function is declared is
made available to the function when it is run. This is done
by storing the values of free variables within the declared
function in the func_closure attribute of the created
function object.

If you want to read more, the keyword you're looking for is
"closure" - a quick search on Google for "python closure"
should satisfy your curiosity handily. There is also a neat
recipe for inspecting the values kept in the func_closure
attribute of function objects directly:

http://aspn.activestate.com/ASPN/Coo.../Recipe/439096


Cheers,
Aldo

--
Aldo Cortesi
al**@nullcube.com
http://www.nullcube.com
Off: (02) 9283 1131
Mob: 0419 492 863

Sep 7 '05 #5
Aldo Cortesi <al**@nullcube.com> writes:
The lexical scope within which a function is declared is
made available to the function when it is run. This is done
by storing the values of free variables within the declared
function in the func_closure attribute of the created
function object.


Actually not quite right:

a = []
for i in range(5):
a.append(lambda: i) # i is free in the lambda
print [f() for f in a]

prints [4,4,4,4,4] instead of [0,1,2,3,4]. The value of i has not
been copied into the closure. Rather, the closure has a cell bound to
the same place that i is bound. So:

for i in range(5):
def f():
j = i # bind a new variable "j" and assign the value from i
return lambda: j # j is free and its value doesn't change
a.append(f())
print [f() for f in a]

prints [0,1,2,3,4]. There's a Pythonic idiom using default args:

a = []
for i in range(5):
a.append(lambda i=i: i) # the "inner" i is free in the lambda
print [f() for f in a]

Closures like may look a little surprising in Python but they're a
standard technique in Scheme. The classic textbook "Structure and
Interpretation of Computer Programming" explains it all. Full text is
online at:

http://mitpress.mit.edu/sicp/
Sep 7 '05 #6
Paul Rubin wrote:
Aldo Cortesi <al**@nullcube.com> writes:

Thanks to Paul and Aldo... one more question on the implementation.

Why is the func_closure a tuple of Cells and not just a tuple of
objects? Why the extra level of indirection?
Sep 7 '05 #7

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

Similar topics

2
by: | last post by:
OK: Purpose: Using user's input and 3 recursive functions, construct an hour glass figure. Main can only have user input, loops and function calls. Recursive function 1 takes input and displays...
9
by: Marek Lewczuk | last post by:
Hello, I'm moving out from MySQL to PostgreSQL and there are some function which are not supported in PG so I'm trying to write my own functions. Currently I have big problem with function IF(),...
8
by: Tweaxor | last post by:
Hey, I was trying to figure out was it possible in C to pass the values in an array from one function to another function. Is the possible in C? ex. y is the array that holds seven values If...
11
by: Marco Loskamp | last post by:
Dear list, I'm trying to dynamically generate functions; it seems that what I really want is beyond C itself, but I'd like to be confirmed here. In the minimal example below, I'd like to...
17
by: Razzel | last post by:
I created this as a test: #include <time.h> main(){ printf(X1: %s\n", putim()); printf(X2: %s\n", putim()); } putim() { time_t t; time(&t); return(ctime(&t));
4
by: ranjmis | last post by:
Hi all, I have come across a piece of code wherein a function returns a function pointer as it seems to me but not very clear from the prototype. As shown below - although return type is void...
2
by: mosesdinakaran | last post by:
Hi everybody, Today I faced a problem where I am very confused and I could not solve it and I am posting here.... My question is Is is possible to return a value to a particular function ...
7
by: jknaty | last post by:
I'm trying to create a function that splits up a column by spaces, and I thought creating a function that finds the spaces with CHARINDEX and then SUBSTRING on those values would an approach. I...
11
by: Antoninus Twink | last post by:
What's the correct syntax to define a function that returns a pointer to a function? Specifically, I'd like a function that takes an int, and returns a pointer to a function that takes an int and...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
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,...
0
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
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...

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.