[Python-ideas] Another way to avoid clumsy lambdas, while adding new functionality

Andrew Barnert abarnert at yahoo.com
Wed Mar 5 02:16:38 CET 2014


On Mar 4, 2014, at 17:05, João Bernardo <jbvsmo at gmail.com> wrote:

>> * assign a bill to `a` so that `a` will evaluate to the value of the name `foo` any time that `a` is evaluated, in the scope of that evaluation
>> 
>>    a = $foo
>> 
>> * as above, but always plus one
>> 
>>    a = $foo + 1
>> 
>> * make `a` a bill that evaluates to the value of the name `foo` at the time that `a` is evaluated, in that scope, plus the value of `bar` **at the time and in the scope of the assignment to `a`**
>> 
>>    a = $foo + bar
> 
> 
> You can do all that programmatically. No need for magic operators.
> Check this module as a proof of concept: https://github.com/jbvsmo/funcbuilder
> 
> foo = FuncBuilder()
> a = foo + 1
> # Then evaluate a with a function call
> 
> For it to do exactly what you want, you just need override the evaluation function (Funcbuilder.__call__) to load names from current frame locals or something.
> BTW, I don't recommend using that on real code because it is extremely experimental (unless you're a hipster... In this case, carry on).

I posted something similar in the first of the many improving-lambda threads this month, but it had a lot of little problems and one big one.

The big one is that not every expression can be caught by operator overloading (foo[i] is fine, but lst[foo] isn't). And call expressions are one of the most important kinds of expression, but you can't catch that--or, rather, if you _do_ catch it, then you have no way to call the resulting object.

The same idea in C++ doesn't have that last problem because C++ is statically typed, and you can use an implicit cast from autolambda object to function object to get from an object whose call operator builds a call expression to one whose call operator evaluates the expression. But that doesn't work in Python. 

I wrote a blog post that gets into this further, but I can't find the link from my phone. I included it in an earlier message in the thread.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140304/07f6bb2f/attachment-0001.html>


More information about the Python-ideas mailing list