PyCQA / pycodestyle

Simple Python style checker in one Python file
https://pycodestyle.pycqa.org
Other
5.01k stars 755 forks source link

Inconsistent handling of indented comments (E116) #1218

Closed PeterJCLaw closed 8 months ago

PeterJCLaw commented 8 months ago

The following is clean:

if False:
    print()

# comment
    # comment

print()

However if we add a statement after the conditional we get an error on that statement:

if False:
    print()

print('this line creates errors')

# comment
    # comment

print()
demo.py:7:5: E116 unexpected indentation (comment)

I'm not sure which of these is the desired behaviour for the indented comment, however it's somewhat surprising when adding a call before such a comment block that a lint error appears on a comment line which the author hasn't touched.

Both of these spellings seem to be valid Python.

For context, in the original code the commented block was itself a conditional which had been commented out, akin to:

# if False:
    # something()

(yes, I realise that commented-out code is itself undesirable, but it happens)

asottile commented 8 months ago

until adding a statement between the comments and your block the block has not been "ended". inside a block indentation is allowed up to the block's indentation

once you add the statement it is ended before that making it over-indented

an example in line with yours, but perhaps illustrates the point more directly

if True:
    return 1
    # all done!
PeterJCLaw commented 8 months ago

If that's the case, could you explain why the dedented comment in the original is allowed to be followed by an indented comment?

Perhaps more consistent spellings of the rule would be:

asottile commented 8 months ago

I did already:

inside a block indentation is allowed up to the block's indentation

only a statement can end a block in python