anonymous functions? class?
Justin Dubs
jtdubs at eos.ncsu.edu
Thu Nov 15 15:48:16 EST 2001
"Peter Bismuti" <peterb at cortland.com> wrote in message
news:3bf4240d$1 at 207.229.64.20...
> 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)
>
>
> I'm guessing this can't be done because of Python's indenting syntax.
> In ECMAscript you can send a function as an argument that is defined on
the
> fly such as:
>
> callMyFunction( new Function(){ blah blah })
>
> Something like that. Here the function has not been named and was not
> defined outside of the call. Can this be done in Python?
>
> Thanks
>
>
If it's a short function than you can use lambda syntax as follows:
mul = lambda x, y : x * y
This defines a function called mul that takes two arguments, x and y, and
returns their product. The generic form is:
lambda args : value
So, you can do this:
functionToCall( lambda x : x + 1 )
Hope that helps. Have fun,
Justin
More information about the Python-list
mailing list