Python Style Guide (Google)

This project is not an official Google project, but was created and maintained by domestic programmers out of passion.

If you are looking for the official English version from Google, please visitGoogle Style Guide

In the following code,Yesindicates recommended,Noindicates not recommended.


Semicolons

Do not add semicolons at the end of lines, and do not use semicolons to put two commands on the same line.


Line Length

Each line should not exceed 80 characters.

Except in the following cases:

  1. Long import module statements
  2. URLs in comments

Do not use backslashes to join lines.

Python willimplicitly join lines within parentheses, brackets, and bracesYou can take advantage of this feature. If necessary, you can add an extra pair of parentheses around the expression.

推荐: 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'):

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

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

In comments, if necessary, 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

Note the element indentation in the example above; you can find an explanation in the :ref:`indentation <indentation>` section of this document.


Parentheses

Use parentheses sparingly.

Do not use parentheses in return statements or conditional statements unless they are used for line joining. However, using parentheses around tuples is acceptable.

Yes: if foo:
         bar()
     while x:
         x = bar()
     if x and y:
         bar()
     if not x:
         bar()
     return foo
     for (x, y) in dict.items(): ...
No:  if (x):
         bar()
     if not(x):
         bar()
     return (foo)

Indentation

Use 4 spaces to indent code.

Never use tabs, and do not mix tabs and spaces. For line joining, you should either vertically align the wrapped elements (see the example in the :ref:`line length <line_length>` section), or use a 4-space hanging indent (in which case the first line should not have arguments):

Yes:   # 与起始变量对齐
       foo = long_function_name(var_one, var_two,
                                var_three, var_four)

       # 字典中与起始值对齐
       foo = {
           long_dictionary_key: value1 +
                                value2,
           ...
       }

       # 4 个空格缩进,第一行不需要
       foo = long_function_name(
           var_one, var_two, var_three,
           var_four)

       # 字典中 4 个空格缩进
       foo = {
           long_dictionary_key:
               long_dictionary_value,
           ...
       }
No:    # 第一行有空格是禁止的
      foo = long_function_name(var_one, var_two,
          var_three, var_four)

      # 2 个空格是禁止的
      foo = long_function_name(
        var_one, var_two, var_three,
        var_four)

      # 字典中没有处理缩进
      foo = {
          long_dictionary_key:
              long_dictionary_value,
              ...
      }

Blank Lines

Two blank lines between top-level definitions, one blank line between method definitions.

Two blank lines between top-level definitions, such as function or class definitions. Method definitions, and between a class definition and its first method, should have one blank line. Within a function or method, add a blank line where you think it is appropriate.


Whitespace

Follow standard typographic conventions for spaces around punctuation.

No spaces inside parentheses.

Follow standard typographic conventions for spaces around punctuation.

Yes: spam(ham[1], {eggs: 2}, [])
No:  spam( ham[ 1 ], { eggs: 2 }, [ ] )

Do not put a space before commas, semicolons, or colons, but do put a space after them (except at the end of a line).

Yes: if x == 4:
         print x, y
     x, y = y, x
No:  if x == 4 :
         print x , y
     x , y = y , x

Do not put a space before the opening parenthesis of a parameter list, index, or slice.

Yes: spam(1)
no: spam (1)
Yes: dict['key'] = list[index]
No:  dict ['key'] = list [index]

Add a space on both sides of binary operators, such as assignment (=), comparison (==, <, >, !=, <>, <=, >=, in, not in, is, is not), and Boolean (and, or, not). As for how to use spaces around arithmetic operators, you need to make your own judgment. However, you must be consistent on both sides.

Yes: x == 1
No:  x<1

When '=' is used to indicate a keyword argument or a default parameter value, do not use spaces on either side of it.

Yes: def complex(real, imag=0.0): return magic(r=real, i=imag)
No:  def complex(real, imag = 0.0): return magic(r = real, i = imag)

