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

孤者浪人 提交于 2019-11-28 09:03:04

问题


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?


回答1:


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

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




回答2:


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.



来源:https://stackoverflow.com/questions/4755566/python-im-getting-an-indented-block-error-on-the-last-3-quotes-of-my-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!