Translation in python of C++ idiom

Sean 'Shaleh' Perry shalehperry at attbi.com
Fri Aug 9 18:34:32 CEST 2002


> 
> Are you sure the paper wasn't entitled "Minimalism: Kelvin's Guide to
> Unreadable Code Spew"? :) For me, the density of that code is 
> intolerable.
> 

I stopped to read the article before making a decision on its validity.  It was
a difficult choice (-:

I have read Scott Myer's "Effective C++" series.  In a way Mr. Henney is making
a similar assertion.

Given the language of C++ the following:

for (int i = 0; i < final; ++i) {
  do stuff on a container
}

should if at all possible be replaced with something like

for_each(container.begin(), container.end(), action),
copy(), transform, etc.

The point being you are no longer babysitting a for loop and the word
'for_each' has semantic meaning.

This is useful and important.  Getting away from the ++i style of code helps us
focus on the important issues.

In Python we seem a similar goal in our use of functions.  It is recommended to
encapsulate common items in usefully named chunks.  Now you have:

for item in container:
  action(item)

or even

map(action, container)

which is about as useful as the STL functions.

C++ (and C) can be overly verbose and it is easy to walk into the path of low
level details.  That is why it is still a useful language.  So extoling the
virtues of abstraction and minimalism is a good thing.  In Python we are by
nature more concise and clear because the power of abstraction and the object
model gives us for free and as part of the language what the STL gave C++ as an
add on.

I believe the equivalence of his paper for python is to let the language do
the work for you.

i = 0
while (i < end_point):
  action(container[i])
  i += 1

why would you write that?  A coder coming from a pascal/c background might.




More information about the Python-list mailing list