Do not use spaces to vertically align tokens across multiple lines, because this becomes a maintenance burden (applies to :, #, =, etc.):

Yes:
     foo = 1000  # 注释
     long_name = 2  # 注释不需要对齐

     dictionary = {
         "foo": 1,
         "long_name": 2,
         }
No:
     foo       = 1000  # 注释
     long_name = 2     # 注释不需要对齐

     dictionary = {
         "foo"      : 1,
         "long_name": 2,
         }

Shebang

Most .py files do not need to start with #! as the beginning of the file. According toPEP-394, the program's main file should start with #!/usr/bin/python2 or #!/usr/bin/python3.

(Translator's note: In computer science,Shebang(also known as Hashbang) is a string line consisting of a hash sign and an exclamation mark (#!), which appears as the first two characters of the first line of a text file. When a Shebang exists in a file, the program loader of Unix-like operating systems analyzes the content after the Shebang, treats this content as an interpreter directive, invokes the directive, and uses the path of the file containing the Shebang as an argument to the interpreter. For example, a file starting with the directive #!/bin/sh will actually invoke the /bin/sh program when executed.)

#! is first used to help the kernel find the Python interpreter, but it will be ignored when importing modules. Therefore, only files that are directly executed need to include #!.


Comments

Ensure that the correct style is used for modules, functions, methods, and inline comments.

Docstrings

Python has a unique way of commenting: using docstrings. A docstring is the first statement in a package, module, class, or function. These strings can be automatically extracted through the object's __doc__ member and are used by pydoc. (You can run pydoc on your module to try it out and see what it looks like). Our convention for docstrings is to use triple double quotes """ (PEP-257). A docstring should be organized as follows: first, a summary line ending with a period, question mark, or exclamation mark (or the docstring simply has only one line). Then a blank line. Then the rest of the docstring, which should be aligned with the first quote of the first line of the docstring. There are more formatting specifications for docstrings below.

Modules

Each file should contain a license boilerplate. Choose the appropriate boilerplate according to the license used by the project (e.g., Apache 2.0, BSD, LGPL, GPL).

Functions and Methods

The functions referred to below include functions, methods, and generators.

A function must have a docstring unless it meets the following conditions:

  1. Not externally visible
  2. Very short
  3. Simple and clear

The docstring should contain what the function does, as well as a detailed description of the inputs and outputs. Usually, it should not describe "how to do it," unless it involves some complex algorithms. The docstring should provide enough information so that when someone else writes code to call the function, they do not need to look at a single line of code — just the docstring. For complex code, adding comments next to the code is more meaningful than using a docstring.

Several aspects of a function should be documented in specific sections, as described below. Each section should begin with a header line. The header line ends with a colon. Except for the header line, the rest of the section should be indented 2 spaces.

Args:
List the name of each parameter, and after the name use a colon and a space to separate the description of the parameter. If the description is too long and exceeds 80 characters on a single line, use a hanging indent of 2 or 4 spaces (consistent with the rest of the file). The description should include the required type and meaning. If a function accepts *foo (variable-length argument list) or **bar (arbitrary keyword arguments), *foo and **bar should be listed in detail.
Returns: (or Yields: for generators)
Describe the type and semantics of the return value. If the function returns None, this section may be omitted.
Raises:
List all exceptions related to the interface.
def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
    """Fetches rows from a Bigtable.

    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.

    Args:
        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

Class

A class should have a docstring below its definition that describes the class. If your class has public attributes, the documentation should have an Attributes section. It should follow the same format as 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."""

Block Comments and Inline Comments

The code that most needs comments is the tricky parts. If youcode reviewhave to explain it, then you should write a comment for it now. For complex operations, write several lines of comments before the operation begins. For code that is not obvious at a glance, add a comment at the end of the line.

# 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

To improve readability, comments should be 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; they just do not know what your code is supposed to do.

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

Class

If a class does not inherit from other classes, explicitly inherit from object. The same applies to nested classes.

Yes: class SampleClass(object):
         pass


     class OuterClass(object):

         class InnerClass(object):
             pass


     class ChildClass(ParentClass):
         """Explicitly inherits from another class already."""
No: class SampleClass:
        pass


    class OuterClass:

        class InnerClass:
            pass

Inheriting fromobjectis to make properties work correctly, and this protects your code from a special potential incompatibility in Python 3000. This also defines some special methods that implement the default semantics of objects, including__new__, __init__, __delattr__, __getattribute__, __setattr__, __hash__, __repr__, and __str__ .


Strings

Yes: 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)
No: 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)

