To write perfect code is possible. Moreover, it is advantageous. Adding elegance and clarity to your code, you are laying the strong foundation for improving not only your technical skills but also your relationships with others who read your code. After all, doing so, you get all the chances to make your life easier because you’ll avoid spending extra time on finding answers to questions like — What? Where? For what? :)
I adore the phrase said by Python creator Guido van Rossum:
The code is read much more often than it is written.
You may agree, the most awful mistake is to write code and not think that you will read it later. Such an approach is a total disaster not only for you but also for your employer and colleagues, who may also ask for your code. But the coding style that drives a reader’s nuts is unlikely to be successful.
Writing elegant code is the right thing to make you a good specialist, and there is no room for doubt or arguing. Unless you are a lazy ass to deal with it and break the old habits. But with time, your efforts will bear fruit and pave the way for proficiency, and then maybe you will even regret why you did not try to do it much earlier.
The proper organization brings peace and order. So, how to write perfect code? The answer can be contained in three characters — PEP. It is Python’s style guide that will change your life forever. Today I’ll tell you how to use it in such a way that you will be able to format your code and maximize its readability.
PEP is actually an acronym that stands for Python Enhancement Proposal. Since Python is an open-source programming language, everyone can submit their suggestions through PEP. Over the years, hundreds of PEPs have appeared, but of course, not all of them are useful. The most popular are PEP 8 and 20, which is exactly what I want to talk about today.
And though, logically, things should start with a smaller number, I’ll start with PEP 20 :)
The Zen of Python is a collection of 19 guiding principles penned by Tim Peters in 1999. It was included as entry number 20 in the language’s official Python Enhancement Proposals. Besides, it is included as an Easter egg in the Python interpreter. You can see it when typing
import this
You may ask, why does Zen of Python distill the guiding principles into 20 aphorisms but lists only 19? So, what’s the twentieth? Well, lists are more fun when they’re left to the imagination. I think it is some bizarre Tim Peters in-joke. And yes, it may be an opportunity for people to provide their own addition.
I also found a very fun explanation of it:
Rule number 20: there is no rule #20. This replaced the old rule #20: “you do not talk about fight club”.
Nice suggestion, isn’t it?
One way, or another, PEP 20 should be the main concern while writing code both for programmers and data scientists. PEP 20 is the thing that summarizes the Python philosophy. Keeping these principles in mind, you will always have a base for all kinds of operations and algorithms.
But one PEP 20 isn’t enough…
PEP 8 is a more formal Python document or style guide that contains mostly practical tips: from the formatting and choosing variable names to applying the language itself. It was written in 2001 by Guido van Rossum, Barry Warsaw, and Nick Coghlan. After PEP 20, it is another great stuff that every Python specialist should be acquainted with.
The main idea behind PEP 8 is to improve the readability and consistency of Python code. You can become familiar with the complete list of all the rules from the official document, below I will highlight the most important rules:
##1 Naming Conventions
First and foremost rule of good code sounds as follows: each variable should refer to what it stores. The ideal variable is clear and easy to read:
The working code should be readable and clear without the personal presence of the author. What do newbies do wrong? Often beginners use the usual letters of the alphabet as variables: a, b, c, d. Another mistake may be the letter + number: a1, a2, a3. If there are twenty variables, then there will be a20. Understanding what information that they store is very difficult.
What else is not recommended to use is the string variable l. Developers try to avoid this letter since it is not customary to use it not only in Python but also in other programming languages because when reading code quickly, the lowercase l can be easily confused with one. Similar confusion arises with O and 0.
##2 Blank Lines
Surround top-level functions and classes with two blank lines. Top-level functions and classes should be fairly self-contained and handle separate functionality. It makes sense to put extra vertical space around them so that it’s clear they are separate:
class MyFirstClass:
pass
class MySecondClass:
pass
def top_level_function():
return None
Surround method definitions inside classes with a single blank line. Inside a class, functions are all related to one another. It’s good practice to leave only a single line between them:
class MyClass:
def first_method(self):
return None
def second_method(self):
return None
Use blank lines sparingly inside functions to show clear steps. Sometimes, a complicated function has to complete several steps before the return statement. To help the reader understand the logic inside the function, it can be helpful to leave a blank line between each step.
def calculate_variance(number_list):
sum_list = 0
for number in number_list:
sum_list = sum_list + number
mean = sum_list / len(number_list)
sum_squares = 0
for number in number_list:
sum_squares = sum_squares + number**2
mean_squares = sum_squares / len(number_list)
return mean_squares — mean**2
Use vertical whitespace carefully, it can greatly improve the readability of code. It helps the reader visually understand how your code splits up into sections, and how those sections relate to one another.
#3 Wrap lines so that they don’t exceed 79 characters
The Python standard library is conservative and requires limiting lines to 79 characters. The lines can be wrapped using parenthesis, brackets, and braces. They should be used in preference to backslashes.
Example:
with open(‘/path/from/where/you/want/to/read/file’) as file_one, \
open(‘/path/where/you/want/the/file/to/be/written’, ‘w’) as file_two:
file_two.write(file_one.read())
#4 Use spaces around operators and after commas, but not directly inside bracketing constructs:
a = f(1, 2) + g(3, 4)
#5 Comments
When you or someone else reads a comment, they should be able to easily understand the code the comment applies to and how it fits in with the rest of your code.
Here are some key points to remember when adding comments to your code:
Comments should form complete sentences. If a comment is a full sentence, its first word should be capitalized, unless it is an identifier that begins with a lowercase letter. In short comments, the period, in the end, can be omitted. In block comments, there are more than one paragraph and each sentence must end with a period. Block comments and inline comments can be written followed by a single ‘#’.
Python is sometimes like poetry. The presence of the words on the page holds nearly as much weight as the words themselves. Once you’ve written it, you’re never going to write it again. But you’ll definitely have to read it again. Learning to write your code to PEP 8 standards really helps when working with a team and once you know the rules, it makes it really easy to find syntax mistakes in your own code.
#python #programming