anonymous functions,classes?

Jeff Shannon jeff at ccvcorp.com
Thu Nov 15 14:29:20 EST 2001


Peter Bismuti wrote:

> Anonymous was the word I was looking for in my previous post.  I want to
> pass a function as an argument but don't want to have to define it globally.
> 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.

True, but thanks to nested function defs, you also don't need to define the
argument-function globally.

(Note--this uses nested scopes, thus requires Python 2.x; in 2.0,
from __future__ import nested_scopes is required.)

def Outerfunction(foo, bar):
    def Inner():
        return bar * 5
    return foo + Inner()

You can also use lambdas, as has been pointed out by others.  But really, I
can't see where there's any harm done by defining a function by name just before
you need to use it.  (If you're *that* worried about polluting the namespace,
you can always del it when you're done...)

(Suddenly I find myself missing Alex Martelli and his long discourses... :) )

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list