Avoid using the + and += operators to accumulate strings in a loop. Since strings are immutable, this creates unnecessary temporary objects and results in quadratic rather than linear runtime. As an alternative, you can add each substring to a list, and then after the loop ends, use.jointo join the list. (You can also write each substring to acStringIO.StringIObuffer.)

Yes: items = ['<table>']
     for last_name, first_name in employee_list:
         items.append('<tr><td>%s, %s</td></tr>' % (last_name, first_name))
     items.append('</table>')
     employee_table = ''.join(items)
No: employee_table = '<table>'
    for last_name, first_name in employee_list:
        employee_table += '<tr><td>%s, %s</td></tr>' % (last_name, first_name)
    employee_table += '</table>'

In the same file, keep consistency in the use of string quotes. Use either single quotes ' or double quotes " for strings, and stick to it in the same file. You may use the other kind of quote inside a string to avoid needing to escape it. PyLint has already added this check.

Yes:
     Python('Why are you hiding your eyes?')
     Gollum("I'm scared of lint errors.")
     Narrator('"Good!" thought a happy Python reviewer.')
No:
     Python("Why are you hiding your eyes?")
     Gollum('The lint. It burns. It burns us.')
     Gollum("Always the great lint. Watching. Watching.")

Use triple double quotes """ for multi-line strings instead of triple single quotes '''. Only if the project uses single quotes ' to quote strings may triple ''' be used for multi-line strings that are not docstrings. Docstrings must use triple double quotes """. Note, however, that implicit line concatenation is usually clearer, because multi-line strings do not align with the indentation of the rest of the program.

Yes:
    print ("This is much nicer.\n"
           "Do it this way.\n")
No:
      print """This is pretty ugly.
  Don't do this.
  """

Files and Sockets

Explicitly close files and sockets when they are finished.

Leaving files, sockets, or other file-like objects open unnecessarily has many side effects, for example:

  1. They may consume limited system resources, such as file descriptors. If these resources are not returned to the system promptly after use, the code handling these objects will exhaust them.
  2. Holding files open can prevent other operations on the files, such as moving or deleting them.
  3. Merely closing files and sockets logically still leaves them open to inadvertent reads or writes by programs that share them. Only when they are truly closed will attempts to read or write raise exceptions, making problems appear quickly.

Moreover, the idea that files and sockets will automatically close when file objects are destructed, trying to bind the lifetime of file objects to the state of the files, is unrealistic. For the following reasons:

  1. There is no way to ensure that the runtime will actually execute the file's destructor. Different Python implementations use different memory management techniques, such as delayed garbage collection. Delayed garbage collection can cause object lifetimes to be arbitrarily and indefinitely extended.
  2. Unexpected references to files can cause files to be held longer than expected (for example, in exception tracebacks that include global variables, etc.).

It is recommended to usethe "with" statementto manage files:

with open("hello.txt") as hello_file:
    for line in hello_file:
        print line

For file-like objects that do not support the "with" statement, use contextlib.closing():

import contextlib

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

Legacy AppEngine Python 2.5 code using the "with" statement requires adding "from __future__ import with_statement".


TODO Comments

Use TODO comments for temporary code, a short-term solution. Not perfect, but good enough.

TODO comments should contain the "TODO" string at the very beginning, followed by your name, email address, or other identifier in parentheses. Then an optional colon. After that, there must be a line of comment explaining what to do. The main purpose is to have a uniform TODO format so that the person who added the comment can be searched for (and can provide more details as needed). Writing a TODO comment does not guarantee that the writer will personally fix the issue. When you write a TODO, please include your name.

