Summary of python programming specifications for coding work - Google version

python code specification (Google)

format specification

  1. do not add semicolons
  2. No more than 80 characters per line
  3. Do not join lines with backslashes
  4. Indent code with 4 spaces
  5. Two blank lines between top-level definitions and one blank line between method definitions.
  6. space
  • No spaces in parentheses
  • Don't put spaces before commas, semicolons, colons, but should put them after (except at the end of the line)
  1. Argument lists, indices or slices should not have a space before the opening parenthesis
  2. Put a space on both sides of the binary operator
  3. When '=' is used to indicate a keyword argument or a default argument value, do not use spaces around it, e.g. def complex(a=1)is right.
  4. Do not use spaces to vertically align markup across multiple lines.
  5. import format

Each import should be on its own line
Imports should be at the top of the file. The import order should be in the order of common to non-common, the standard library is greater than the third-party library than the program library

  1. Each statement should be on its own line.
    If the test result and the test statement are not more than 80 characters in one line, they can also be placed on the same line. If it is an if statement, it can only be done if there is no else; try/except cannot be arranged in this way. For example:
Yes:

  if foo: bar(foo)
No:

  if foo: bar(foo)
  else:   baz(foo)

  try:               bar(foo)
  except ValueError: baz(foo)

  try:
      bar(foo)
  except ValueError: baz(foo)

files and sockets

When files and sockets end, explicitly close them.
In addition to file presses, sockets or other file-like objects that are not necessary to be opened can have many side effects, such as:

  1. May consume limited system resources such as file descriptors. If these resources are not returned to the system immediately after use, the code used to process these objects will consume resources
  2. Holding a file will prevent other operations on the file such as moving, deleting, etc.
  3. Just logically close files and sockets, and they may still be inadvertently read or written by programs they share.
  • It is recommended to use 'with' to manage files:
with open('q.txt') as f:
    for line in f:
        print(line)
f.closed()
  • For file-like objects that do not support the use of "with" statements, use contextlib.closing():
import contextlib

with contextlib.closing(urllib.urlopen("http://www.python.org/")) as front_page:
    for line in front_page:
        print line

Naming conventions

  1. Names that should be avoided.
  • single character name
  • Hyphens cannot appear in module names
  • cannot write names beginning and ending with double underscores
  1. naming convention
  • Start with a single underscore (_) to indicate that the module variable or function is protected
  • Start with a double underscore (_) to indicate that the module variable or function is private
  • Put related classes and top-level functions in the same module
  • Use upper camelCase for class names, and lowercase and underlined naming methods for module names.

Constant declarations use uppercase characters and are separated by underscores, such as NAMES_LIKE_THIS

note

  1. File comments
    The top-level opening comments are used to tell readers who are not familiar with the code what this file contains, and should provide the general content of the file, its author, dependencies and compatibility information. as follows:

/**
* 文件描述,他的使用和必要信息
* 存在的依赖
* 作者
  1. Class annotations
    Class annotations describe the functionality and usage of the class, and also need to explain the constructor parameters.
    If a class does not inherit from other classes, it explicitly inherits from object. The same is true for nested classes. Examples are as follows:
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."""
  1. Comments for methods and functions
    Provide descriptions of parameters, using complete sentences, and writing descriptions in the third person.
def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
    """方法内容

    Retrieves rows pertaining to the given keys from the Table instance
    represented by big_table.  Silly things may happen if
    other_silly_variable is not None.

    参数:
        big_table: An open Bigtable Table instance.
        keys: A sequence of strings representing the key of each table row
            to fetch.
        other_silly_variable: Another optional variable, that has a much
            longer name than the other args, and which does nothing.

    Returns:
        A dict mapping keys to the corresponding table row data
        fetched. Each row is represented as a tuple of strings. For
        example:

        {'Serak': ('Rigel VII', 'Preparer'),
         'Zim': ('Irk', 'Invader'),
         'Lrrr': ('Omicron Persei 8', 'Emperor')}

        If a key from the keys argument is missing from the dictionary,
        then that row was not found in the table.

    Raises:
        IOError: An error occurred accessing the bigtable.Table object.
    """
    pass
  1. Attribute comments
    Provide a description of the parameter, use complete sentences, and write the description in the third person
/**
* 参数描述
* @type {string} 值描述
  1. Type cast annotations
    Add type tag annotations to clarify that parentheses must be wrapped around expressions and type annotations.
/**  */ (x)
  1. Put long URLs on one line
Yes:  # See details at
      # http://www.example.com/us/developer/documentation/api/content/v2.0/csv_file_name_extension_full_specification.html
No:  # See details at
     # http://www.example.com/us/developer/documentation/api/content/\
     # v2.0/csv_file_name_extension_full_specification.html
  1. block and line comments

The most important places to write comments are those tricky parts of the code. If you have to explain it during the next code review, you should write comments for it now. For complex operations, you should write several Line comments. For code that is not self-explanatory, comments should be added at the end of its 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 if i is 0 or a power of 2.
  1. TODO comments
    Use TODO comments for temporary code, it is a short-term solution.
    TODO comments should contain the "TODO" string at the beginning of all comments, then bracket your own email address or name, and describe the character content. Specific examples are as follows:
# TODO([email protected]): Use a "*" here for string repetition.
# TODO(Zeke) Change this to use relations.

Guess you like

Origin blog.csdn.net/weixin_44077556/article/details/128975137