Python Mastery: Complete Beginner to Professional
Documentation & Maintenance

Smart Commenting: The Art of Explanation

Code tells the machine how to do something. Comments tell the human why it is being done. Master the delicate balance between helpful documentation and visual clutter.

Imagine walking into a massive library where the books have no covers, no titles, and are sorted randomly by color. That is a codebase without comments. You might eventually find what you're looking for, but it will take hours of frustrating skimming.

The Librarian Analogy: Think of your code logic as the "Books" (the actual content) and your comments as the "Card Catalog" or "Librarian" (the metadata that helps you navigate). A good librarian doesn't read the book out loud to you (redundant comments); they point you to the right section and warn you if a book is outdated or fragile.

In professional software engineering, writing code is only 20% of the job. The other 80% is reading, debugging, and maintaining code written by others (or your past self). High-quality documentation is what separates "write-only" legacy scripts from enduring, maintainable software products.

What You'll Learn

  • The Golden Rule: Explaining "Why" not "How".
  • Docstrings (PEP 257): The industry standard for function documentation.
  • Type Hinting: The modern replacement for variable comments.
  • Technical Debt: Using TODO and FIXME tags effectively.
  • Anti-Patterns: Avoiding "Zombie Comments" and clutter.

The Golden Rule: "Why" vs "What"

The single biggest mistake intermediates make is commenting on syntax rather than intent. The code itself already explains the syntax. If your code is so complex that it needs a comment to explainwhat it's doing, you should probably refactor the code (rename variables, break into functions) rather than comment it.

CategoryBad Comment (The "Captain Obvious")Good Comment (The "Navigator")
Variablestimeout = 10 # Set timeout to 10timeout = 10 # Legacy API requirement (Ticket #404)
Logici += 1 # Increment ii += 1 # Compensate for 0-based indexing
Conditionalsif x < 0: # If x is less than 0if x < 0: # Negative balance triggers overdraft protection
Refactoring Over Commenting
PYTHON
# ❌ BAD: Complex logic with explanatory comments
# Check if user is over 18 and has active subscription
if u.age &gt; 18 and u.status == 'active' and u.balance &gt; 0:
    process_order()

# ✅ GOOD: Self-documenting code (No comments needed!)
def is_eligible_for_purchase(user):
    return (
        user.is_adult 
        and user.has_active_subscription 
        and user.has_positive_balance
    )

if is_eligible_for_purchase(user):
    process_order()

Docstrings: The Professional Standard

While regular comments (#) are for the developer maintaining the implementation, Docstrings (Documentation Strings) are for the developer using your interface. They are a formal specification of input, output, and behavior.

Python treats Docstrings differently than comments. They are retained at runtime in the __doc__ attribute, allowing tools like IDEs (VS Code, PyCharm) to pop up helpful tooltips when you type a function name.

The Google Style Guide

There are several formats for docstrings (reStructuredText, NumPy, Epytext), but the Google Style is widely considered the most readable for humans.

Anatomy of a Perfect Docstring
PYTHON
def connect_to_database(url: str, retries: int = 3) -&gt; bool:
    """
    Establishes a secure connection to the primary database replica.

    Backs off exponentially if the connection fails, up to the specified
    number of retries. Uses SSL by default.

    Args:
        url (str): The JDBC or ODBC connection string.
            Example: 'postgresql://user:pass@localhost:5432/db'
        retries (int, optional): Max connection attempts before giving up. 
            Defaults to 3.

    Returns:
        bool: True if connection successful, False if all retries failed.

    Raises:
        ConnectionTimeout error: If the server is reachable but unresponsive.
        ValueError: If the URL format is invalid.
    """
    # Implementation hidden...
    return True
🔍
Try it yourself: Copy that function into VS Code. Then, in a new line, type connect_to_database(. Notice how VS Code displays the "Args" and "Returns" info? That is the power of Docstrings interacting with the Pylance language server.

Managing Technical Debt: TODO and FIXME

Software is never finished. Sometimes you need to leave a placeholder, mark a hacky fix, or note an area for optimization. Instead of random notes, professional teams use standardized "Tags".

Project Tags
PYTHON
def calculate_tax(amount):
    # TODO: Switch to external TaxJar API for international support
    rate = 0.20
    
    # FIXME: This crashes if amount is negative!
    # HACK: Use abs() for now until validation is fixed upstream
    return abs(amount) * rate

    # OPTIMIZE: This nested loop is O(n^2), refactor to use a hash map
    for item in items:
        # ...

Why use these keywords?

  • Searchability: You can grep your entire project for TODO to generate a task list.
  • IDE Integration: VS Code extensions like "Todo Tree" explicitly highlight these in the sidebar.
  • CI/CD Safety: Some build pipelines (like in Rust or Go) can be configured to fail deployment if FIXME tags remain in main.

Comments vs Type Hinting

Before Python 3.5, developers often used comments to specify types. This is now considered "Legacy" practice. Modern Python uses Type Hints (PEP 484), which are standard, readable, and verifiable by tools.

Evolution of Type Syntax
PYTHON
# ❌ LEGACY (Pre-2015): Using comments (Fragile)
def greet(name):
    # type: (str) -&gt; str
    return "Hi " + name

# ✅ MODERN (Recommended): Using Type Hints (Robust)
def greet(name: str) -&gt; str:
    return f"Hi {name}"

Common Anti-Patterns

🧟 The Zombie Comment

Code that is commented out instead of deleted. "I might need this later."

Fix: Delete it. That's what Git history is for. If you need it back, look at the commit log.

🤥 The Liar

A comment that contradicts the code. (e.g., Code says x = 10, Comment says # Set x to 5).

Fix: This happens when you update code but forget to update the comment. Trust the code, delete the comment.

🎯 Key Takeaways

Why vs How

Code explains how. Comments explain why. If the "how" is unclear, refactor the code instead of adding comments.

Docstrings

Use Triple-Quotes (""") for functions and classes. Follow the Google Style Guide for args and returns.

No Zombies

Never commit commented-out code. Use Version Control (Git) to save history.

Standard Tags

Use TODO, FIXME, and HACK ensures your team can find technical debt easily.