# TODO(kl@gmail.com): Use a "*" here for string repetition.
# TODO(Zeke) Change this to use relations.

If your TODO is in the form "do something in the future", make sure you include a specific date ("fix in November 2009") or a specific event ("remove this code once all customers can handle XML requests").


Import Format

Each import should be on its own line

Yes: import os
     import sys
No:  import os, sys

Imports should always be placed at the top of the file, after module comments and docstrings, and before module global variables and constants. Imports should be grouped from the most general to the least general:

  1. Standard library imports
  2. Third-party library imports
  3. Application-specific imports

Within each group, imports should be sorted lexicographically by the full package path of each module, ignoring case.

import foo
from foo import bar
from foo.bar import baz
from foo.bar import Quux
from Foob import ar

Statements

Generally, each statement should be on its own line

However, if the test and the result fit on one line, you may also put them on the same line. In the case of an if statement, you may only do this if there is no else. In particular, never do this totry/exceptdo this, because try and except cannot be placed on the same line.

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)

Access Control

In Python, for trivial and unimportant access functions, you should use public variables directly instead, to avoid extra function call overhead. When adding more functionality, you can use properties to maintain syntactic consistency.

(Translator's note: object-oriented programmers who value encapsulation may be offended by this, because they have always been taught that all member variables must be private! In fact, that is really troublesome. Try to accept the Pythonic philosophy.)

On the other hand, if access is more complex, or the variable access overhead is significant, you should use something likeget_foo()andset_foo()function calls. If previous code behavior allowed access through properties, then do not bind new access functions to the property. This way, any code that tries to access the variable via the old method will fail, and users will realize the complexity has changed.


Naming

module_name, package_name, ClassName, method_name, ExceptionName, function_name, GLOBAL_VAR_NAME, instance_var_name, function_parameter_name, local_var_name.

Names to avoid

  1. Single-character names, except for counters and iterators.
  2. Hyphens (-) in package/module names
  3. Names that begin and end with double underscores (reserved by Python, e.g., __init__)

Naming conventions

  1. The so-called "Internal" means only available within the module, or, within a class, protected or private.
  2. A leading single underscore (_) indicates that a module variable or function is protected (not included when using import * from).
  3. Instance variables or methods starting with double underscores (__) are private to the class.
  4. Put related classes and top-level functions in the same module. Unlike Java, there is no need to limit one class per module.
  5. Use capitalized words for class names (e.g., CapWords, i.e., Pascal style), but module names should use lowercase with underscores (e.g., lower_with_under.py). Although many existing modules use names like CapWords.py, this is now discouraged because it can be confusing if the module name happens to match a class name.

Specifications recommended by Python's father, Guido

Type Public Internal
Modules lower_with_under _lower_with_under
Packages lower_with_under  
Classes CapWords _CapWords
Exceptions CapWords  
Functions lower_with_under() _lower_with_under()
Global/Class Constants CAPS_WITH_UNDER _CAPS_WITH_UNDER
Global/Class Variables lower_with_under _lower_with_under
Instance Variables lower_with_under _lower_with_under (protected) or __lower_with_under (private)
Method Names lower_with_under() _lower_with_under() (protected) or __lower_with_under() (private)
Function/Method Parameters lower_with_under  
Local Variables lower_with_under  

Main

Even a file intended to be used as a script should be importable. And a simple import should not cause the script's main functionality to be executed, as that is a side effect. The main functionality should be placed in a main() function.

In Python, pydoc and unit tests require modules to be importable. Your code should always check before executing the main programif __name__ == '__main__', so that the main program is not executed when the module is imported.

def main():
      ...

if __name__ == '__main__':
    main()

All top-level code is executed when the module is imported. Be careful not to call functions, create objects, or perform operations that should not be executed when using pydoc.