Python Coding Standards (Google)
Category Programming Techniques
This project is not an official Google project, but is created and maintained by domestic programmers with enthusiasm.
If you are interested in the official English version of Google, please go to Google Style Guide
The following code Yes indicates recommended, No indicates not recommended.
Semicolons
Do not add semicolons at the end of the line, nor use semicolons to put two commands on the same line.
Line Length
No more than 80 characters per line
The following exceptions apply:
Long import module statements
URLs in comments
Do not use backslashes to connect lines.
Python will implicitly connect lines in parentheses, brackets, and curly braces, you can take advantage of this feature. If necessary, you can add an extra pair of parentheses around the expression.
Recommended: 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 cannot fit on one line, you can use parentheses to achieve implicit line connection:
x = ('This is a very long very long very long very long '
'very long very long very long very long very long string')
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 indentation of the elements in the above example; 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 connection. However, it is acceptable to use parentheses on both sides of a tuple.
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
Indent code with 4 spaces
Never use tabs, nor mix tabs and spaces. For line connections, you should either vertically align the elements of the line break (see the example in the :ref:line length <line_length>
section), or use a 4-space hanging indent (the first line should not have parameters):
Yes: # Aligned with the starting variable
foo = long_function_name(var_one, var_two,
var_three, var_four)
# Aligned with the starting value in the dictionary
foo = {
long_dictionary_key: value1 +
value2,
...
}
# 4-space indentation, the first line does not need it
foo = long_function_name(
var_one, var_two, var_three,
var_four)
# 4-space indentation in the dictionary
foo = {
long_dictionary_key:
long_dictionary_value,
...
}
No: # The first line with spaces is prohibited
foo = long_function_name(var_one, var_two,
var_three, var_four)
# 2 spaces are prohibited
foo = long_function_name(
var_one, var_two, var_three,
var_four)
# Indentation not handled in the dictionary
foo = {
long_dictionary_key:
long_dictionary_value,
...
}
Blank Lines
Two blank lines between top-level definitions, one blank line between method definitions
There should be two blank lines between top-level definitions, such as function or class definitions. There should be one blank line between method definitions, and between the class definition and the first method. Within functions or methods, you can add a blank line where you think it is appropriate.
Spaces
Use spaces around punctuation according to standard formatting conventions
Do not leave spaces inside parentheses.
Use spaces around punctuation according to standard formatting conventions.
Yes: spam(ham[1], {eggs: 2}, [])
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 just below its definition. If your class has public attributes, there should be an Attributes section in the docstring, following 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 Line Comments
>
The most comment-worthy parts of the code are those that involve tricks. If you have to explain it during the next code review, then you should comment it now. For complex operations, write several lines of comments before the operation begins. For code that is not immediately obvious, 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 separated from the code by at least two spaces.
On the other hand, never describe the code. Assume that the person reading the code knows Python better than you do; they just don't 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
Classes
If a class does not inherit from another class, explicitly inherit from object. Nested classes should do the same.
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 from object
is to make properties work properly, and it protects your code from a special potential incompatibility with Python 3000. Doing so 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 loops. Since strings are immutable, doing so will create unnecessary temporary objects and result in quadratic rather than linear running time. As an alternative, you can add each substring to a list and then join the list with For objects similar to files that do not support the use of 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)
For code in Legacy AppEngine using Python 2.5 with "with" statement, it is necessary to add "from __future__ import with_statement".
TODO Comments
Use TODO comments for temporary code; it's a short-term solution. It's not perfect, but it's good enough.
TODO comments should include the string "TODO" at the beginning, followed by your name, email address, or other identifier in parentheses. Then there should be an optional colon. There must be a line of comment explaining what needs to be done. The main purpose is to have a unified TODO format so that those who add comments can search for them (and provide more details as needed). Writing a TODO comment does not guarantee that the person who wrote it will solve the problem personally. When you write a TODO, please include your name.
# TODO([email protected]): Use a "*" here for string repetition.
# TODO(Zeke) Change this to use relations.
If your TODO is in the form of "do something in the future," then make sure you include a specific date ("resolve by November 2009") or a specific event ("remove this code when all customers can handle XML requests").
Import Formatting
Each import should occupy a line by itself.
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 in order from most to least common:
Standard library imports
Third-party library imports
Application-specific imports
Within each group, they should be sorted in dictionary order, ignoring case, based on the full package path of each module.
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 occupy a line by itself.
However, if the test results and the test statement can fit on one line, you can also put them on the same line. If it is an if statement, this can only be done if there is no else. In particular, never do this for try/except
, because try and except cannot be 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 less important access functions, you should directly use public variables instead to avoid the extra function call overhead. When adding more features, you can use properties to maintain syntactic consistency.
(Translator's note: Object-oriented programmers who value encapsulation may be very averse to seeing this, as they have always been taught that all member variables must be private! In fact, that is really a bit troublesome. Try to accept the Pythonic philosophy)
On the other hand, if the access is more complex, or the variable access cost is significant, then you should use function calls like get_foo()
and set_foo()
. If the previous code behavior allows access through properties, then do not bind new access functions with properties. In this way, any code that tries to access the variable through the old method will not run, and the user will realize that 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
>
Single character names, except for counters and iterators.
Hyphens in package/module names.
Names starting and ending with double underscores (reserved by Python, such as
__init__
)
Naming Conventions
>
The term "Internal" means only available within the module, or within the class it is protected or private.
A single underscore (_) at the beginning indicates that module variables or functions are protected (not included when using import * from).
Instance variables or methods starting with double underscores (__) indicate they are private within the class.
Place related classes and top-level functions in the same module. Unlike Java, there is no need to restrict one class per module.
Use capitalized words for class names (e.g., CapWords, i.e., Pascal style), but module names should