CHAPTER 12 · 5 lessons · 62 exercises

Writing it cleanly

From code that runs to code that gets read. Write for yourself in three days, and for the person next to you.

0 / 62 solved

The last chapter is about turning code that runs into code that gets read.

Code spends far longer being read than being written, and the first person to read yours is usually you, three days later. Whether that person has to say "what was this again?" makes an enormous difference to how fast you go from there.

First, PEP 8. Python has an official style guide — four spaces to indent, lowercase names with underscores, one space either side of an operator, and so on. None of it is enforced. Python users everywhere follow it anyway, because when the writing is uniform you get to spend your attention on what the code says.

Next, the docstring. Put """...""" just below a function or class and Python treats it as that thing's description. The difference from a comment is that a program can read it back out. A great deal of library documentation is in fact assembled from these.

Then type hints: writing the kinds in, as in def add(a: int, b: int) -> int:. Python runs fine without them, but they tell the reader what you meant, and they let your editor point out mistakes. Plenty of modern Python is written assuming they are there.

Last is the dataclass. Remember writing line after line of self.name = name in __init__ back in Chapter 5? For a class that only holds data, one extra line — @dataclass — does away with all of it. Less to write means the parts that matter stand out.

Get here and the Python course is done. You have been through the grammar, you can read other people's code, and you can write code others can read. What you build next is up to you.

Lessons in this chapter

Write for the reader

  1. 103Write the way everyone else writesPython has an official style guide called PEP 8. Nothing makes you follow it, and the whole world does.Go to the exercises
  2. 104Write a description that can be read backA description written in """...""" can be read back out of the program with __doc__. That is the decisive difference from a comment.Go to the exercises

Spell out what you meant

  1. 105Writing down what kind of value it isWrite a: int and the reader knows what you meant. Python itself checks nothing while it runs.Go to the exercises
  2. 106Writing a data-only class shortAdd one line of @dataclass and __init__, a readable display and == all come along with it.Go to the exercises
  3. 107Finishing with code that gets readA round-up bringing PEP 8, docstrings, type hints and dataclasses together. No basics here — ten practice questions only.Go to the exercises

This is the last chapter of the course.