Fundamentals 25 min read

Master Python Coding Standards: 50 Essential Best Practices for Clean, Maintainable Code

This comprehensive guide presents 50 practical Python coding best‑practice rules covering naming, function design, object‑oriented principles, exception handling, code style, and project structure, showing how to write self‑explanatory, reusable, and robust code that stands the test of time and team collaboration.

21CTO
21CTO
21CTO
Master Python Coding Standards: 50 Essential Best Practices for Clean, Maintainable Code

1. Code Expression: Self‑Explanatory Over Comments

Python code should be clear enough that comments become redundant. Use descriptive names and structures so the code reads like natural language.

2. Code Expression – Self‑Explanatory

Prefer clear, expressive code over excessive comments. Well‑named variables, functions, and classes convey intent without extra notes.

Rule 1: Code Should Be Self‑Explanatory

Avoid relying on comments; let the code speak for itself.

Rule 2: Use Meaningful Names

Names should reflect purpose and type, avoiding vague or redundant prefixes.

Rule 3: Prefer Clear Naming Over Comments

Use descriptive identifiers instead of comments to explain logic.

3. Function Design: Single Responsibility, Simplicity, Layered Abstraction

Rule 4: Single Responsibility Principle (SRP)

Each function should perform one distinct task, improving readability, testability, and maintainability.

Example of a good single‑purpose function:

def calculate_user_total_score(user):
    # implementation

Rule 5: Function Names Should Use Verbs

Function names must start with an action word to indicate their behavior, e.g., process_user_data() instead of user_data().

Rule 6: Keep Function Signatures Clear

Specify parameter and return types to improve IDE assistance and reduce errors.

Rule 7: Avoid Redundant Type Information in Names

Do not embed type hints in names like user_name_str; the type system already conveys that.

Rule 8: Use Descriptive Parameter Names

Parameters should clearly indicate their role, e.g., user_id instead of uid.

Rule 9: Keep Function Body Small

Limit functions to about 20 lines of code (excluding comments) to maintain focus.

Rule 10: Split Large Functions

If a function exceeds the limit, break it into smaller, cohesive functions.

4. Exception Handling: Robust and Clear

Rule 26: Use try‑except‑finally Wisely

Apply exception handling only where failures are possible (e.g., file I/O, API calls). Use finally for cleanup.

try:
    file = open("data.txt", "r")
    data = file.read()
except FileNotFoundError:
    print("Error: file not found")
finally:
    file.close()

Rule 27: Provide Context in Error Messages

Include operation details and original exception information to aid debugging.

except Exception as e:
    print(f"Failed to read data.txt: {e}")

Rule 28: Avoid Overusing Multiple Exception Types

Catch specific exceptions first, then use a generic except Exception for the rest.

Rule 38: Do Not Use assert for Validation in Production

Replace assert with explicit raise ValueError(...) to ensure checks are always performed.

5. Code Style & Engineering: Maintainable Collaboration

Rule 16: Limit Source File Length

Keep files between 100–500 lines; split larger files into logical modules.

Rule 17: Separate Logical Blocks with Blank Lines

Use empty lines to visually separate sections within functions and between functions.

Rule 19: Use Spaces to Indicate Association Strength

No space between function name and parentheses indicates strong coupling; spaces between parameters indicate weaker coupling.

Rule 20: Follow Team Coding Standards

Adopt the team’s agreed naming, indentation, and style guidelines.

Rule 21: Replace Magic Numbers with Constants

Define meaningful constants, e.g., NUM_OF_RECENT_ORDERS = 50, instead of hard‑coded literals.

Rule 25: Avoid Hard‑Coded Paths

Use environment variables or configuration files for file locations.

import os
file_path = os.getenv("FILE_PATH")

Rule 34: Use with Statements for Resource Management

Automatically close files or connections.

with open("example.txt", "r") as file:
    data = file.read()

Rule 35: Prefer if‑elif Over Complex Ternary Expressions

Complex conditional logic should be expressed with clear if‑elif‑else blocks.

Rule 36: Use is/is not for Mutable Types, == for Immutable

Check identity for lists/dicts, equality for strings/ints.

Rule 37: Apply Dependency Inversion Principle (DIP)

Depend on abstractions, not concrete implementations.

from abc import ABC, abstractmethod

class LoggerInterface(ABC):
    @abstractmethod
    def log(self, message: str) -> None:
        pass

class FileLogger(LoggerInterface):
    def log(self, message: str):
        with open("log.txt", "a") as f:
            f.write(message + "
")

class Calculator:
    def __init__(self, logger: LoggerInterface):
        self.logger = logger
    def add(self, x: int, y: int) -> int:
        result = x + y
        self.logger.log(f"Add: {x}+{y}={result}")
        return result

Rule 39: Follow DRY – Don't Repeat Yourself

Extract common logic into reusable functions.

def calculate_product_price(quantity: int, price: float) -> float:
    return quantity * price

book_total = calculate_product_price(2, 50.0)
laptop_total = calculate_product_price(1, 5000.0)

Rule 40: Adhere to PEP 8

Use snake_case for functions/variables, PascalCase for classes, 4‑space indentation, line length ≤79 characters, and explicit imports.

from math import sqrt, pow

class CircleCalculator:
    def calculate_area(self, radius: float) -> float:
        return 3.14159 * pow(radius, 2) + sqrt(radius)

Rule 41: Law of Demeter – Interact Only with Direct Friends

Avoid chaining calls like order.customer.profile.name; expose needed data via methods.

class Customer:
    def __init__(self, name: str):
        self._profile = Profile(name)
    def get_name(self) -> str:
        return self._profile.get_name()

class Order:
    def __init__(self, customer: Customer):
        self.customer = customer
    def get_customer_name(self) -> str:
        return self.customer.get_name()

Rule 42: Readability Over Brevity

Write code that is easy to understand first; concise tricks are secondary.

Rule 43: Clean Imports – Import Only What You Need

Avoid from module import * to prevent name clashes.

from math import sqrt, pow

6. Summary – Simplicity Is Core

All the rules converge on a single principle: write simple, clear, and maintainable code. Follow tests, avoid duplication, use expressive names, keep classes and methods minimal, and adhere to established standards. This creates a solid foundation for collaborative development and long‑term code health.

Author: 场长
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.

Pythoncoding standardssoftware designclean code
21CTO
Written by

21CTO

21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.

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.