This article is about Python style. Compared to the C++ world, there are pretty rigid conventions implemented in the language itself as well as in the Python ecosystem. That makes this topic kind of surprising and worth writing some lines about.
One of the most obvious things about the language – as you probably have noticed already – is the lack of any token for block separation. Instead of having a pair of curly braces for introducing a new code block, simply the level of indent is used.
I still find this surprising sometimes, especially because not even mixing spaces and tabs is allowed in recent versions of the language. Apparently though, people got used to it and seem to utilize the advantages of this strict style requirement. Consider the following C++ snippet:
if (flag == true) foo(); bar(); baz();
As the indent levels suggest, the author wants both foo() and bar() to be called depending on flag. Unfortunately, C and C++ compilers do not care about indent, which leads to unexpected behavior. In this case, only the call to foo() depends on the value of flag. Both bar() and baz() get called unconditionally.
By the way, this is exactly what made the famous goto fail bug possible. Such a flaw couldn’t have happened in Python. Here’s the equivalent to the example from above:
if flag == True: foo() bar() baz()
Here, the behavior perfectly matches the author’s intention.
If you look at some Python projects out there, you may notice that many of them adhere to a common style – aside from the indent convention mentioned above, which is integrated into the language anyway. The style guide described in PEP 8 seems to be widely adopted.
One thing I do not understand about this guide though is the convention for method names. It is stated that all methods must have lowercase names, where words are separated by underscores, e.g. do_some_work(). Compared to camel case (like doSomeWork()) i find this rather hard to write. Maybe it’s a bit easier to read, but I’m not sure about that yet.
Support in Vim
The Vim text editor has out-of-the-box support for Python block indents. With filetype plugin indent on, it adheres to the rule four spaces, no tabs for all .py files you edit.
Is there anything I’ve missed? Feel free to leave me a comment or contact me on twitter: @ronalterde.