Python is a very versatile programming language, and it has a very flexible syntax. Therefore, it is also very easy to write ugly code in python. This chapter reviews a number of guidelines and conventions widely accepted by the community. At this stage of the lecture we won't go in depth for each of these points, but try to keep them in mind while writing your assignments and also while checking my suggested solution to the assignments.
PEP 8 is a style guide for python code. It introduces new rules where the syntax leaves them open. As an example:
# OK syntax but not PEP8 compliant
a=2*3
# OK syntax *and* PEP8 compliant
a = 2*3
PEP8 gives guidelines, not strict rules. It is your choice to comply with them or not. As a matter of fact however, many open source projects have adopted PEP8 and require to use it if you want to contribute. If you want to use it too, a good choice is to turn on PEP8 checking in your favorite IDE (in Spyder: Tools -> Preferences -> Editor -> Code Introspection/Analysis ->
Tick Real-time code style analysis
for PEP8 style analysis).
The text space that code is taking is less important than your time. Give meaningful name to your variables and functions, even if it makes them quite long! For example, prefer:
def fahrenheit_to_celsius(temp):
"""Converts degrees Fahrenheits to degrees Celsius."""
to the shorter but less explicit:
def f2c(tf):
"""Converts degrees Fahrenheits to degrees Celsius."""
Separation of concerns is an important design principle for separating a computer program into distinct sections, such that each section addresses a separate concern. This increases the code readability and facilitates unit testing (as we will see).
For example, a scientific script can often be organized in well defined steps:
Each of these steps and sub-steps should be separated in different functions, maybe even in different scripts. When discussing your assignment solutions, we will always discuss how your code is organized for readability and testing.
Write comments in your code, and document the functions with docstrings. We will have a full lecture about it, but it's good to start early. Here again, there are some conventions that I recommend to follow.
Note that this is useful even if you don't plan to share your code. At the very last there is at least one person reading your code: yourself! And it's always a good idea to be nice to yourself ;-)
Abstruse Goose made a funny comic about code documentation: http://abstrusegoose.com/432
import this
Back to the table of contents, or jump to this week's assignment.