Python — Code style
vvrubelPEP 8
How to write code that is clean and easy to read? That is the question that you bump into when moving from simple single-line programs to more complicated ones. In the beginning, it may seem unimportant, but in real life, programming is a process that involves a lot of people that work together, so you spend more time reading code than writing it.
Although Python is often more readable than other programming languages because of its minimalistic syntax, just syntax itself is not enough. It is the way you write code that affects general readability. That is why you need to follow common conventions about programming style, so other programmers could read your code easily.
You may ask, where do these conventions come from? There is a document that is called PEP 8. The key idea of it is to use the same code style for all python projects as if they were written by the same programmer. This document guarantees that even a beginner will easily understand the code, written by any other developer.
§1. PEPs
Before going further, let’s talk about PEP for a moment. PEP stands for Python Enhancement Proposal. There are different types of PEP and the most useful one for beginners is the informational PEP. PEPs of this kind typically describe commonly accepted guidelines or conventions about the language, so they can be very helpful. Besides PEP 8, which is an official style guide, another great PEP to look at is the Zen of Python.
Since we know what PEP 8 is, let’s read a bit from it.
§2. The length of a line
Do not use more than 79 characters in a line of code. Shorter lines look better in code editors. During this course, we will learn several ways to achieve it.
§3. Avoid extra spaces
Sometimes you may add some spaces even if you don't really need it. This will reduce the readability of your code.
- Avoid extra spaces within parentheses.
Good:
print('Hello!')
Bad:
print( 'Hello!' )
- Avoid an extra space before an open parenthesis.
Good:
print('some text')
Bad:
print ('some text')
§4. Quotes
As it was already mentioned, you can use either single or double quotes to define strings. Please, choose one that you like the most and consistently use it in your code. The only recommendation in PEP 8 is that if a string contains single or double quotes, you should use the other one to avoid backslashes.
Good:
print("It's a good string!")
Bad and harder to read:
print('It\'s a bad string!')
As you can see, the first example is easier to read.
§5. What’s next?
Later on, you will learn a lot of things about Python and become a more skillful programmer, but following the code style will always remain important. Do not worry, though: you do not need to learn all the conventions at once; just open them from time to time after learning something new. We will also give parts of these conventions in this course.
Comments
Sometimes you need to explain what some particular parts of your code are for. Lucky you, since Python gives you an opportunity to fulfill your needs. You can leave special notes called comments. They are especially useful for beginners. Throughout this course, we will often use comments to explain our examples.
§1. What is a comment?
Python comments start with a hash #. Everything after the hash mark and up to the end of the line is regarded as a comment and will be ignored when running the code.
print("This will run.") # This won't run
In the example above, you can see what PEP 8 calls an inline comment because it's written on the same line as the code.
A comment can also refer to the block of code that follows it:
# Outputs three numbers
print("1")
print("2")
print("3")
We intend to use such comments primarily for learning purposes. Now, it's time to find out how to comment code properly.
§2. Formatting comments
Although it is pretty easy to write a comment, let's discuss how to do this in accordance with best practices.
To begin with, after a hash mark there should be one space and, in inline comments, there should be two spaces between the end of the code and the hash mark. Putting more than two spaces between the end of the code and the hash mark is also acceptable but most commonly there are exactly two spaces.
print("Learning Python is fun!") # This is a proper comment formatting
print("PEP-8 is important!")#This is a very bad example
Indent your comment to the same level as the statement it explains. E.g. the following example is wrong:
# this comment is at the wrong place
print("This is a statement to print.")
A comment is not a python: it should not be too long. Following PEP-8, the comment length should be limited to 72 characters. It's better to split a long comment into several lines: you can do it by adding a hash mark at the beginning of each new line:
# Imagine that this is an example of a really long comment
# that we need to spread over three lines, so we continue
# to write it even here.
print("The long comment above explains this line of code.")
Comments that span multiple lines are called multi-line or block comments. In Python, there is no special way to indicate them.
You may come across multi-line comments enclosed in triple quotes """...""", still, we recommend that you use several hash marks for this purpose. Thus, your code will comply with the official style guide. Triple quotes are reserved for documentation strings, or docstrings for short. They are also informative, but their use is limited to functions, methods and several other cases.We hope our comments will help you understand our code examples better!
Avoiding bad comments
As you already know, a Python feature (beloved by all Python programmers) is its well-readable syntax. However, apart from the syntax itself, there are other important things that contribute to the readability of your program. We assume that you are already familiar with comments and how they help in learning a new language.
In real programs, comments become especially important as the program gets bigger and more complicated. Without them, things may get confusing even for you within a few months after writing the program, not to mention other developers who see your code for the first time. However, there is also a downside of making comments, meaning that more is not necessarily better, and we will discuss it below as well.
§1. When not to write comments?
This may sound strange but sometimes it's better not to write comments at all. Carefully written, they can indeed contribute to the readability of your program, but it doesn't mean you should include them wherever you can. On the contrary, many programmers are convinced that a good piece of code doesn't require any comments in the first place, for it is so transparent and accurate. That is what we all should aim at. So, if code can be made self-explanatory, comments are unnecessary, and it's better to change the code. Let's highlight cases when developers need to comment less.
- If a comment explains a variable/function, you can usually delete the comment and explicitly name the variable/method itself. Compare the following lines of code:
n = 0 # number of participants participants_num = 0
- Avoid writing obvious comments, like the one below. They make your code redundant and even harder to read. You should always seek following the D.R.Y. (don't repeat yourself) principle, not W.E.T. ("wrote everything twice" or "wasted everyone's time" for more cynical ones).
age = 20 # age is 20 greeting = 'hello' # assign 'hello' to greeting
- If you see a way to alter your code so that comments would become unnecessary - you should do that.
That is, if you can avoid commenting — you'd better do. Then your code would be clean, wouldn't be overloaded with unnecessary details and wouldn't become more complicated rather than clearer for readers to understand.
§2. How to write good comments?
Now, let's turn to cases when you decide to write a comment. The main thing to remember then is that comments should be easily understandable by anyone, be that Future You or some other programmer. Here are some tips on how to achieve it:
- Generally, comments should answer the question "why" as opposed to "what". However, it may be useful for beginners to write comments for themselves explaining what the code does, especially when using a newly learned syntax expression, e.g.:
result = 15 % 4 # % is used for division with remainder
- Make sure that your comments do not contradict the code (that happens more often than you can imagine!). Wrong comments are worse than no comments at all.
# decrease the counter counter += 1
- Do not forget to update the comments if you modify the code. It will only confuse the reader instead of helping them. In the example below the variable "counter" used to be designated as "i"; the programmer changed its name in the code but not in the comment.
# i is incremented in case of errors counter += 1
Following these pieces of advice, you can write code that is clean, organized, easy to understand, and pleasant to read.
§3. Conclusion
When annotating the code, it's important to know where to draw the line. Both over- and undercommented programs can be difficult to understand, resulting in wasted and unpleasant time spent working with such pieces of code. So, you should always try to write comments carefully and only when necessary.
The simplest way to learn to do so is just by doing it. It's a good idea to start practicing when you only start coding because you will get used to it, and by the time some more complex problems should be solved, you will know how to write comments properly. From now on, try to include simple comments in your code to explain difficult moments that took you a while to understand. It is also useful to get back to review your older programs and see how they (including comments) could be enhanced.
Naming variables
As you know, every variable has a name that uniquely identifies it among other variables. Giving a good name to a variable may not be as simple as it seems. Experienced programmers are careful when naming their variables to ensure that their programs are easy to understand. It is important because programmers spend a lot of time reading and understanding code written by other programmers. If variables have bad names, even your own code will seem unclear to you in a few months. In this topic, we will consider how to choose good names for your variables in accordance with conventions and best practices established in the Python community.
§1. Code style convention
PEP 8 provides some rules for variable names to increase code readability.
- Use lowercase and underscores to split words. Even if it's an abbreviation.
http_response # yes! httpresponse # no myVariable # no, that's from Java
However, if you want to define a constant, it's common to write its name in all capital letters and, again, separate words with underscores. Normally, constants are stored in special files called modules. Although we'll cover this later, here is a small example:
SPEED_OF_LIGHT = 299792458
- Avoid names of one letter that could be easily mixed up with numbers like 'l' (lowercase letter el), 'O' (uppercase letter oh), or 'I' (uppercase letter eye).
l = 1 # no O = 100 # no, if you use this variable name further in your code it would look like zero
- Although you can use any Unicode symbols, the code style convention recommends limiting variable names with ASCII characters.
# Using Cyrillic instead of Latin can cause an evening of useless headache # These are different variables! copy = "I'm written in Latin alphabet" # yes! сору = "And I'm written in Cyrillic!" # no
- If the most suitable variable name is some Python keyword, add an underscore to the end of it.
class_ = type(var) # yes! klass = type(var) # no
All the code style rules regarding names are described in PEP 8.
§2. Other variable names best practices
There are also some best practices that are common for many programming languages.
- Choose a name that makes sense. The variable name must be readable and descriptive and should explain to the reader what sort of values will be stored in it.
score # yes! s # no count # yes! n # no
- Don't use too generic names. Try to choose a name that will explain the meaning of the variable. But don't make it too wordy. 1-3 words are usually enough.
http_response # yes! var1 # no http_response_from_the_server # no, some words can be dropped
- If a word is long, try to find the most common and expected short form to make it easier to guess later.
output_file_path # yes! fpath # no output_flpth # no
- Avoid names from the built-in types list.
str = 'Hello!' # no, because in the further code you can't use str type as it's overridden
Note, the last best practice is pretty Python-specific.
§3. Conclusion
All the naming conventions and best practices are optional, but it is strongly recommended to follow them. As we mentioned at the beginning of this lesson, they make your code more readable and self-descriptive for you and other programmers.