DEV Community

qing
qing

Posted on

How to Write Clean Python Code: 10 Principles

How to Write Clean Python Code: 10 Principles

tags: python, programming, tutorial, beginners


tags: python, programming, tutorial, beginners


How to Write Clean Python Code: 10 Principles

You’ve probably seen that code snippet where a function is 200 lines long, variables are named x, y, and temp, and comments explain what the code does instead of why. It’s painful to read, impossible to debug, and a nightmare to maintain. The good news? Clean Python code isn’t magic—it’s a set of repeatable habits. Here are 10 principles you can start applying today to write code that’s readable, maintainable, and genuinely enjoyable.

1. Choose Meaningful, Descriptive Names

The first step to clean code is choosing names that reveal intent. Instead of lr, use learning_rate. Instead of process_data, use calculate_user_revenue. Descriptive names make your code self-documenting and reduce the need for comments.

Actionable tip: If you can’t name a function or variable without hesitating, it’s probably too complex or vague. Simplify it.

2. Follow the Single Responsibility Principle

Each function should do one thing, do it well, and do it only. Long functions that mix multiple tasks are hard to test, understand, and refactor. Aim for functions under 20 lines that focus on a single task [3].

Actionable tip: If a function has more than one if block handling unrelated logic, split it into smaller functions.

3. Keep Functions Small and Focused

Small functions are easier to test, debug, and reuse. They also reduce cognitive load for anyone reading your code. A good rule of thumb: if your function feels like it’s doing too much, it probably is [2].

Actionable tip: Use the “extract method” pattern—pull out complex logic into helper functions with clear names.

4. Use Docstrings to Explain Purpose, Not Implementation

Docstrings should explain what a function does, its inputs, and its return values—not restate the code. They’re the first piece of documentation developers see in tooltips and IDEs [12].

Actionable tip: Start every function and class with a concise docstring that lists parameters and return types.

5. Follow PEP 8 Consistently

PEP 8 is Python’s official style guide. Key rules include:

  • Use 4 spaces per indentation (no tabs) [5][6]
  • Limit lines to 79 characters (or 99 for teams) [5][10]
  • Surround operators with spaces (x = a + b) [6][11]
  • Use blank lines to separate functions and classes [5][11]

Actionable tip: Automate this with tools like black, ruff, or isort. Consistent formatting reduces merge conflicts and cognitive load [2][14].

6. Write Comments That Explain Why, Not What

Code should speak for itself. Comments are valuable when they explain the reasoning behind a choice, not when they restate what the code does [2][12].

Actionable tip: Before adding a comment, ask: “Can I refactor the code to make this obvious?” If not, explain the why.

7. Avoid Global Variables and Magic Strings

Global variables make code harder to test and debug. Magic strings (like "error" or "admin") scattered across your code create multiple sources of truth. Instead, use constants or StrEnum [12].

Actionable tip: Define all constants at the top of your module or in a dedicated constants.py file.

8. Handle Exceptions Gracefully

Don’t let your program crash silently. Use try/except blocks to handle errors gracefully, and avoid bare except clauses. Always specify the exception type [5][6].

Actionable tip: Log exceptions with context and provide meaningful error messages to users.

9. Use Context Managers for Resource Handling

When working with files, sockets, or database connections, use with statements to ensure resources are cleaned up automatically. This prevents leaks and simplifies error handling [5][11].

Actionable tip: Replace manual open()/close() patterns with with open(...) as f:.

10. Write Unit Tests for Your Code

Tests aren’t just for catching bugs—they’re documentation. They show how your code is expected to behave and make refactoring safer [5][9].

Actionable tip: Write tests for every public function. Use clear, descriptive test names like test_calculate_revenue_with_discount.


Putting It All Together: A Clean Code Example

Here’s a messy function and its clean counterpart that applies all 10 principles:

# ❌ Messy version
def proc(d):
    x = 0
    for i in d:
        if i > 5:
            x += i
        else:
            x -= 1
    return x

# ✅ Clean version
from typing import List

def calculate_sum_above_threshold(values: List[int], threshold: int = 5) -> int:
    """
    Calculate the sum of values greater than the threshold,
    subtracting 1 for each value below or equal to it.

    Args:
        values: List of integers to process.
        threshold: Minimum value to include in sum (default: 5).

    Returns:
        Final calculated sum.
    """
    total = 0
    for value in values:
        if value > threshold:
            total += value
        else:
            total -= 1
    return total
Enter fullscreen mode Exit fullscreen mode

Notice the descriptive name, type annotations, docstring, small scope, and clear logic. This is code you (and your team) will thank yourself for later.


Start Today, Not Tomorrow

Clean code isn’t about perfection—it’s about consistency. Pick one or two of these principles and apply them to your next commit. Then add another. Over time, these habits will transform your code from a maintenance burden into a reliable asset.

Your call to action: Open your most recent Python file. Find one function that violates these principles. Refactor it using at least three of the 10 rules above. Share your before/after snippet on Dev.to or with your team—clean code is a community effort.

What’s the first principle you’ll start applying today? Let’s build cleaner code together.


If you found this helpful, consider buying me a coffee ☕ — it keeps these articles coming!

Also check out my AI tools collection: AI 次元世界 — free AI tools for developers.

Top comments (0)