Closures in Python and other languages

The Python Closure "Cheat Sheet" Page (Part 1)1 shows how to use closures in Python, in direct comparison to the Ruby equivalent.

There are two things I don't understand about Python closures:

First Problem:

Why do Python lambda expressions have to be so verbose? Compare the Python implementation for 'selecting numbers higher than 10' with the Smalltalk (Squeak) code:


>>> filter(lambda a: a>10, [1,2,3,4,5,9,10,11,12])
[11, 12]
#(1 2 3 4 5 9 10 11 12) select: [ :a | a > 10 ]
#(11 12)

Second problem

Python is an object-oriented language. Why aren't methods like filter and map available on the collection objects, instead of relying on the ability of the programmer to find them floating around as simple functions?

Other languages (without closures)

Python's support for passing around closure objects may not be the best available. However, it's of course better to have poor support than none at all. Which leads us to the world of curly-braced languages and Java, which will serve as an example. As Java is Turing-complete just like every other programming language, we can still search collections for items fulfilling certain conditions.

However, passing such a condition to such an algorithm turns out to be harder than expected. The only reasonable way (to me) would be to pass it as an object. This object will need a method returning a boolean value for an object of the type contained in the list. (That's when you need to start thinking about types, classes and interfaces. When you'd like to apply your algorithm to all possible lists, you also need to use generics.) The point I'd like to make is: Java can get very inconvenient when you try to emulate even very primitive closures with it.

As a result, people avoid the generic approach and loop explicitely over collections:

int[] array = {1, 2, 3, 4, 5, 9, 10, 11, 12};
Set<Integer> result = new HashSet<Integer>();
for (int i : array) {
    if (i > 10) result.add(i);

Even for an experienced Java programmer, it takes a couple of seconds to understand what's happening here. Compare that to the Smalltalk example above!

When I started to learn Java, I was amazed at how clear and clean the language was to me. I came from C, that's my excuse. ;-)

Update: Obviously, I am not the only one who noticed these problems in Python; See Guido van Rossum's blog post on that topic: lambda, map and filter must have been highly disputed at that time...


1. Part 2 of the "Python closures" article points out a couple of other not-so-obvious problems with Python closures and climaxes in praise for Smalltalk.

2. Usually, Python programmers would probably circumvent the use of a closure here by using a so-called "List-Comprehension":

[a for a in [1,2,3,4,5,9,10,11,12] if a > 10]</tt></li>