Reinderien
Reinderien

Reputation: 15211

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:

Upvotes: 0

Views: 489

Answers (1)

kareem_emad
kareem_emad

Reputation: 1183

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.

Upvotes: 5

Related Questions