Search code examples
pythoncommentswhitespaceindentation

Why does Python ignore comment indentation?


Apparently, this:

def f():
    pass
# maybe the function is over
    pass  # oh wait, it's not

f()

is valid syntax, whereas this is not:

def f():
    pass
''' maybe the function is over '''
    pass  # oh wait, it's not

f()

That comes as a huge surprise to me. So my questions are:

  • Why? Why does Python not consider the first version to be a syntax error?
  • Is there anything in PEP8 recommending that this not be done?

Solution

  • Yes the first one is valid because it starts with # which defined in the language to be a comment line so it's ignored and its indentation won't end functions or start new ones.

    The latter is different, it's a string evaluated but its value is never used, you could use that to achieve multi line comments but still the interpreter will try to evaluate that string as code, so the indentation of this string matter to the interpreter and it could end scopes.

    for the second one writing something like

    '''comment''''
    

    is as much code to the interpreter as this

    my_var = '''comment'''
    

    But this

    # comment
    

    is ignored and is not code to the interpreter.