Table of Contents
Coding standards
1. Semicolon
2. Naming
3. Line length
4. Indentation
5, empty line
6. Spaces
7. Class
8. Block comments and line comments
9, string
10, import package
1. Naming
2. Blank
3. Statement
4. Comments
Home Backend Development Python Tutorial What are the coding standards in Python?

What are the coding standards in Python?

May 09, 2023 pm 03:22 PM
python

Coding standards

The reason why Python coding standards are important can be summed up in one sentence: Unified coding standards can improve development efficiency.

ps.python code writing must basically follow the PEP8 style

1. Semicolon

Do not add a semicolon at the end of the line, and do not use A semicolon puts two commands on the same line.

2. Naming

module_name, package_name, ClassName, method_name

Names that should be avoided

  1. Single character names, except counters and iterators.

  2. Hyphens (-) in package/module names

  3. Start and end with double underscore The name (Python reserved, such as __init__)

Naming convention

  1. The so-called "internal" means Only available within the module, or, protected or private within the class.

  2. Starting with a single underscore (_) indicates that the module variable or function is protected (not used when using import * from Will contain)

  3. Instance variables or methods starting with a double underscore (__) indicate private within the class.

  4. Relate the relevant class and top-level Functions are placed in the same module. Unlike Java, there is no need to limit one class to one module.

  5. Use words starting with capital letters (such as CapWords, Pascal style) for class names, But module names should be in lowercase and underlined (such as lower_with_under.py). Although there are many existing modules using names similar to CapWords.py, this is no longer encouraged because if the module name happens to be the same as the class name Consistent, this will cause trouble.

3. Line length

No more than 80 characters per line

Except for the following situations:

  1. URLs in long import module statement comments

  2. Do not use backslashes to connect lines.

Python will implicitly connect the lines enclosed in parentheses, square brackets and curly braces. You can take advantage of this feature. If necessary, you can add a pair around the expression Extra parentheses.

Recommendation:

foo_bar(self, width, height, color='black', design=None, x='foo',
             emphasis=None, highlight=0)
 
     if (width == 0 and height == 0 and
         color == 'red' and emphasis == 'strong'):
Copy after login

If a text string does not fit on one line, you can use parentheses to implement implicit line connection:

x = ('这是一个非常长非常长非常长非常长 '
     '非常长非常长非常长非常长非常长非常长的字符串')
Copy after login

4. Indentation

Use 4 spaces to indent code

Never use tabs, or mix tabs and spaces. In the case of line concatenation, you should either vertically align wrapped elements (see :ref:`line length` part of the example), or use a hanging indent of 4 spaces (in this case there should be no parameters on the first line):

       # 与起始变量对齐
       foo = long_function_name(var_one, var_two,
                                var_three, var_four)
 
       # 字典中与起始值对齐
       foo = {
           long_dictionary_key: value1 +
                                value2,
           ...
       }
Copy after login

5, empty line

Top level Two blank lines between definitions, one blank line between method definitions

Two blank lines between top-level definitions, such as function or class definitions. There should be one blank line between method definitions, class definitions and the first method. . In functions or methods, if you think it is appropriate in some places, leave a blank line.

6. Spaces

Use spaces on both sides of punctuation in accordance with standard formatting specifications

There should be no spaces within the brackets.

Use spaces on both sides of the punctuation according to standard formatting conventions

正确示范: spam(ham[1], {eggs: 2}, [])
Copy after login
错误示范: spam( ham[ 1 ], { eggs: 2 }, [ ] )
Copy after login

7. Class

The class should be in its definition There is a docstring describing the class below. If your class has public attributes (Attributes), then the documentation should have an attributes (Attributes) section. And it should follow the same format as the function parameters.

class SampleClass(object):
    """Summary of class here.
    Longer class information....
    Longer class information....
    Attributes:
        likes_spam: A boolean indicating if we like SPAM or not.
        eggs: An integer count of the eggs we have laid.
    """
 
    def __init__(self, likes_spam=False):
        """Inits SampleClass with blah."""
        self.likes_spam = likes_spam
        self.eggs = 0
 
    def public_method(self):
        """Performs operation blah."""
Copy after login

8. Block comments and line comments

The most important parts of the code to write comments are those technical parts. If you must explain it during the next code review, then you You should write comments for it now. For complex operations, you should write several lines of comments before the operation starts. For code that is not self-explanatory, comments should be added at the end of the lines.

# We use a weighted dictionary search to find out where i is in
# the array.  We extrapolate position based on the largest num
# in the array and the array size and then do binary search to
# get the exact number.
 
if i & (i-1) == 0:        # true iff i is a power of 2
Copy after login

In order to improve readability , comments should leave at least 2 spaces away from the code.

On the other hand, never describe the code. Assume that the person reading the code knows Python better than you do, he just doesn’t know what your code is doing.

# BAD COMMENT: Now go through the b array and make sure whenever i occurs
# the next element is i+1
Copy after login

9, string

正确示范: 
     x = a + b
     x = '%s, %s!' % (imperative, expletive)
     x = '{}, {}!'.format(imperative, expletive)
     x = 'name: %s; score: %d' % (name, n)
     x = 'name: {}; score: {}'.format(name, n)
