1.7. Code formatting and documentation

Perhaps one of the greatest achievements of the Python programming language, besides being easy to learn/start with, is its use of indentation instead of brackets. Why? Simply because this makes code formatting mission-critical. Therefore, wrongly formatted Python code will simply not run. That does not mean that you cannot make a mess with Python code as well – believe me, you can!

Warning

Nothing better reveals the general attitude and carefulness of a programmer than looking at the source code. Of course, we all do make mistakes and develop further. But that is no excuse for inconsistencies and lack of care.

The Python community has a strong opinion on how code and docstrings (in-code documentation of functions, methods, classes, and alike) should be formatted, codified in two “Python Enhancement Proposals” (PEP), namely PEP 8 for code formatting and PEP 257 for docstrings.

Therefore, make sure to read both PEPs, now and every once a while:

Furthermore, make use of tools that automatically check for conforming to those two PEPs. PyCharm provides you with quite some helpful hints and tools. Besides that, use code checking tools such as Prospector.

Besides automatic checks and the respective tools, it is important to have code formatting in mind right from the beginning. There is no such thing as “but I just wanted to quickly check something”. If you really want to prototype, use the Python console, but not a script/function. As soon as you use an editor, hence persisting your code, aim at proper formatting and documentation. Every code file will persist once it is created, and potentially live forever. Believe me, it will.

For sensible Python packages, proper code formatting and documentation is not optional. And of course, we are all sensible programmers. Furthermore, scientists rarely program just for fun, but mostly to solve problems or getting help with tedious tasks. As nearly everything in science that is simple is both, trivial and solved already, the complexity of the task at hand as well as the corresponding code will quickly become substantial. The only working strategy to sensibly cope with complexity, though, is to be structured and organised. Hence, take care of your code formatting and documentation.

One last word: Documentation as mentioned above refers to the documentation within the code, i.e. aimed at developers (future-you). While necessary, this is not sufficient for documenting your program. For further details as well as tools for automatically generating nicely formatted documentation from the docstrings, have a look at the respective section of the course.