How do I dynamically create functions without lambda?
James Stroud
jstroud at ucla.edu
Fri Jan 27 16:17:34 EST 2006
Kay Schluehr wrote:
> Russell wrote:
>
>>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.
>>
>>Now, I am sure there are a half-dozen ways to do this.
>>I just want the one, new and shiny, Pythonic way. ;-)
>
>
> If you want to code partial application without lambda I recommend
> using the code presented in the accepted PEP 309 that will be
> implemented in the functional module in Python 2.5.
>
> http://www.python.org/peps/pep-0309.html
>
> Kay
>
For anyone who got my last post: sorry, typos....
def f(foo, x):
print foo, x
def make_newfunc(foo):
def _newfunc(x, foo=foo):
f(foo, x)
return _newfunc
foo = 42 # or "dynamically generated"
newfunc = make_newfunc(foo)
newfunc(14) # output will be "42 14"
newfunc2 = make_newfunc(69)
newfunc(21) # output will be "69 21"
If this doesn't fit your needs, then please elucidate.
More information about the Python-list
mailing list