n1000
n1000

Reputation: 5314

Indented comments in Python

I was wondering if this is wrong or considered bad practice or anything:

def my_fuction():
    """This function does something."""
    pass

my_function()  # Yes I could write a comment here
    # But sometimes I need more space and make it clear
    # that a comment belongs to a certain part of my code

As you can see I indented my comment below the function call, in order to leave specific instructions / comments for this particular call. I indent it to make it clear that this comment belongs to this call of the code. PyCharm warns me that this is an unexpected indentation according to PEP8, but the code will execute.

Is this bad style and is there a better practice to make this kind of comment?

Upvotes: 1

Views: 2454

Answers (2)

M András
M András

Reputation: 169

You may also use editor-fold function to keep a part of code together and expand, like

# <editor-fold desc="Name of this block of code">
Here is my code
Here is also my code
# </editor-fold>

Upvotes: 0

Anand S Kumar
Anand S Kumar

Reputation: 91009

I believe this falls under Block Comments part of PEP0008 , which advices -

Block comments generally apply to some (or all) code that follows them, and are indented to the same level as that code. Each line of a block comment starts with a # and a single space (unless it is indented text inside the comment).

(Emphasis mine)

I believe the correct indentation for the comments would be -

# Yes I could write a comment here
# But sometimes I need more space and make it clear
# that a comment belongs to a certain part of my code
my_function()

And to me this looks better than having the first comment on the same line as the function call, and the rest below it.

Upvotes: 4

Related Questions