ruk·si

🐍 Python
Comments

Updated at 2017-01-02 23:22

Comments should explain why you do something, not what you do. Code itself should tell what you do.

# bad
# Increment x by one.
x = x + 1

# good
# Compensate for border.
x = x + 1

Prefer block comments over end line comments. But use whichever is more readable.

# ok
x = x + 1 # Compensate for border

All block comments should have blank line before them.

# bad
x = x + 1
# This is a really long comment about why the next few lines of code are
# so important.
y = x * y
u = x + y

# good
a = a + a

# Another comment, but now we focus only on the next line.
# Notice how we left extra space between previous code block and this comment.
z = z + 1

Use docstrings. You should include documentation string (docstring) to important public module, class, method and function. Docstrings come after the declaration. Docstrings should always be defined with double quotes ".

class MyClass:
    """Singleline docstrings can be like this."""
    pass

class MyOtherClass:
    """
    This is MyOtherClass documentation.

    This is how docstrings are used if they go multiline.
    """
    pass

Docstrings should tell what it does using "action words".

# bad
def foo() -> None:
    """
    Calculates something and returns the result.
    """

# good
def bar() -> None:
    """
    Calculate something and return the result.
    """
    pass

Sources