Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Python Dictionary

  1. Home
  2. Python Dictionary
  3. Comment (#) / Docstring (""")

Comment (#) / Docstring (""")

In Python, single-line comments are written with #, and multi-line docstrings are written with triple quotes (""" or '''). A docstring is a documentation comment attached to a function, class, or module, and is automatically read by the help() function and various documentation generation tools.

Syntax

# Single-line comment: the convention is to put one space after #.

# Triple quotes written immediately after a function/class/module body are docstrings.
def func_name(arg):
    """Written in this form when it fits on one line."""
    pass

def func_name(arg):
    """Summary line for a multi-line docstring.

    Write detailed description here. Insert one blank line between summary and detail.
    """
    pass

# Google style
def func_name(arg1, arg2):
    """Write summary in one line.

    Args:
        arg1 (type): Description.
        arg2 (type): Description.

    Returns:
        type: Description of return value.

    Raises:
        ExceptionClass: Description of when it occurs.
    """
    pass

# NumPy style
def func_name(arg1, arg2):
    """Write summary in one line.

    Parameters
    ----------
    arg1 : type
        Description.
    arg2 : type
        Description.

    Returns
    -------
    type
        Description of return value.
    """
    pass

Comment / Docstring Reference

SyntaxNotes
# textSingle-line comment. Everything after # to the end of the line is a comment. There are two types: inline comments written after code and block comments written above code.
"""text"""Docstring using triple double quotes. Written at the beginning of the body of a function, class, or module.
'''text'''Docstring using triple single quotes. Functions the same as """. Style guides generally prefer """.
help(object)Displays the docstring attached to an object in the console. Used for documentation lookup in interactive environments.
object.__doc__Attribute that directly references the docstring string. If None, no docstring has been written.

Sample Code

Basic writing styles and placement of single-line comments.

comment_style.py
# Block comment: written above code to explain the next line's processing.
# Multiple lines can be written by continuing with #.

# Define power level data for Dragon Ball fighters.
fighters = {
    "Son Goku": 9000,
    "Vegeta": 8500,
    "Frieza": 120000,
}

# Extract fighters with power level over 10000.
powerful = {name: power for name, power in fighters.items() if power > 10000}

print("Elite fighters:", powerful)  # Inline comment: brief note written at end of line.

# Inline comments should be at least 2 spaces from the code.
base_power = 5000      # base power level
multiplier = 50        # Super Saiyan multiplier
final_power = base_power * multiplier  # power after transformation
print("After transformation:", final_power)
python3 comment_style.py
Elite fighters: {'Frieza': 120000}
After transformation: 250000

Attaching a docstring to a function and checking the content with help() and __doc__.

docstring_basic.py
def get_power_level(name, base, multiplier=1):
    """Calculates and returns a fighter's final power level.

    Returns base power multiplied by the multiplier.
    Omitting multiplier gives the power level without transformation.

    Args:
        name (str): Fighter's name.
        base (int): Base power level.
        multiplier (int): Transformation multiplier. Default is 1 (no transformation).

    Returns:
        dict: Dictionary with keys name (name) and power (final power level).
    """
    return {"name": name, "power": base * multiplier}

# The docstring can be accessed directly via the __doc__ attribute.
print(get_power_level.__doc__)

# help() displays it in a more readable format.
# help(get_power_level)

result = get_power_level("Son Goku", 9000, 50)
print(result["name"], "power level:", result["power"])
python3 docstring_basic.py
Calculates and returns a fighter's final power level.

    Returns base power multiplied by the multiplier.
    Omitting multiplier gives the power level without transformation.

    Args:
        name (str): Fighter's name.
        base (int): Base power level.
        multiplier (int): Transformation multiplier. Default is 1 (no transformation).

    Returns:
        dict: Dictionary with keys name (name) and power (final power level).

Son Goku power level: 450000

Comparing the three docstring formats: Google, NumPy, and reStructuredText.

docstring_styles.py
# Google style: readable and simple. Widely used in Google and TensorFlow projects.
def charge_ki_google(fighter, amount, max_ki=100):
    """Charges a fighter's ki (Google style).

    Args:
        fighter (str): Name of the fighter to charge.
        amount (int): Amount of ki to charge.
        max_ki (int): Maximum ki limit. Default is 100.

    Returns:
        int: Ki value after charging. Excess is cut off at the limit.

    Raises:
        ValueError: Raised when amount is 0 or less.
    """
    if amount <= 0:
        raise ValueError("Charge amount must be 1 or more")
    return min(amount, max_ki)


# NumPy style: used in scientific and numerical computing libraries.
def charge_ki_numpy(fighter, amount, max_ki=100):
    """Charges a fighter's ki (NumPy style).

    Parameters
    ----------
    fighter : str
        Name of the fighter to charge.
    amount : int
        Amount of ki to charge.
    max_ki : int, optional
        Maximum ki limit. Default is 100.

    Returns
    -------
    int
        Ki value after charging. Excess is cut off at the limit.

    Raises
    ------
    ValueError
        Raised when amount is 0 or less.
    """
    if amount <= 0:
        raise ValueError("Charge amount must be 1 or more")
    return min(amount, max_ki)


# reStructuredText style: commonly used with Sphinx documentation generation.
def charge_ki_rst(fighter, amount, max_ki=100):
    """Charges a fighter's ki (reStructuredText style).

    :param fighter: Name of the fighter to charge.
    :type fighter: str
    :param amount: Amount of ki to charge.
    :type amount: int
    :param max_ki: Maximum ki limit. Default is 100.
    :type max_ki: int
    :returns: Ki value after charging. Excess is cut off at the limit.
    :rtype: int
    :raises ValueError: Raised when amount is 0 or less.
    """
    if amount <= 0:
        raise ValueError("Charge amount must be 1 or more")
    return min(amount, max_ki)


print(charge_ki_google("Son Goku", 80))   # 80
print(charge_ki_numpy("Vegeta", 150))     # 100 (cut at limit)
print(charge_ki_rst("Piccolo", 60))       # 60
python3 docstring_styles.py
80
100
60

Writing docstrings for classes and at module level.

class_docstring.py
"""A module for managing Dragon Ball fighters.

This module provides the Saiyan class.
It handles fighter information and transformation management.
"""


class Saiyan:
    """A class representing a Saiyan.

    Manages the name, power level, and transformation state of a Saiyan.

    Attributes:
        name (str): Saiyan's name.
        base_power (int): Base power level before transformation.
        transformation (str): Current transformation state.
    """

    def __init__(self, name, base_power):
        """Initializes the Saiyan.

        Args:
            name (str): Saiyan's name.
            base_power (int): Base power level.
        """
        self.name = name
        self.base_power = base_power
        self.transformation = "Normal"

    def transform(self, level):
        """Transforms into a Super Saiyan.

        Args:
            level (int): Transformation level (1-3).

        Returns:
            str: Status string after transformation.
        """
        multipliers = {1: 50, 2: 2500, 3: 4000}
        multiplier = multipliers.get(level, 1)
        power = self.base_power * multiplier
        self.transformation = "Super Saiyan " + str(level)
        return self.name + " [" + self.transformation + "] Power: " + str(power)


# Check docstrings for class and method.
print(Saiyan.__doc__)
print("---")

goku = Saiyan("Son Goku", 9000)
print(goku.transform(1))
print(goku.transform(3))
python3 class_docstring.py
A class representing a Saiyan.

    Manages the name, power level, and transformation state of a Saiyan.

    Attributes:
        name (str): Saiyan's name.
        base_power (int): Base power level before transformation.
        transformation (str): Current transformation state.

---
Son Goku [Super Saiyan 1] Power: 450000
Son Goku [Super Saiyan 3] Power: 36000000

Comparing type hints and docstrings. When type hints are present, the type descriptions in docstrings can be omitted.

type_hints_vs_docstring.py
# Without type hints: write type info in docstring (Google style).
def fuse(fighter1, fighter2, method):
    """Fuses two fighters together.

    Args:
        fighter1 (str): Name of the first fighter to fuse.
        fighter2 (str): Name of the second fighter to fuse.
        method (str): Fusion method ("Fusion" or "Potara").

    Returns:
        str: Name of the fused fighter.
    """
    return fighter1[:2] + fighter2[1:] + " (" + method + ")"


# With type hints: type info can be omitted from docstring.
def fuse_typed(fighter1: str, fighter2: str, method: str) -> str:
    """Fuses two fighters together.

    Args:
        fighter1: Name of the first fighter to fuse.
        fighter2: Name of the second fighter to fuse.
        method: Fusion method ("Fusion" or "Potara").

    Returns:
        Name of the fused fighter.
    """
    return fighter1[:2] + fighter2[1:] + " (" + method + ")"


print(fuse("Son Goku", "Vegeta", "Fusion"))
print(fuse_typed("Son Goku", "Vegeta", "Potara"))
python3 type_hints_vs_docstring.py
Son Geta (Fusion)
Son Geta (Potara)

Common Mistakes

Common Mistake 1: Docstring placed in the wrong position

A docstring must be written at the very beginning of the body of a function, class, or module. A string written anywhere else is not recognized as a docstring, and the __doc__ attribute becomes None.

ng_docstring_position.py
# NG: the docstring is not at the beginning of the function body.
def get_power_level(name, base):
    result = base * 50
    """This string is not a docstring — it is just a string literal."""
    return result

print(get_power_level.__doc__)
python3 ng_docstring_position.py
None
ok_docstring_position.py
# OK: write the docstring at the very beginning of the function body.
def get_power_level(name, base):
    """Calculates and returns a fighter's power level after transformation."""
    result = base * 50
    return result

print(get_power_level.__doc__)
python3 ok_docstring_position.py
Calculates and returns a fighter's power level after transformation.

Common Mistake 2: Forgetting to close triple quotes

Forgetting to close triple quotes causes a SyntaxError. This is a common mistake when writing multi-line docstrings.

ng_unclosed_docstring.py
# NG: triple quotes are not closed.
def fuse(fighter1, fighter2):
    """Fuses two fighters together.

    Args:
        fighter1 (str): Name of the first fighter to fuse.
        fighter2 (str): Name of the second fighter to fuse.

    return fighter1[:2] + fighter2[1:]
python3 ng_unclosed_docstring.py
  File "ng_unclosed_docstring.py", line 9
    return fighter1[:2] + fighter2[1:]
                                      ^
SyntaxError: EOF while scanning triple-quoted string literal
ok_unclosed_docstring.py
# OK: properly close the triple quotes.
def fuse(fighter1, fighter2):
    """Fuses two fighters together.

    Args:
        fighter1 (str): Name of the first fighter to fuse.
        fighter2 (str): Name of the second fighter to fuse.
    """
    return fighter1[:2] + fighter2[1:]

print(fuse("Son Goku", "Vegeta"))
python3 ok_unclosed_docstring.py
Son Geta

Common Mistake 3: Type hint and docstring type are inconsistent

When type hints and docstring type descriptions contradict each other, they cause confusion for static analysis tools and readers. When adding or changing type hints, update the docstring type descriptions at the same time.

ng_type_mismatch.py
# NG: type hint says int, but docstring says str.
def get_rank(score: int) -> str:
    """Returns a rank from a score.

    Args:
        score (str): Score (string).  # Contradicts type hint.

    Returns:
        int: Rank string.             # Contradicts type hint.
    """
    return "S" if score >= 90 else "A"
python3 ng_type_mismatch.py
ok_type_mismatch.py
# OK: align the type hints and docstring type descriptions.
# When type hints are present, the type descriptions can also be omitted from docstrings.
def get_rank(score: int) -> str:
    """Returns a rank from a score.

    Args:
        score: Score (integer from 0 to 100).

    Returns:
        A string representing the rank (one of "S", "A", "B", "C").
    """
    if score >= 90:
        return "S"
    elif score >= 80:
        return "A"
    elif score >= 70:
        return "B"
    return "C"

print(get_rank(85))
python3 ok_type_mismatch.py
A

Notes

Comments are written with #. A comment that explains "why" rather than "what the code does" is more informative. Comments on self-evident code can be redundant. Inline comments should be at least 2 spaces from the code per PEP 8 style.

A docstring is a special string literal placed at the beginning of a module, class, or function, accessible via the __doc__ attribute. The help() function formats and displays this attribute. Sphinx and other documentation generation tools also read docstrings automatically, so writing docstrings when building a library is common practice.

Any of the three formats — Google, NumPy, or reStructuredText — can be used, but consistency within a project is important. When using type hints (-> or : type for arguments), duplicate type descriptions in docstrings can be omitted. Type hints and docstrings complement each other: type hints convey "what type", while docstrings convey "what it means". For type hint details, also see def / Function Definition.

If you find any errors or copyright issues, please .