Do python single line comments have to obey indentation/whitespace rules?


If I have python code that requires indenting (for, with, function, etc), will a single line comment end potentially the context of the construct if I place it incorrectly? For example, presuming step1, step2 and step3 are functions already defined, will:

def myFunc():
#   step2()

(unintentionally) reduce the scope of myFunc() so that it only contains step1? If I only want to remove step2 from the 3-step sequence, must I place the # at the same level of indentation as the statements within the scope of the construct? All the code I have seen so far suggests this is a requirement, but it might just be a coding habit.

Asked By: omatai



Try it out:

def myFunc():
#   print(2)

which outputs:


So yeah, the answer is “Line comments don’t need to match indentation”. That said, PEP8 really prefers that they do, just for readability.

Answered By: ShadowRanger

Syntax-wise, blank lines are ignored. Blank lines include lines that have any amount of white space followed by a comment.
Indenting a comment the way you show in your example does not change the block of code included in your function.

Convention-wise, PEP8 calls for comments indented to the same indentation as code.

Answered By: Bennett Brown

It doesn’t really matter where you place the #

Either in the first identation level or close to the instruction, everything underneath it is going to be executed.

I suggest you to play with the code below and You’ll figure it out yourself.

a = 1
b = 10
c = 100
d = 1000

if (a == 1):
    result = a+b
#   result = result + c
    result = result + d

Answered By: Matheus Torquato

Python clearly considers comments when checking for indentation errors, which I hope the devs think of as a bug, and fix. I was just running a program that failed to errors, but suddently worked when I deleted some of the comments (and changed nothing else).

Answered By: guest
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.