Writing it cleanly

INPUT · Slides

Write the way everyone else writes

01 / 07

It runs, but it is hard to read

The code below runs perfectly well. No errors. All the same, there is something awkward about reading it.

The two sides of the = do not line up, and there is loose space inside the brackets of print. The meaning is identical, and yet your eye keeps catching.

price=250count =4print( price*count )

Result

1000

02 / 07

PEP 8, the official answer

For all these small questions of how to write something, Python has an official answer. It is a style guide called PEP 8.

Four spaces to indent, one space either side of an operator, a space after a comma. Everything you have been doing without thinking since Chapter 1 is written down in there.

price = 250count = 4print(price * count)

Result

1000

03 / 07

How to name things

PEP 8 settles naming as well. Each kind of thing has its own shape, so the name alone tells you what you are looking at.

  • Variables and functions — lowercase words joined with underscores: total_price, price_with_tax. This is snake_case
  • Classes — every word capitalised and run together: Fruit, MoneyBox. This is PascalCase
  • Constants (values you never change) — capitals throughout: MAX_COUNT, SALES_TAX

None of the three is enforced. But because their shapes differ, a name says what it is before you have read a single other line.

MAX_COUNT = 3class Fruit:    def __init__(self, name, price):        self.name = name        self.price = priceapple = Fruit("apple", 150)count = 2total_price = apple.price * countprint(total_price)print(MAX_COUNT)

Result

300
3

04 / 07

Where the spaces go

Any number of spaces will run, but here is how PEP 8 puts it.

  • One space either side of an operator: a = 1 + 2
  • One space after a comma: print(a, b), [1, 2, 3]
  • None at all just inside a bracket: print(x), never print( x )
  • Nothing left at the end of a line. You cannot see it, and it turns up later in the diff to annoy you

Too many spaces is as hard to read as too few. One is the watchword.

scores = [80, 95, 70]total = scores[0] + scores[1] + scores[2]print(total, len(scores))

Result

245 3

05 / 07

How to lay a file out

It is not only what happens within a line. The order of the file as a whole has rules too.

  • Put your import lines at the top of the file, together. Not just before the thing that needs them
  • Leave two blank lines between function definitions. The joins between blocks then show up to the eye
  • Do not let a line get too long. PEP 8 suggests 79 characters; when it runs over, pull part of it out into a variable

Two blank lines may feel like a lot. Open any real Python and you will find it is almost always written that way.

import mathdef circle_area(radius):    return math.pi * radius * radiusdef rectangle_area(height, width):    return height * widthprint(round(circle_area(2), 2))print(rectangle_area(3, 4))

Result

12.57
12

06 / 07

Nothing enforces it. Follow it anyway

You will have worked this out by now: break PEP 8 and the program still runs. No error, and nobody tells you off.

Python users everywhere follow it regardless, because when the writing is uniform you get to spend your attention on what the code says.

When everyone writes differently, you have to work out "how does this person write?" before you can get at the meaning. That is effort spent on nothing at all. If everyone writes to one shape, the effort drops to zero.

07 / 07

Let the tools do it

You do not have to hold all of it in your head. There are tools that check whether code follows PEP 8, and tools that tidy it for you. In real work it is usually set up so that it straightens itself out the moment you save.

So what you want to take away is not a character count. It is the feeling that lining things up makes them readable.

The next lesson takes what comes after lining things up: a way of putting the description of the code inside the code itself.