Copy after login
错误示范: 
    x = '%s%s' % (a, b)  # use + in this case
    x = '{}{}'.format(a, b)  # use + in this case
    x = imperative + ', ' + expletive + '!'
    x = 'name: ' + name + '; score: ' + str(n)
Copy after login

10, import package

Each import should be on its own line

正确示范: 
import os 
import sys
Copy after login
错误示范:   import os, sys
Copy after login

The import should always be placed at the top of the file, located in the module comment and docstrings, before module global variables and constants. Imports should be grouped in order from most common to least common:

Standard library imports Third-party library imports Application-specific imports

【Summary】

1. Naming

  1. Functions, variables and properties should be spelled in lowercase words. Use _ to connect, do not follow camel case naming convention

  2. Classes and exceptions should be capitalized, do not use _ to connect

  3. Protected instance attributes , should start with a single underscore

  4. The private properties of the instance should start with a double underscore

  5. Module-level variable words must be capitalized, with the middle Separate with single underscores

  6. Variables should be as meaningful as possible

2. Blank

  1. Each level of indentation related to syntax is represented by 4 spaces

  2. When assigning, there must be a space on both sides of the equal sign

  3. Each The number of characters occupied by one line should not exceed 79. In actual operation, you should try not to let the line scroll bar of the code editor be displayed

  4. When using functions for functional programming, there should be two blank lines between functions

  5. For functions in a class, there should be one blank line between functions

  6. If functions and classes are at the same level, there should be two empty lines between them

  7. For long expressions that exceed the specified number of characters per line formula, you should hit Enter to indent, usually all lines except the first line should be indented by 4 spaces again based on the original

3. Statement

  1. Do not use == when judging whether a variable is None, False or True. Use is. For example, if a is None

  2. The import statement should be placed at the beginning of the sentence. When importing, try to use absolute import instead of relative import, and it is best to specify a specific function of the corresponding module when importing. For example, from datetime import datetime

  3. The module should be imported according to Classification of standard library modules, third-party modules and self-used modules

  4. When detecting that the container is not empty, the if container name should be used, for example, lists = [] if lists

  5. Use inline form of negative words, do not put the negative word in front of the entire expression, for example, it should be if a is not None instead of if not a is None

4. Comments

  1. For functional descriptions of some important code blocks, single-line comments

  2. should be used for the entire module function. The description should use multi-line comments

  3. The detailed description of the function and usage of the class or function should use the documentation string

  4. python Please use English as much as possible

The above is the detailed content of What are the coding standards in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Google AI announces Gemini 1.5 Pro and Gemma 2 for developers Google AI announces Gemini 1.5 Pro and Gemma 2 for developers Jul 01, 2024 am 07:22 AM

Google AI has started to provide developers with access to extended context windows and cost-saving features, starting with the Gemini 1.5 Pro large language model (LLM). Previously available through a waitlist, the full 2 million token context windo

How to download deepseek Xiaomi How to download deepseek Xiaomi Feb 19, 2025 pm 05:27 PM

How to download DeepSeek Xiaomi? Search for "DeepSeek" in the Xiaomi App Store. If it is not found, continue to step 2. Identify your needs (search files, data analysis), and find the corresponding tools (such as file managers, data analysis software) that include DeepSeek functions.

How do you ask him deepseek How do you ask him deepseek Feb 19, 2025 pm 04:42 PM

The key to using DeepSeek effectively is to ask questions clearly: express the questions directly and specifically. Provide specific details and background information. For complex inquiries, multiple angles and refute opinions are included. Focus on specific aspects, such as performance bottlenecks in code. Keep a critical thinking about the answers you get and make judgments based on your expertise.

How to search deepseek How to search deepseek Feb 19, 2025 pm 05:18 PM

Just use the search function that comes with DeepSeek. Its powerful semantic analysis algorithm can accurately understand the search intention and provide relevant information. However, for searches that are unpopular, latest information or problems that need to be considered, it is necessary to adjust keywords or use more specific descriptions, combine them with other real-time information sources, and understand that DeepSeek is just a tool that requires active, clear and refined search strategies.

How to program deepseek How to program deepseek Feb 19, 2025 pm 05:36 PM

DeepSeek is not a programming language, but a deep search concept. Implementing DeepSeek requires selection based on existing languages. For different application scenarios, it is necessary to choose the appropriate language and algorithms, and combine machine learning technology. Code quality, maintainability, and testing are crucial. Only by choosing the right programming language, algorithms and tools according to your needs and writing high-quality code can DeepSeek be successfully implemented.

How to use deepseek to settle accounts How to use deepseek to settle accounts Feb 19, 2025 pm 04:36 PM

Question: Is DeepSeek available for accounting? Answer: No, it is a data mining and analysis tool that can be used to analyze financial data, but it does not have the accounting record and report generation functions of accounting software. Using DeepSeek to analyze financial data requires writing code to process data with knowledge of data structures, algorithms, and DeepSeek APIs to consider potential problems (e.g. programming knowledge, learning curves, data quality)

The Key to Coding: Unlocking the Power of Python for Beginners The Key to Coding: Unlocking the Power of Python for Beginners Oct 11, 2024 pm 12:17 PM

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Oct 11, 2024 pm 08:58 PM

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

See all articles