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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

See all articles