[Tutor] function that returns a fn

Kent Johnson kent37 at tds.net
Sat Dec 11 20:34:18 CET 2004


Yes, it really is that simple. :-)

A common example is a function that makes a function which adds a constant to its argument:

 >>> def makeadder(n):
...   def adder(x):
...     return x + n
...   return adder
...

Make a function that adds 3 to its argument...note there is no special syntax for the return, just 
assign to a name
 >>> add3 = makeadder(3)

add3 is a function:
 >>> add3
<function adder at 0x008D68F0>
 >>> add3(4)
7

Make another function to add 5:
 >>> add5 = makeadder(5)
 >>> add5(10)
15

add3 still works, it is a separate function with its own binding of n:
 >>> add3(2)
5

Kent

Nandan wrote:
> I'm looking for resources to help me with a fn that returns a fn after
> binding one of its arguments (aka currying, like the bind1st of C++)
> 
> Considering Python syntax is quite straightforward, this is my first try:
> 
> def getjlistrenderer(opname):
> 	def listrender():
> 		# use opname, eg ops=getlist(opname)
> 		# or set local fn variable
> 		return renderer;
> 	return listrender;
> 	#?or f=listrender(); return f;
> 
> Is it really as simple as this? Or will I always return the same function
> definition? I need it to return a 'new' function for each call to
> getjlistrender() .. do I need to create a new fn with f=listrender() ?

No, this is a call to listrender, it will return the renderer object not a function.

> 
> Any pointers to pages/books etc. appreciated. I am looking through my
> books too, but thought I'd get some more pointers as well. Web searching
> so far only shows lambda, which is one-liner, and that won't do.

There are several currying recipes in the Python Cookbook:
http://aspn.activestate.com/ASPN/search?query=curry&x=0&y=0&section=PYTHONCKBK&type=Subsection

Searching the cookbook for 'closure' also gives some recipes that might be of interest.

Kent

> 
> Thanks!


More information about the Tutor mailing list