Python Notes

Sunday, February 20, 2005

A curious remark about code structure in Python

Python never ceases to surprise me. Today I noticed something really simple; it's one of those things that can go on unnoticed for ages, but make the code read better.

When coding in several other languages -- C, C or Delphi -- there's the need to declare things before using them. As a consequence, class declarations tend to be organized to satisfy this restriction (of course, there are forward declarations, but that's the practice anyway). When debugging, or mentally tracing a sequence of calls, or simple doing a review of the code, more often than not, we end up reading the code 'backwards' - the most common entry points are usually located at the end of the source file, and more specifi methods are located before them. After some time, we get used to it, and we don't notice it anymore.

Then today, I noticed today, by accident, that the ordering of the methods in my Python classes is much more intuitive. Starting with the __init__, the methods are organized in a clear 'top-down' approach. The effect is that the source code can be comfortably read from top to bottom, as if it was an article.

I don't know about other programmers 'mental model' in this regard, but it seems to me that we are able to mentally 'push' the yet undefined symbols to check them down the code. Whatever it is, I found it very interesting, and yet another strong point for Python.


Post a Comment

<< Home