1

Why does PyCharm fold newline comments at the end of a nested code block into the previous block?

Example (try folding the first "if" block):

def print_me(a):

# newline comment
    if a == 'me':
        dummy_padding = ''
        if not dummy_padding:
            favorite_place = 'zoo'
            print(a)
        else:
            pass

# invisible newline comment
    elif a == 'you':
        dummy_padding = ''
        pass

# visible newline comment
    elif a == 'us':
        dummy_padding = ''
        if not dummy_padding:
            favorite_place = 'movies'
            print(favorite_place)

    # visible indented comment
    elif a == 'them':
        dummy_padding = ''
        pass

    return a

Is there a spec in Python that states that comments inside a function should always be indented? If not, is there some way to adjust settings in PyCharm so that it doesn't disappear newline comments when it folds nested code?

R J
  • 4,473
  • 2
  • 22
  • 29

1 Answers1

1

PEP8 states that

Block comments generally apply to some (or all) code that follows them, and are indented to the same level as that code.

So I think it is the fact that your following comment is not indented that causes that behavior.

If you were to indent the "# invisible newline comment" to the same level as the elif that follows, you'll see that PyCharm no longer folds it into the upper block.

# newline comment
    if a == 'me':
        dummy_padding = ''
        if not dummy_padding:
            favorite_place = 'zoo'
            print(a)
        else:
            pass

    # invisible newline comment  -- now not folded
    elif a == 'you':
Myk Willis
  • 12,306
  • 4
  • 45
  • 62
  • Thanks. Very good to know... though slightly daunting since PEP8 compliance may require me to massively refactor now. Ugh! However PEP8 does not explain entirely why the phenomena occurs only when the code block contains another (nested) code block. Notice how the comment above ```elif a == 'us':``` is still visible even when you fold its previous code block since that block does not contain further nesting. – R J Sep 27 '17 at 15:19