What are the coding standards in Python?

WBOY
Release: 2023-05-09 15:22:07
forward
1556 people have browsed it

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!

Related labels:
source:yisu.com
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!