Using X twice in the same expression probably won’t work (this can be solved)

Since calling X evaluates it, it can’t emulate method calls. For that you have to do use call, like: X.upper.call() (‘hello’) –> ‘HELLO’.

Not all operations can be “captured”. For example, the “in” operator. For that you have to use X.in_( … ), like: X.in_(range(10)) (5) –> True

Not all attributes will be accessible

More problems? Likely.

Conclusion

While not innovative nor a complete solution, I believe X can be a useful replacement for some uses of anonymous functions, providing a shorter and simpler syntax which is easier to read and understand.

It is provided here in full, in hope that it will be useful to my readers (Improvements and fixes are welcome):

Like this:

LikeLoading...

Related

This entry was posted on Saturday, November 1st, 2008 at 21:31 and is filed under Python. You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.

Post navigation

9 Responses to Fun While Avoiding Lambda (Python)

It’s a pretty fun exercise, I guess. Boost for C++ has exactly that as boost::lambda, and it is horrifying to use, partly because C++ does not have closures. C++ is now (for a certain value of “now”) adding new lambda syntax (not a particularly comfortable one), because these things should just be handled as part of the language. There’s also a performance penalty for a non-trivial use of X.

Personally I am quite in favor of the current Python lambda syntax. I dislike replacing simple “lambda employee: employee.salary” expressions with something as obscure as operator.attrgetter(“salary”). I find it harder to read and understand, but to each his own I guess.

There is a performance penalty, that’s true. However, a more serious implementation can solve this problem, and also make X-expressions pickle-able at the same time.

I’m don’t think ” X.salary ” is harder to read or understand than its lambda counterpart. I think the opposite is true.
Perhaps in some cases where the context is not clear, argument names can add some clarity. But in my experience it’s rare. Also, you can do ” employeeX = X ” :)

Alain and Foord:
__contains__ can only return a bool. No matter what I return in it, it’s converted into True or False.

Evan:
It’s a good point, but I don’t think it’s much different from any utility library that you use in your code. When I first started using itertools, people at my office would ask me “what does chain do, what does groupby do” etc.