anonymous functions? class?

Werner Schiendl ws-news at gmx.at
Fri Nov 16 06:29:16 EST 2001


Hi,

depending on what you want to achieve, nested functions may be what you
want.
Python allows nesting of function definitions:

>>> def consumer(func):
...  print "The function returns ", func()
...
>>> def caller():
...  def producer():
...   return "Hi from nested function!"
...  consumer(producer)
...
>>> caller()
 The function returns  Hi from nested function!
>>> producer
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
NameError: name 'producer' is not defined
>>>

As you can see, the function defined within caller() is not visible from
outside.

hth
Werner

"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
>
>





More information about the Python-list mailing list