Make Readable Code

Make Readable Code#

I hate it when a piece of code is passed to me that I cannot understand on itself.

This rule pretty much speaks for itself, and is also the Golden Rule most closely linked to PEP 8. So rather than rewrite it, we reccommend that at the start you focus on the four aspects of PEP 8 listed here. And don’t forget to read the document every once in a while to refresh your memory and see examples.

  • blank lines are great for making space, but don’t overuse them

  • use indentation to make your line breaks readable

  • space around operators, especially =, +, -, and after function arguments

  • incorporate a maximum line length

The 79 character maximum line length reccommendation in PEP 8 is often a contentious one. It’s important to limit line length because not all documentation software, word processers, text viewers, etc, know how to present long lines of code. Line breaks may introduced in a way that makes the code completely unreadable, or worse, large portions of your code may not be visible when printed. However, you will find that in practice it is very difficult to limit your lines to 79 characters, especially if you are using descriptive variable and function names (Golden Rule 1). On the other hand, once you learn a few tricks for making easy line breaks (below), it becomes much easier. So, our advice is to definitely incorporate a maximum line length in your code, but start with 79 and feel free to increase it doesn’t work for a certain project. It’s generally not a problem to increase the maximum length to 100 or even 120 characters, and autoformatters can be set up to help enforce this. Whatever you do, just make sure that your lines don’t get cut off or broken in a way that makes your code unreadable. To help, we provide a few tips for adding line breaks to your code. Can you find the PEP 8 violations in this example? Try copying this code into pep8online.com to test yourself.

# You can always break items inside brackets wherever you like
my_sum = sum([1,
              2])

bad_bracket_alignment = sum([1,
                             2
                            ]) 

# When you split function arguments use indentation to make sure
# the entire function can be easily read with breaks
OK = sum([1, 2, 3, 4, 5, 6, 7, 8,
          9, 10, 11, 12])

not_good = sum([1, 2, 3,
           4, 5, 6,
               7, 8, 9, 10, 11, 12])

much_better = sum([1, 2, 3, 4,
                   5, 6, 7, 8,
                   9, 10, 11, 12])

# Line breaks with strings
this_is_one_string_in_two_parts = ("This string has to be split in two. "
                                   "Notice how this line is aligned above.\n")

print(this_is_one_string_in_two_parts)