AI Generate code comments instantly

Python code commenting guide

Master Python code commenting with our comprehensive guide. Learn best practices, conventions, and techniques for clear comments.

Best practices

Python commenting conventions

Python uses # for single-line comments and """...""" for multi-line comments. Following Python commenting conventions ensures your code is readable and maintainable.

Python comment syntax

  • Single-line: #
  • Multi-line: """ ... """
  • Documentation: Triple-quoted strings with various formats (Google, NumPy, Sphinx)

Single-line comments

Use single-line comments for brief explanations, clarifications, or notes about specific lines of code. Keep them concise and relevant to the immediate context.

// Good: Explains why, not what

// Calculate tax before shipping to comply with local regulations

const totalWithTax = subtotal * taxRate;

Multi-line comments

Use multi-line comments for longer explanations, complex algorithms, or when documenting important business logic that requires detailed context.

/*

* Complex algorithm explanation:

* 1. First step description

* 2. Second step description

*/

Documentation comments

Use structured documentation comments for functions, classes, and modules. Include parameters, return values, and usage examples when appropriate.

/** Description of function

* @param {type} name - parameter description

* @returns {type} return value description

*/

TODO and FIXME tags

Use standardized tags like TODO, FIXME, HACK, or NOTE to mark items that need attention. Include your initials and a date for tracking.

// TODO(username): Add error handling for edge case

// FIXME: Memory leak when processing large files

// NOTE: This approach was chosen over X because Y

Avoid these commenting mistakes

  • Stating the obvious: Don't comment what the code clearly shows (e.g., "increment counter" above `i++`)
  • Outdated comments: Remove or update comments when code changes
  • Commented-out code: Use version control instead of leaving old code
  • Excessive comments: If you need many comments, consider refactoring for clarity

Let DocuWriter.ai generate comments for your Python code automatically

Open markdown editor

Want to learn more? Check out our guide on technical documentation best practices

FAQ

Frequently asked questions

When should I add comments to my code?

Add comments for complex logic, non-obvious decisions, important algorithms, and to explain the 'why' behind your code choices.

What's the difference between good and bad comments?

Good comments explain intent and reasoning, while bad comments state the obvious or become outdated. Focus on 'why' not 'what'.

How detailed should my code comments be?

Comments should be concise but informative. Provide enough context for others to understand without being verbose or redundant.

Related resources

Get started

Start documenting and organizing your codebase