[Edu-sig] Re: ..., closures, ...

Jeff Sandys sandysj at juno.com
Mon Jan 26 18:39:20 EST 2004


Kirby said:
> Here's the same example in Python, in shell mode:
>
> >>> def newprint(x):
>         def anon(y):
>                print "%s, %s!" % (x,y)
>           return anon
>
> >>> h = newprint("Howdy")
> >>> g = newprint("Greetings")
>
> >>> # Time passes...
>
> >>> h("world")
> Howdy, world!
>
> >>> g("earthlings")
> Greetings, earthlings!
>
> =======
>
> I use 'anon' for anonymous function, but that's sort of an oxymoron, as
> 'anon' is the function's name, insofar as functions have a name.  If 
> you ask for string representations of these references, you get:
>
>
>  >>> g
>  <function anon at 0x0089A030>
>  >>> h
>  <function anon at 0x00ACEC70>
>
> If you want to make it clear in a different way, that these functions 
> are anonymous, you could use lambda like this:
>
> >>> def newprint(x):
>           def anon(y):
>                  print "%s, %s!" % (x,y)
>           return lambda y: anon(y)
>
> >>> h = newprint("Howdy")
> >>> g = newprint("Greetings")
> >>> h
> <function <lambda> at 0x00ACEB70>
> >>> g
> <function <lambda> at 0x00ACEE30>
>
> I guess I have no strong preference for either format.  However, this 
> does show it's easy for lambda to represent functions of any length, 
> with print statements included.
>

Since lambda means anonymous you don't need to, def anon(y):

 >>> def newpr(x):
 ...     return lambda y : "%s, %s!" % (x,y)
 ... 

 >>> h = newpr("Howdy")
 >>> g = newpr("Greetings")
 >>> h("World")
 'Howdy, World!'
 >>> g("earthlings")
 'Greetings, earthlings!'
 >>> g
 <function <lambda> at 0x200f35b0>
 >>> h
 <function <lambda> at 0x200ecf70>

Of course this method returns a string instead of printing the message.
If you want to print the message you need to, def anon(x): 
because print is not a valid lambda expression (why?, I don't know):

 >>> def newprint(x):
 def newprint(x):
 ...     return lambda y : print "%s, %s" % (x,y)
   File "<stdin>", line 2
     return lambda y : print "%s, %s" % (x,y)
                          ^
 SyntaxError: invalid syntax

 >>> 

Closures are cool,
Thanks,
Jeff Sandys



More information about the Edu-sig mailing list