Fundamentals 8 min read

Essential Python Coding Style Guide: Simple Rules for Clean Code

This article distills the most practical Python coding conventions into clear principles, minimal guidelines, detailed formatting rules, naming standards, writing tips, and commenting practices to help developers write readable, consistent, and maintainable code.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Essential Python Coding Style Guide: Simple Rules for Clean Code

0. Introduction

This article summarizes the most essential and simple Python coding conventions after reading "Python Coding Rule", offering personal choices that are easy to follow, intended for reference.

1. Important Principles

a. Consistency in style is important, but the most crucial thing is knowing when to be inconsistent. b. Two good reasons to break an established rule: • When following the rule reduces code readability. • To stay consistent with surrounding legacy code.

2. Minimal Guidelines

a. Use spaces for indentation only. b. Use UTF-8 encoding. c. Write one statement per line. d. Use a backslash at line end to fold long lines, limiting each line to a maximum of 79 characters. e. Import statements: one per line, ordered from standard library to third‑party to project modules, using absolute imports. f. Separate class methods with one blank line; separate top‑level functions/classes with two blank lines. g. Surround operators (except *) with a single space; no spaces around the equals sign in default arguments. h. Use lowercase with underscores for modules, functions, methods, and variables; use CamelCase for class names. i. One leading underscore denotes “protected”, two leading underscores denote “private”, and a trailing underscore avoids conflicts with reserved words. j. Write comments in Chinese during development; provide English documentation for released scripts.

3. Detailed Guidelines

a. General rules for the whole codebase. b. Indent with four spaces per level. c. Keep line length within 79 characters, using a backslash to continue long lines. d. Use UTF-8 encoding. e. One statement per line.

4. Naming Conventions

Import one module per line; order imports as standard library, related third‑party packages, then specific application packages, with a blank line between groups, using absolute paths. Separate top‑level function and class definitions with two blank lines, and class methods with one blank line; ensure a blank line after the class declaration before the first method. Write spaces after commas and semicolons only; do not add spaces inside parentheses, brackets, or braces. Use a single space around operators (except *). No spaces around the equals sign in function arguments. Module names: short, all lowercase, no underscores. Class and exception names: CapitalizedWords (CamelCase). Function, global variable, method, and instance variable names: lowercase with underscores. A single leading underscore marks non‑public globals, internal functions, or methods. Double leading underscores indicate class‑private names to avoid name clashes in inheritance. Private attributes must have two leading underscores and no trailing underscore. Non‑public attributes have one leading underscore and no trailing underscore. Public attributes have no leading or trailing underscores, unless a trailing underscore is needed to avoid a keyword conflict (e.g., class_ is preferred over klass).

5. Writing Tips

Compare singletons like None using is or is not (e.g., if x is not None:). Define base exception classes within modules and packages. Prefer string methods over the string module. Use startswith() and endswith() instead of slicing for prefix/suffix checks. Use isinstance() for type checking rather than comparing types directly. Do not compare a boolean to True or False with ==; simply write if condition:.

6. Comments

Write comments in Chinese during development; provide English documentation for released tools. Comments should be complete sentences (or short phrases) with the first letter capitalized; omit the final period for very short comments. A comment block consists of one or more full sentences, each ending with a period, followed by two spaces. Start each comment line with # and align it with the code’s indentation; surround comment blocks with a blank line above and below. Use inline comments sparingly, separating them from code with at least two spaces. Employ documentation tools such as pydoc, epydoc, or Doxygen; write docstrings for all public modules, functions, classes, and methods. Non‑public methods need not have docstrings, but a brief comment describing their purpose should follow the def line. Triple‑quoted docstrings should have the closing """ on its own line.

Version note: define a variable __version__ = "$Revision: 1.4 $" Stay hungry. Stay foolish.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

best practicesnaming conventionsreadabilitycoding stylepep8
MaGe Linux Operations
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.