PEP8 — Python Code Writing Guide
If a programmer has a task to write an application or a library for himself or herself, or if there are no plans to involve other people to work on the project in the future, he or she can really do with code whatever he or she wants. The golden rule for single programmers is as follows: “As long as I understand my code, I don’t need to do anything else”.
If a programmer works in a team (or such work is planned soon), there is a need to document and test the source code, as well as to correctly name variables, observing the python style guide. This is necessary to inform colleagues about their intentions directly through the source code. Otherwise, the project will always face a threat of a large number of errors caused by the influence of some code fragments on other — regressions.
Teamwork also implies using non-trivial programming techniques — design patterns. With their help, the code is broken down into necessary structural elements which are documented and tested independently from each other. If all programmers working on one project speak one “language” of the application architecture, everyone will be able to write such independent modules. The probability of their “breakage” will tend to zero. Design patterns, unit tests, code documentation is a kind of written agreement between programmers on how they work on a particular project.
PEP8 Naming Style
Coherence within the project is very important. But coherence within a module or function is the most crucial. You should know python file naming conventions. It is very important.
1. Variables, functions, methods, packages, modules use higher case letters, words use a lower emphasis between them: e.g. check_pass or _socket.
2. Classes and exceptions use capital letters at the beginning and an upper case between words instead of space, for example, CamelCase or JustCounter.
3. Protected methods and internal functions use emphasis sign in front of words: _start_engine
4. Private methods use two underscore signs in front of them: __foo(self, …).
5. Constants are written using upper case: IP_SERVER=’111.11.11.11'.
6. It’s better to use the reverse notation:
elements = …
active_elements = …
defunct_elements = …
It is very important to understand when you can move away from the recommendations and when not. Exist cases when the manual is not applicable. Use your own experience if you don’t know what to do. Just look at other codes and decide which one looks better. Don’t be afraid to ask!
PEP8 Importing
Each import, as a rule, must be on a separate line without exceptions. Imports live at the beginning of the file, their place is after comments to the module and documentation lines, but before constants.
Import grouping order:
1. Built-in Python packages.
2. Third-party packages.
3. Local packages.
Experienced programmers recommend using absolute import. Absolute import works nicer when the imported system is set up incorrectly. Also, it is more readable and provides clear error messages.
PEP8 Line length
Exist many devices where the length of the line is limited to 80 characters; also, by limiting the width of the window to 80 characters, we can place several windows next to each other. Automatically porting lines on such devices will break formatting, and the code will be harder to understand. So confine the length to 79 characters.
The preferred way to move long lines is to use an implied line continuation between normal, square, and curly brackets. Long lines can be split into several lines in brackets.
even_numbers = [var for var in range(400)
if var % 4 == 0]
PEP8 Spaces
The best way to indent is to use spaces. They should be made only using tabulation. The code that has tabs and spaces should be corrected. When you call an interpreter on the command line with the parameter -t it will give a warning if you use a mixed style in indents. When you run the -tt command-line interpreter, you will get errors in these places.
In new projects use only spaces for indents. In many editors, you can easily do it.
1. Put a space between a colon and the value of the key in the dictionary:
names = {‘gagan’: 456}
2. Put a space between operators in case of arithmetic and assignment operations:
var = 40
math_operation_result = 40 * 5
3. Do not put a space between operators when transmitting as a parameter:
def count_even(num=27):
pass
4. Put a space after the decimal point:
var1, var2 = get_values(num1, num2)
You can also add blank lines (not too often) to define groups of related functions. Empty lines should not be added between several related programs in a single line (for example, in a formal implementation).
Not so often it is possible to add blank lines in function code to separate logical parts from each other.
Python treats the control+L (or ^L) character as space. Many editors treat it as a page break, so it can be used to highlight logical parts in a file on different pages. Note that not all editors recognize control+L and can display a different character in its place.
PEP8 Documentation
The code is written many times less than it is read. Actually, the recommendations on the python style guide about code writing are aimed at making code as comfortable as possible. Moreover, the recommendations are also needed to make code consistent between many projects. That is why all programmers know python naming conventions. Ideally, all the Python projects should be done in a single style. Thanks to this anyone could easily understand it.
The multi-line documentation should consist of:
- Rows with a brief description.
- A case of use, if any.
- Argumenty.
- Type of return value and semantics if no None is returned.
An example:
class Car:
“””A simple representation of a car.
:param brand: A string, car’s brand.
:param model: A string, car’s model.
“””
def __init__(self, brand, model):
self.brand = brand
self.model = model
Conclusion
Is it worth spending time on “beautiful” code design according to different python style guides? Or is it bad thoughts that come out of idleness, and the main thing is that the code works?
Let’s start with the most important thing: if the code doesn’t work, you don’t have to spend time evaluating its other parameters. If the code does not work, it is the missing code.
The working code will be read by many completely unrelated people, much longer than the author writes it. It will be read by people who are as far away from the ideas embedded into the code as possible. That’s why what is called “beautiful code” is an ordinary tool that is intended to make the main parameter of the code cheaper — its maintainability.
Architecture, style, adherence to standards and documentation, mnemonic naming of entities, and the size of indents — all this should serve one purpose: to facilitate code maintenance. This helps to make changes to the already working code cheaper.
First of all, when writing the code, you should make sure that it is simple and easy to read. Nobody should have problems with understanding the code.