Python code style and python code style

Source: Internet
Author: User

Python code style and python code style

1 Principle

It is important to consider some general principles before you begin to discuss specific standards adopted by the Python community or suggestions recommended by others.

Remember that the goal of readability standards is to improve readability. These rules exist to help users read and write code, rather than the opposite.

This section describes the principles you need to remember.

1.1 assume that your code needs to be maintained

It is easy to believe that you do not need to add or maintain a part of the work completed at a certain time in the future. This is because it is difficult to predict future needs and underestimate the tendency to cause bugs. However, few written code remains unchanged.

If you assume that the code you write will be read, debugged, or repaired once and for all without having to do so, you will easily fall into a situation where you ignore other readability principles, this is only because you believe that "this time is not important ".

Therefore, it is best to maintain an intuitive distrust of the code you feel you do not need to maintain. You can bet that you will see your code again. Even if you do not maintain it, you need maintenance by others.

1.2 maintain consistency

The two aspects of consistency are internal consistency and external consistency.

In terms of code style and code structure, the Code should satisfy internal consistency as much as possible. Regardless of the formatting rules, the Code style must be consistent throughout the project. Code structure consistency means that the same type of code is put together. This makes it easy to control projects.

The code generation should also maintain external consistency. The structure of the project and code is consistent with that of others. If a new developer opens your project, you should not let it respond as follows: "I have never seen anything like this ". The Community guiding principles are important because they are what developers expect to see when they join your project. Similarly, for the same reason, consider the standards used to complete tasks and organize code when using a specific framework.

1.3 consider the way things exist, especially with data

The main meaning of Ontology is "Research on existence ". In philosophy (the term is often used in this field), ontology is a study of the nature of reality and existence, and a subset of metaphysics.

For writing a software program, the ontology refers to how different "things" exist in the program. How do you convert concepts into representation in a database? Or is it represented by a class structure?

Such problems ultimately affect the way you write or organize code. Do you want to use inheritance or combination to organize the relationship between two classes? Which table is used in the database to complete this function or who belongs to this column?

These suggestions ultimately come down to "thinking before writing code ". Especially when thinking about what programs want to achieve and how they interact. A program is a world in which objects interact with data. So what are the rules to be followed for collaboration between them?

1.4 do not repeat work

When writing code, consider changing the value that will be reused over time. Is this value used in multiple modules or functions? If necessary, how much does it cost to modify it?

The same principle applies to functions. Do you have a lot of repeated code in the program? If there are many lines of repeated code, you can consider abstracting it into a function. If you need to modify the code, it is easier to manage it.

On the other hand, the principle should not be too late. Not all values need to be defined as constants in the module (this will damage readability and maintainability ). Please make a wise decision and constantly ask the following question: "If you need to change the code, what is the cost of changing all the locations of the code "?

1.5 let comments tell stories

Code is a story. It is a description of the story, from the beginning to the end of the interaction between the user and the program. The program starts from a certain point (may contain some input), follows a series of "select your own adventure story" steps to reach the end, and ends (probably with some output results ).

The annotation style can be used to add a comment before each line of code to explain the code function. If the code is a story, comments are the explanation and narration of the story.

If the narrative annotation works well, the reader can read the annotation to understand the story and parse the Code (for example, when trying to solve the problem or maintain the Code ), then you can quickly understand the code to be maintained from scratch, so that you can focus on the meaning of the Code itself.

Narrative annotations can also help explain the code intent. It can answer the following question: "What is the goal of the person who writes this code ?" Occasionally, you can also help answer the question: "Why do you complete the work in this way "? These questions are naturally asked when you read the code. Providing answers to these questions will help you understand the content.

Therefore, annotations are used to explain how the code is not obvious or complex. If you use a complex algorithm, consider adding comments to the link to the article pointing to the interpretation mode and other examples.

1.6 Occam Razor principles

