Loading…

Read PEP 8 and write code as Guido van Rossum does

In a bid for an attractive and comprehensive code, Python community needs reference point: what is good and what is bad. The programming language creator Guido van Rossum and his partner Barry Warsaw have described pretty good Python code style in PEP 8.

The provided brief overview of PEP 8 will help you orientate in these principles.

Why do you need PEP 8

The particular uniform design style makes the actual code understandable for the programmers and their colleagues with different levels of experience.

Ideally, the most complex bit of program code should be clear from the first reading. This simplifies team development and practicing beginners, allows you to quickly go back to your own long-standing projects.

Guido van Rossum

PEP 8 touches upon the structure and the code visual appearance:

  • choice of source code encoding;

  • grouping instructions on importing modules;

  • The maximum length of a code line is recommended up to 79 characters, and for docstring lines – 72 characters;

  • use of indents – tabs and spaces;

  • using blank lines to break code into blocks and highlight top-level functions;

  • use of comments;

  • the naming of variables, constants, classes and instances, functions, arguments, modules, packages;

  • selection of the level of accessibility of classes and methods (public, private, API subclasses), as well as the order of their inheritance.

Regardless of whether you write code in PyCharm, Notepad++ or another editor, it is better to save .py files in UTF-8 encoding. For Python 3, it is recommended officially; for Python 2, ASCII encoding is formally required, but it does not support Cyrillic, therefore it is reasonable to use the same UTF-8. If for some reason you really need an “alternative” source encoding, be sure to include it in the comments in the first line of the file:

 

# coding: cp1251

print("The text is in Windows 1251 encoding.")

input()

 

Interpretator will output an error without this comment.

PEP 8: Spaces are important for Python

The most well-known requirement of PEP8 on Python code style is spaces. With the help of this think, you form the structure of conditions, loops, functions. Traditionally, developers put four spaces for a single margin level. For example:

if sunny:

    print("The sun is shining!")

else:

    pass

 

Theoretically, you can use a different number of spaces: 2, 8, etc. The main thing is that it coincides across the code – otherwise, the interpreter will swear. But 4 is the “gold standard” of the community: set quickly, familiar to read.

 

In someone else’s code, you may encounter another type of indent — tabulation. PEP 8 categorically does not recommend it, but with one reservation. If you are finalizing a ready project, where indents are made by tabs, stick to the standard you have adopted. If the code is inconsistent, replace everything with spaces.

 

Interesting fact: the 2017 study on StackOverflow showed that programmers who indent spaces earn almost 9% more than Tabs lovers.

When you should not put spaces in Python

  1. Immediately after the opening bracket and before the closing bracket: (x) – this is not necessary.

  2. Before parentheses when calling the argument. Wrong: arg (1). That’s right: arg (1).

  3. Before the parentheses of the index and slice: dict [‘step’] = map [i].

  4. Between the name of the parameter / argument, the “=” sign and the value: min (a = 10, b = input).

 

And please do not align the code with extra spaces. On the sides of the “=” put no more than one space. Do not try using indentation to make the block look like a table or table of contents. This slows down the reading and understanding of what is written.

It is better to put one space on the sides of the signs of arithmetic operations:

x = (y + 1) * (y — a)

It is not recommended to write down several commands in a single line through a semicolon. Instead of “act1(); act2(); act3()”, it is highly recommended to do the following:

act1()

act2()

act3()

Do not forget to put space after «#» symbol in comments.

PEP 8 and objects’ names in Python

If you want to name a variable as one character, avoid lowercase Latin l (“el”), uppercase I (“ai”), and uppercase O – in some fonts they are indistinguishable from numbers 1 and 0, respectively. With the capital L there are no such problems.

Objects of different types must be different in the format of the name entry. So the reader quickly realizes what is written. Here are the recommendations:

  • Classes and exceptions — LikeThis

  • Constants  — LIKE_THIS

  • Variables and arguments — like_this

  • Functions and methods —   like_this as well, but it is allowed to use likeThis if you finish other’s or old code where such a format is already set.

When the argument name of your functionality has the exact word reserved in Python, do not pose the spelling, but put an underscore at the end. Like this: “input_”.

Truth verification with equal signs

Do not use two equal signs (==) to validate boolean values. Rather, use if or if not with the name of an object (for example, a variable):

 if  i_have_apples:

# doing this

 if not  key_obtained:

# doing this

In case you want to compare something with the value “None”, use is or is not rather than assessment operators.

Keep in mind that empty listings, tuples, and sequences fails to false.

Other important info about Python in PEP 8

  • In the style guide, there exists a suggested order of importing segments: first load the segments of the standard collection, then from third-party your local library, at the conclusion – your own modules.

  • Whenever handling exceptions, use name binding syntax that is equally compatible with Python 2 and 3:

try:

    something()

except Exception as exc:

    raise AnotherDamnError(str(exc))

  • Attempt to minimize the amount of code in a try… except constructions. This will help to avoid difficult to discover errors.

  • In case possible, choose a format that works for all Python implementations: CPython, Jython, PyPy, as well as others.

Automatic PEP verification of Python code

While you are creating small projects, it is not a problem to read the code for errors and elegance violations. In the work on large projects, you will get help from automatic code checking scripts. PyCharm inspections written on runtime. But what to do if you need to work without an IDE? GitHub has a entire section of the Python Code Quality Authority, where utilities for increasing the quality of the program code are stored, including for exploring the style for conformity with the PEP eight: flake8, pycodestyle, pep8-naming. Whenever needed, you can incorporate Flake8 into the development atmosphere.

Conscious need

Remember that you need to know PEP 8, but not always follow it. Spaces will have to be highly regarded, otherwise the interpreter will refuse to execute your code. But in the manual itself, there are cases when the programmer, at their own discretion, can and should violate the recommendations.

If a particular code becomes ugly when fitting to the style, “we don’t need such hockey. ” For example, if a breakdown of 72 characters makes reading difficult, PEP 8 indicates extending a line to 80 or even 100 characters – depending on what is convenient for you and your development team. Clear restrictions apply only to public library projects.


Leave a Comment