How do I dynamically create functions without lambda?

Antoon Pardon apardon at forel.vub.ac.be
Mon Jan 30 08:02:48 EST 2006


Op 2006-01-27, Russell schreef <russell_turpin at hotmail.com>:
> I want my code to be Python 3000 compliant, and hear
> that lambda is being eliminated. The problem is that I
> want to partially bind an existing function with a value
> "foo" that isn't known until run-time:
>
>    someobject.newfunc = lambda x: f(foo, x)
>
> The reason a nested function doesn't work for this is
> that it is, well, dynamic. I don't know how many times
> or with what foo's this will be done.

I don't see how dynamic is supposed to contradict with
nested functions. I assume from your tekst that foo
has some parameter-like charateristics. So the following
should work.

    def produce(foo):

        def func(x):
	    return f(foo, x)

	return func


    someobject.newfunc = produce(foo)


This kind of code can be generalized. Look for partial 
application or curry.


> Now, I am sure there are a half-dozen ways to do this.
> I just want the one, new and shiny, Pythonic way. ;-)

The new and shiny, pythonic way depends on what you
really want, your question was a bit vague to answer
that.

-- 
Antoon pardon



More information about the Python-list mailing list