The most important principle for coding and maintenance is the Occam Razor principle: the simplest solution is usually the best. In his "Python Zen" blog (https://www.python.org/dev/peps/pep-0020/), this page is a collection of programming sayings (for example, you can see this article by entering "import this" on the Python console ), tim Peters also includes the following sentence: "If you cannot describe your solution to people, it is definitely not a good solution ".

The above principles take effect in terms of code running and code appearance. When it comes to code running, a simple system is easier to maintain. Implementation simplification means less complex bugs are introduced, and those who maintain your code (including yourself) are more likely to intuitively understand what the code represents, and add code for the program without being pitted.

In terms of the Code appearance, remember to try to make reading the code as much as possible as a story about the code's work, rather than parsing words. Words are the means, and stories are the ultimate goal. It is easy to write a line such as "do not use a ternary operator. However, simply following these rules (although valuable) is not a sufficient condition for clear code. Focus on writing and organizing code in the simplest way possible

2 Standard

Most of the Python community follows the so-called PEP 8 (https://www.python.org/
Dev/peps/pep-0008/) guidelines, written by Guido van rosum (father of Python) and used by most mainstream Python projects including the Python standard library.

The universality of PEP 8 is one of the reasons for its strength. This standard is adopted by most community projects, so you can expect most of the Python code you encounter to follow this standard. When you write code in this way, the code is easier to read and write.

2.1 Concise Rules

The guiding principles in most PEP 8 are simple and clear. Some important points are as follows:

L use four spaces for indentation. Do not use tabs (\ t ).

L The variables should be connected using underscores (_ var rather than myVar) instead of the camel naming style ). The class name starts with a letter and is a camel-style naming style (for example, MyClass ).

L if a variable is used only internally, add an underscore before the variable name.

L add a single space (for example, x + y, not x + y) before and after the operator, and also include the value assignment operator (z = 3 instead of z = 3 ), it is not applicable only when the keyword parameter is used. In this case, spaces can be omitted.

L unnecessary parentheses are omitted in the list and Dictionary (for example, [1, 1, 2, 3, 5], instead of [1, 1, 2, 3, 5]).
Read the Python code style guide for more examples and more discussions about these rules.

2.2 document string

