In response to Luke Hutteman’s post on continuations, someone offered the
following Python snippet to illustrate filtering:

values = range(10)
for nr in (nr for nr in values if nr%2==0):
    print nr

There are several things that bother me with this code:

  • I count four different meanings for the variable nr, each with a different semantics. You should not need more than two (one as a parameter to for and the other one used inside the body)
  • It mixes procedural, and inverted style and doesn’t contain anything that is object-oriented.  Python does support some object
    orientation, so for more complex pieces of code, you will find yourself constantly mixing three different styles of programming.
  • It mixes filtering (nr % 2 == 0) and business logic (print), making it
    hard to parameterize either.

Here is a Ruby way of doing the same thing:

  .find_all { |it|
    it %2 == 0
  .each { |it|
    puts it;

What I like about it:

  • It’s object-oriented, which makes it regular:  each object is applied a
    message and the result is then piped into the next treatment.
  • Filtering and business logic are clearly separated, so you can improve this
    example by substituting blocks (strategy pattern)
  • It minimizes the number of intermediate variables (only one:  it and it is only used as a parameter and inside the body of the closure.

The latter solution feels much more natural and intuitive to me, whereas most of my time in
Python is typically spent

  • Filtering out the omnipresent and totally useless keyword self.
  • Wondering if the object I am staring at responds to a method or if I need to call a global function on it
    (such as range in the example above).

I guess I’m too young for Python and spoiled by modern languages :-)