anonymous functions? class?

Erik Max Francis max at alcyone.com
Thu Nov 15 21:41:46 CET 2001


Peter Bismuti wrote:

> I want to pass a function as an argument but don't want to have to
> define it
> globally.
> I think the proper terminology for this is "anonymous".
> 
> The way I *don't* want to do it:
> 
> def foo():
>     pass
> callFunction(foo)
> 
> The way I want to do it:
> 
> callFunction(def foo(): pass)
	...
> Something like that. Here the function has not been named and was not
> defined outside of the call.   Can this be done in Python?

Yes.  Python has lambda functions for this, although there are some
restrictions:   lambda functions have to take at least one argument
(otherwise what's the point), and they can only evaluate to expressions,
rather than whole statements.

>>> map(lambda x: 2*x, range(10))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/  \ Laws are silent in time of war.
\__/ Cicero
    Esperanto reference / http://www.alcyone.com/max/lang/esperanto/
 An Esperanto reference for English speakers.



More information about the Python-list mailing list