Remember, in Python, if the first statement in a function or class is a string, the string will be automatically assigned to a special "_ doc _" variable, this variable is used when you call Help (and some other classes.

PEP 8 specifies that the document string (the name can be described as intended) is required.

"Do X, Y, andZ, then return the result ."""

Comparison between the sentence and the document string used as the description:

"Does X, Y, andZ, then returns the result ."""

If the document string is a line, you need to add a blank line before the class or function body. If the document string contains multiple lines, separate the ending double quotation marks with one line.

2.3 blank lines

Empty rows are used for logical chunks.

PEP8 specifies that there are two blank rows between the class and Function Definition of the "highest level.

class A(object):passclass B(object):pass

Code List 1.

PEP 8 also specifies that apart from the highest level, classes and functions are defined as a blank line.

class C(object):def foo(self):passdef bar(self):pass 

Code List 2.

It is reasonable to separate logical segments using a single blank line in a function or other code segment. Consider using annotations to explain the role of a code segment before a logical segment.

2.4 Import

Python allows absolute and relative paths. In Python2, the interpreter tries relative import. If the path cannot be found, try absolute import again.

In Python 3, when a special syntax mark is used, such as ---- starting with (.) ---- "normal", the import method will only try the relative path. The syntax of Python 3 can be used in Versions later than Python 2.6. In addition, you can use-"_ future _" to disable implicit relative path import.

If possible, try to use absolute path for import. If you have to use a relative path, use the explicit import style. If you write code for Python 2.6 or 2.7, consider choosing an explicit style in Python 3.

When importing a module, each module occupies a single line.

import osimport sys

Code List 3

However, if you import multiple names from the same module, You can group these names into one row.

from datetime import date, datetime, timedelta

 

Code list 4

In addition, although PEP 8 does not have a mandatory requirement, we consider importing data to the group as a package source. Each group is sorted alphabetically.

In addition, do not forget to use the as keyword to alias the imported content during import.

from foo.bar import really_long_name as name

Code List 5

This allows you to simplify frequently used long names or nonstandard names.

When the import is frequently used and the original name is invalid for any reason, the alias is very valuable.

On the other hand, remember that when you do this, you will mask the original name in your module. If you do not need to use aliases, this will make the code unclear. No matter what tool you use, you need to analyze the specific situation.

2.5 Variables

As mentioned earlier, variable names are connected using underscores instead of the camel code style (for example, my_val rather than myVal ). In addition, a descriptive name is equally important.

Generally, it is not appropriate to use a very short variable name, although it is acceptable in some cases, such as a variable in a loop (for example, for k in mydict_item ()).

Avoid duplicate names of the named function and common names in the Python language, even if the interpreter permits it. In any case, do not name an object as sum or print. Similarly, avoid names such as list or dict.

If you have to name a variable with the same name as the Python type and keyword, the Convention is to underline the variable name. This is more desirable than modifying the name spelling. For example, if you pass a class as a parameter to a function, the parameter name should be class _ rather than klass (an exception is a static method, cls is used as the first parameter ).

2.6 annotations

Comments should be written into complete sentences in English (Note: of course, this is worth mentioning in China), before the relevant code. Use uppercase letters and syntaxes correctly, and ensure correct spelling.

At the same time, ensure that the comment is up-to-date. If the code changes, the comments may need to be changed accordingly. You should not want the comments to be the opposite of the code representation, which can easily lead to confusion.

A module may contain a comment header, which is usually generated by the version control system and contains the file version information. This makes it easy to find files modified, especially when distributing modules to others.

2.7 rows in length

The most controversial (and often denied) aspect of the Python code style is the limit on the line length. PEP 8 requires a line length of no more than 79 characters and a document string of no more than 72 characters.

This rule has frustrated many developers who think we live in a 27-inch wide screen display era. GitHub is a very popular website that shares code. The window width used is 120 characters.

Supporters of the Rule pointed out that many people still use terminals with narrow screens or 80 characters, and even set the width of the code window to smaller than the screen width.

It is difficult to argue that there is a result. In short, whether it is based on a 79-character width standard or a wider standard, you should follow the Project Standard standard code. When the president is too long, you should know how to handle the code.

Using parentheses is the best way to encapsulate the code of a single President, as shown below:

if (really_long_identifier_that_maybe_should_be_shorter andother_really_long_identifier_that_maybe_should_be_shorter):do_something()

 

Code List 6

If possible, use this method instead of using the \ character before the line break. Note that when using operators such as and, place them before line breaks as much as possible.

It is also possible to encapsulate function calls. PEP 8 lists many acceptable approaches to complete encapsulation. The general rule is to make the indentation of rows of the same level consistent.

really_long_function_name(categories=[x.y.COMMON_PHRASES,x.y.FONT_PREVIEW_PHRASES,],phrase='The quick brown fox jumped over the lazy dogs.',)

 

Code List 7

When dividing a function call, list, or dictionary, add a comma at the end of the row.

3 Summary

Most of the time, people who read your code a year later are yourself. Memory is not as easy as it was at the beginning. When writing code, the readability and maintainability of the Code will naturally make it difficult to read and maintain the code.

Throughout this book, you have learned how to use multiple modules, classes, and structures in Python. When you need to decide how to solve the problem, remember that debugging code is more technical than writing code.

Therefore, we aim to make the code as concise and readable as possible. One year later, you will be grateful to yourself. Of course, your colleagues and subordinates will also thank you.

------ This article is based on my translated book "Python advanced programming", published by Tsinghua University Press -------------------------------------------------------------------------------------------------

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.