How to catch IndentationError [duplicate]

泄露秘密 提交于 2019-11-29 04:01:50

Yes, this can be done. However, the function under test would have to live in a different module:

# test1.py
try:
    import test2
except IndentationError as ex:
    print ex

# test2.py
def f():
    pass
        pass # error

When run, this correctly catches the exception. It is worth nothing that the checking is done on the entire module at once; I am not sure if there's a way to make it more fine-grained.

IndentationError is raised when the module is compiled. You can catch it when importing a module, since the module will be compiled on first import. You can't catch it in the same module that contains the try/except, because with the IndentationError, Python won't be able to finish compiling the module, and no code in the module will be run.

You could use a tool such as pylint, which will analyse your module and report bad indentation, as well as many other errors.

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