Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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():
    step1()
#   step2()
    step3()

(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.

like image 760
omatai Avatar asked Jun 07 '26 08:06

omatai


2 Answers

Syntax-wise, blank lines are ignored. Blank lines include lines that have any amount of white space followed by a comment. https://docs.python.org/2/reference/lexical_analysis.html#blank-lines 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.

like image 75
Bennett Brown Avatar answered Jun 08 '26 20:06

Bennett Brown


Try it out:

def myFunc():
    print(1)
#   print(2)
    print(3)
myFunc()

which outputs:

1
3

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

like image 22
ShadowRanger Avatar answered Jun 08 '26 22:06

ShadowRanger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!