11

First of all - I don't have a problem with bad-indentated code and I have an idea of how does this exception works like.

I ask, if there is any way to catch IndentationError in code with a try/except block? For example, let's say I'm writing a test for a function written by someone else. I want to run it in try/except block and handle all warning he/she could make. I know, that it's not a best example, but the first one coming to my mind. Please, don't focus on an example, but rather on problem.

Let's look at the code:

try:
    f()
except IndentationError:
    print "Error"

print "Finished"

The function:

def f():
  print "External function"

And the result is:

External function
Finished

And that's something, I'm ready to understand, becouse indentation in external function was consistant.

But when the function look like that:

def f():
  print "External function"
     print "with bad indentation"

The exception is unhandled:

    print "with bad indentation"
    ^
IndentationError: unexpected indent

Is there any way to achieve it? I guess that's the matter of compiling, and as far I don't see any possibility to catch. Does the except IndentationError make any sense?

Gandi
  • 3,522
  • 2
  • 21
  • 31

3 Answers3

15

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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
9

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.

kindall
  • 178,883
  • 35
  • 278
  • 309
5

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

Alasdair
  • 298,606
  • 55
  • 578
  • 516