Purpose: This guide defines coding standards for Python code at Google. Use these rules consistently in all Python projects.
- Maximum: 80 characters
- Exceptions:
- Long import statements
- URLs in comments
- Long string module level constants
- Pylint disable comments
- Use 4 spaces per indentation level
- Never use tabs
- Continuation lines should align vertically or use 4-space hanging indent
# Correct
foo = long_function_name(
var_one, var_two, var_three,
var_four)
# Correct - hanging indent
foo = long_function_name(
var_one, var_two,
var_three, var_four
)- Two blank lines between top-level definitions (functions/classes)
- One blank line between method definitions
- One blank line between class docstring and first method
- No blank line after a
defline
- No whitespace inside parentheses, brackets, or braces:
spam(ham[1], {'eggs': 2}) - No whitespace before comma, semicolon, or colon
- Whitespace after comma, semicolon, or colon (except end of line)
- Surround binary operators with single space:
x == 1,x + y - No spaces around
=for keyword arguments:def complex(real, imag=0.0) - Exception: With type annotations, use spaces:
def complex(real, imag: float = 0.0) - No trailing whitespace
- Use Python's implicit line joining inside parentheses, brackets, braces
- Avoid backslashes for line continuation
# Correct
if (width == 0 and height == 0 and
color == 'red' and emphasis == 'strong'):
pass
# Wrong
if width == 0 and height == 0 and \
color == 'red' and emphasis == 'strong':
pass- Use sparingly
- OK for tuples, implied line continuation, or indicating tuples
- Don't use in return statements or conditionals unless necessary
# Correct
if foo:
bar()
return spam, beans
# Wrong
if (x):
bar()
return (foo)- Recommended when closing bracket not on same line as final element
- Required for single-element tuples:
onesie = (foo,)
- Always at top of file (after module docstring, before globals)
- Group imports in order:
from __future__ importstatements- Python standard library
- Third-party modules/packages
- Code repository sub-packages
- Application-specific imports (deprecated, treat as sub-packages)
# Correct
from collections.abc import Mapping, Sequence
import os
import sys
from typing import Any, NewType
# Wrong
import os, sys- Use
import xfor packages and modules only - Use
from x import ywherexis package prefix,yis module name - Use
from x import y as zwhen:- Two modules named
ywould be imported yconflicts with top-level nameyconflicts with common parameter nameyis inconveniently longyis too generic
- Two modules named
- Use full package paths (absolute imports, not relative)
- Sort imports lexicographically by full module path
# Correct
from sound.effects import echo
echo.EchoFilter(input, output, delay=0.7)
# Wrong
import echo # Relative import| Type | Convention | Example |
|---|---|---|
| Packages | lowercase |
mypackage |
| Modules | lowercase_with_underscores |
my_module.py |
| Classes | CapWords |
MyClass |
| Exceptions | CapWords (end with Error) |
MyCustomError |
| Functions | lowercase_with_underscores |
my_function() |
| Global/Class Constants | CAPS_WITH_UNDERSCORES |
MAX_OVERFLOW |
| Global/Class Variables | lowercase_with_underscores |
global_var |
| Instance Variables | lowercase_with_underscores |
instance_var |
| Method Names | lowercase_with_underscores |
method_name() |
| Function Parameters | lowercase_with_underscores |
function_parameter |
| Local Variables | lowercase_with_underscores |
local_var |
- Prefix with single underscore
_for internal use - Prefix with double underscore
__for class-private (rarely needed)
- No semicolons to end lines
- Never put two statements on same line
- Use implicit
Falsewhen possible if foo:instead ofif foo != []:- Always use
if foo is None:(oris not None) - Never compare boolean to
Falseusing==: useif not x: - For sequences, use
if seq:notif len(seq): - For integers (not from
len()), compare explicitly:if i % 10 == 0:
# Correct
if not users:
print('no users')
if x is None:
x = []
# Wrong
if len(users) == 0:
print('no users')
if x == None:
x = []- OK to use, but:
- Never use mutable objects as default values
- Use
Noneas default, then assign mutable in function body
# Correct
def foo(a, b=None):
if b is None:
b = []
# Wrong
def foo(a, b=[]): # Mutable default!
...- Prefer small, focused functions
- No hard limit, but consider breaking up if > 40 lines
- OK for one-liners
- If > 60-80 chars or multiline, use regular nested function
- Prefer
operatormodule functions over lambda:operator.mulnotlambda x, y: x * y
- Use
@propertydecorator for attribute access - Properties should be:
- Cheap computations
- Straightforward
- Unsurprising
- Don't use properties for complex computations that subclasses might override
- Use judiciously when there's clear advantage
- Never use
staticmethodunless forced by external API (use module-level function) - Use
classmethodonly for named constructors or class-specific global state modifications - Write unit tests for decorators
- Don't rely on atomicity of built-in types
- Use
queue.Queuefor thread communication - Use
threadingmodule and locking primitives - Prefer
threading.Conditionover lower-level locks
- Use f-strings,
%operator, or.format()method - Don't format with
+operator
# Correct
x = f'name: {name}; score: {n}'
x = '%s, %s!' % (imperative, expletive)
x = '{}, {}'.format(first, second)
# Wrong
x = 'name: ' + name + '; score: ' + str(n)- Pick single quotes or double quotes and be consistent within file
- Use triple double-quotes for multi-line strings (docstrings)
- Projects may use triple single-quotes for non-docstring multi-line if using single quotes for regular strings
- Use concatenated single-line strings or
textwrap.dedent() - Avoid embedding extra indentation spaces
- OK for simple cases
- No multiple
forclauses - No multiple
ifexpressions (except simple filter) - Optimize for readability, not conciseness
# Correct
result = [mapping_expr for value in iterable if filter_expr]
# Wrong
result = [(x, y) for x in range(10) for y in range(5) if x * y > 10]- Use as needed
- Use
Yields:in docstring, notReturns: - Manage expensive resources with context managers
- Use default iterators for types that support them
# Correct
for key in adict: ...
if obj in alist: ...
# Wrong
for key in adict.keys(): ...- Use built-in exception classes when appropriate
- Custom exceptions must inherit from existing exception class
- Exception names should end in
Error - Never use catch-all
except: - Never catch
ExceptionorStandardErrorunless re-raising or at top level - Minimize code in
tryblock - Use
finallyfor cleanup
- Don't use
assertfor data validation or in place of conditionals - Only use for verifying internal correctness (can be disabled)
- OK in pytest tests
# Correct
if minimum < 1024:
raise ValueError(f'Min. port must be at least 1024, not {minimum}.')
# Wrong - don't rely on assert
assert minimum >= 1024, 'Minimum port must be at least 1024.'
port = self._find_next_open_port(minimum)- Avoid mutable global state
- If necessary:
- Declare at module level or as class attribute
- Make internal with
_prefix - Provide public functions/methods for external access
- Document design reasons in comments
- Permitted and encouraged
- Use
ALL_CAPS_WITH_UNDERSCORES - Prefix with
_for internal use
_MAX_HOLY_HANDGRENADE_COUNT = 3 # Internal
SIR_LANCELOTS_FAVORITE_COLOR = "blue" # Public API- OK when closing over local variable (not just
selforcls) - Don't nest just to hide from module users (use
_prefix instead) - Makes testing easier
- Strongly encouraged for new code and when updating existing code
- Enable type checking with tools like
pytype - Annotate function/method arguments and return values
- Can annotate variables with similar syntax
def func(a: int) -> list[int]:
...
a: SomeType = some_func()- Don't annotate
selforcls(useSelfif needed for proper typing) - Don't annotate
__init__return value (alwaysNone) - Use
Anyfor types that can't be expressed - Use
| Nonefor optional types (PEP 604 union syntax preferred overOptional)
- One parameter per line for long signatures
- Return type on its own line or same line as last parameter
- Align closing parenthesis with
def
def my_method(
self,
first_var: int,
second_var: Foo,
third_var: Bar | None,
) -> int:
...- Every file should have module docstring
- Describe contents and usage
- Include usage examples if helpful
"""A one-line summary of the module or program, terminated by a period.
Leave one blank line. The rest of this docstring should contain an
overall description of the module or program. Optionally, it may also
contain a brief description of exported classes and functions and/or usage
examples.
Typical usage example:
foo = ClassFoo()
bar = foo.function_bar()
"""- Required for functions that are:
- Part of external API
- Non-trivial
- Not immediately obvious
- Describe calling syntax and semantics, not implementation
- Use descriptive or imperative style consistently
Sections (if applicable):
Args:- Each parameter with type and descriptionReturns:- Describe return value and typeRaises:- Exceptions that callers need to handleYields:- For generators
def fetch_rows(
table_handle: Table,
keys: Sequence[bytes | str],
require_all_keys: bool = False,
) -> Mapping[bytes, tuple[str, ...]]:
"""Fetches rows from a Smalltable.
Retrieves rows pertaining to the given keys from the Table instance
represented by table_handle. String keys will be UTF-8 encoded.
Args:
table_handle: An open smalltable.Table instance.
keys: A sequence of strings representing the key of each table
row to fetch. String keys will be UTF-8 encoded.
require_all_keys: If True only rows with values set for all keys will be
returned.
Returns:
A dict mapping keys to the corresponding table row data
fetched. Each row is represented as a tuple of strings.
Raises:
IOError: An error occurred accessing the smalltable.
"""- Describe what class instance represents
- Document public attributes in
Attributes:section - One-line summary should describe what instance represents
class SampleClass:
"""Summary of class here.
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.
"""- Use complete sentences with proper punctuation
- Block comments:
#followed by single space - Inline comments: Two spaces before
# - Update comments when updating code
- Use for temporary, short-term, or good-enough-but-not-perfect code
# TODO: crbug.com/192795 - Investigate cpufreq optimizations.
# TODO(username): Use a "*" here for concatenation operator.- Even for scripts, make executable code callable from other modules
- Use
if __name__ == '__main__':guard - Minimal code at top level (only when pydocing is safe)
def main():
...
if __name__ == '__main__':
app.run(main) # or main() if not using absl- Use
#!/usr/bin/env python3(supports virtualenvs) - Or
#!/usr/bin/python3 - Only needed for executable files, not imported modules
- Run
pylintover your code - Suppress warnings appropriately with comments:
def do_PUT(self): # WSGI name, so pylint: disable=invalid-name
- Include explanation if symbolic name isn't clear
- Prefer
pylint: disable=nameover deprecatedpylint: disable-msg
- Delete at beginning of function with explanation
def viking_cafe_order(spam: str, beans: str, eggs: str | None = None) -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam- Custom metaclasses (except
abc.ABCMeta,dataclasses,enum) - Access to bytecode
- On-the-fly compilation
- Dynamic inheritance
- Object reparenting
- Import hacks
- Some uses of reflection/
getattr() - Modification of system internals
__del__methods
- Hard to read, understand, and debug
- May seem clever but creates maintenance burden
- Standard library modules using these are OK to use
- OK for simple cases
- Each portion must fit on one line
# Correct
one_line = 'yes' if predicate(value) else 'no'
# Wrong - line breaking
bad = ('yes' if predicate(value) else
'no')- Use
from __future__ importstatements as needed - Enables newer Python features in older runtimes
- Keep in file until confident code only runs in modern environments
from __future__ import annotations # For type annotations✅ Formatting: 80 chars, 4 spaces, proper whitespace
✅ Imports: Absolute imports, grouped and sorted, one per line
✅ Naming: snake_case for functions/variables, CapWords for classes
✅ Types: Annotate public APIs, use type checker
✅ Docstrings: Module, class, and public function docstrings with proper sections
✅ Exceptions: Use built-in exceptions, no catch-all except
✅ Functions: Small and focused, no mutable defaults
✅ Strings: Use f-strings or .format(), consistent quotes
✅ Comprehensions: Simple only, optimize for readability
✅ Lint: Run pylint, fix or suppress warnings appropriately
✅ Main guard: Use if __name__ == '__main__':
✅ Avoid: Power features, mutable global state, assert for validation
Version: Based on Google Python Style Guide (https://google.github.io/styleguide/pyguide.html) Last Updated: December 2025