Master Google Python Style Guide: Essential Coding Standards Explained
This comprehensive guide translates Google's Python style guide into clear English, covering everything from naming conventions and imports to docstrings, type annotations, and best practices for functions, classes, and modules, helping developers write clean, consistent, and maintainable Python code.
1 Introduction
This document is a full translation of the Google Python Style Guide, providing a detailed reference for writing clean, consistent, and maintainable Python code.
2 Python Language Rules
2.1 Lint
Use pylint to enforce style. Suppress warnings with # pylint: disable=... when necessary, but keep the list short.
2.2 Imports
Import each module on its own line. Order imports by groups: future imports, standard library, third‑party libraries, and internal packages. Sort alphabetically within each group.
2.3 Packages
Always import full package paths; avoid relative imports. Use import x.y.z rather than from . import z.
2.4 Exceptions
Raise specific exceptions, avoid catching except: unless absolutely required. Prefer raise ValueError(...) over generic Exception.
2.5 Global Variables
Avoid mutable globals. Use module‑level constants in ALL_CAPS and prefix private globals with an underscore.
2.6 Inner Classes and Functions
Define inner classes/functions only when they are truly scoped to the enclosing function. Keep them small and testable.
2.7 List Comprehensions
Prefer list comprehensions for simple cases; avoid complex nested comprehensions.
2.8 Default Iterators and Operators
Use Python’s implicit iteration (e.g., for x in seq) and membership tests ( in) instead of explicit index checks.
2.9 Generators
Use generators for lazy evaluation. Document yielded values with a Yields: section.
2.10 Lambda Expressions
Use lambda only for simple, single‑expression functions; otherwise define a regular function.
2.11 Conditional Expressions
Use ternary operators for short conditions; otherwise write a full if / else block.
2.12 Default Parameter Values
Never use mutable objects as default values. Use None and assign inside the function when needed.
2.13 Properties
Prefer @property for simple getters/setters to keep the API clean.
2.14 Truthiness
Leverage Python’s implicit boolean evaluation (e.g., if seq:) instead of explicit length checks.
2.15 Deprecated Features
Avoid old Python 2 constructs such as apply, string module functions, and has_key().
2.16 Lexical Scoping
Understand closures and the nonlocal keyword to avoid common pitfalls.
2.17 Decorators
Use decorators sparingly; document their effect and test them thoroughly.
2.18 Threading
Prefer queue.Queue for thread communication and avoid relying on built‑in atomicity.
2.19 Powerful Language Features
Use metaclasses, bytecode manipulation, and dynamic imports only when absolutely necessary.
2.20 Python 3 Migration
Include
from __future__ import absolute_import, division, print_functionin all new code to ease transition to Python 3.
2.21 Type Annotations
Annotate public APIs with PEP‑484 types. Use Optional, Union, and Any appropriately. Prefer def func(x: int) -> str: syntax.
3 Python Code Style Guidelines
3.1 Line Length
Limit lines to 80 characters. Exceptions include long imports, URLs, and # pylint: disable=... comments.
3.2 Indentation
Use 4 spaces per indentation level; never mix tabs.
3.3 Whitespace
No spaces inside parentheses, brackets, or braces. One space after commas, colons, and semicolons.
3.4 Blank Lines
Separate top‑level definitions with two blank lines and methods with one blank line.
3.5 Docstrings
Every module, class, and public function should have a triple‑quoted docstring. Follow the summary line. blank line. detailed description format.
3.6 Naming Conventions
Modules and packages: lower_with_underscores Classes: CapWords Functions and methods: lower_with_underscores() Constants: ALL_CAPS Private names: leading underscore
3.7 Imports
One import per line, grouped as described in section 2.2.
3.8 Strings
Prefer format() or f‑strings for formatting. Use triple‑quoted strings for multi‑line text and avoid concatenating strings with + inside loops.
3.9 Main Guard
Wrap executable code in if __name__ == '__main__': and place logic in a main() function.
3.10 Function Length
Prefer short, focused functions. If a function exceeds ~40 lines, consider refactoring.
4 Final Thoughts
Adopt the style guide consistently across a project to improve readability and maintainability. When contributing to existing code, follow the prevailing style to avoid unnecessary churn.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
