"Updating" lambda functions

exarkun at divmod.com exarkun at divmod.com
Thu Sep 16 10:39:15 EDT 2004


On 16 Sep 2004 14:07:20 GMT, Oliver Fromme <olli at haluter.fromme.com> wrote:
>Hi,
> 
> I'm trying to write a Python function that parses
> an expression and builds a function tree from it
> (recursively).
> 
> [snip]
> 
> I need to "update" a lambda function, like this:
> 
>         fu = lambda x: x
>         ...
>         fu = lambda x: fu(x) + 17
>         ...
>         fu = lambda x: fu(x) * 3
> 
> Of course that doesn't work, because fu is resolved
> when the lambda is called, not when it's defined, so
> I'll run into an endless recursion.
> 
> My current solution is to define a helper function
> which passes the lambda through its argument:
> 
> [snip]
> 
> That works, but it strikes me as unclean and ugly.
> Is there a better way to do it?

  One alternative:

>>> fu = lambda x: x
>>> fu = lambda x, fu=fu: fu(x) + 17
>>> fu = lambda x, fu=fu: fu(x) * 3
>>> fu(3)
60

  forcing definition-time binding of the name "fu" in the lambda's local scope.

  It strikes me that the y combinator should help here, but maybe that's just wishful thinking.

  Jp



More information about the Python-list mailing list