Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: I'm getting an 'indented block' error on the last 3 quotes (""") of my comments under functions. What's up?

Super odd, no? The offending code:

def main():
"""
main function
"""
    # Argument handling

    args = sys.argv[1:]
    if not args:
        print "usage is: ...

The third quote is where I get the usual indentation error:

>>>Import someScript
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "someScript.py", line 24
    """
      ^

If I delete the comments (obviously I don't want to) then the next function to be defined gets the same error, at the same location of its comments. If I delete all comments from functions, the error goes away.

I don't understand! Why expect an indent there? I'm writing in Komodo Edit partially because it doesn't let you mix spaces and tabs, but just to be sure I did a search and, sure enough, there are no friggin tabs. Not that it would make sense anyway if there were.

What gives, gurus?

like image 979
WaxProlix Avatar asked Dec 01 '22 09:12

WaxProlix


2 Answers

You need to indent the docstring along with the block for your function.

Every colon (:) must be immediately followed by an indented block.

like image 74
Rafe Kettler Avatar answered Dec 05 '22 19:12

Rafe Kettler


As said, the docstring isn't indented. It would be nicer to get the error on the first line of the string, but that's not the way the lexer currently works. Instead, it takes a whole token at a time – remember triple-quoted strings imply line spanning – then emits an error if it's misindented. That symbol is the entire triple-quoted string, which happens to end on a different line. Compare:

>>> def f():
... """one line"""
  File "<stdin>", line 2
    """one line"""
                 ^
IndentationError: expected an indented block
>>> def f():
... foo()
  File "<stdin>", line 2
    foo()
      ^
IndentationError: expected an indented block
>>> def f():
... return 42
  File "<stdin>", line 2
    return 42
         ^
IndentationError: expected an indented block

Note how it points, in the second example, to the end of "foo", the first symbol in that misindented statement: this is the same as pointing to the end of your docstring.

like image 35
Fred Nurk Avatar answered Dec 05 '22 17:12

Fred Nurk