How To Identify Indentation Error In Python File The Native Way

Most of us have encountered below error while executing Python script:

IndentationError: unindent does not match any outer indentation level

The problem is also pretty well known. Python prefers spaces over tabs. And your code editor might be configured to add tab for indentation. If you modify a Python script, then you might get a mix of space & tab in the script. Python interpreter would throw above error while executing the code.

There are ways to fix this. You can update your text editor setting to use space instead of tab for indentation.

But were you ever curious which lines were having these issues where tab got inserted? You can keep on executing the Python script & try to figure out the lines one by one from error stack trace. There is a better & faster solution.

You can use tabnanny command. It will give you cleaner log mentioning where the indentation problem is. Once you fix that, rerun again to check for error in other places. It is super fast & validates file in microseconds.

python -m tabnanny yourfile.py
'yourfile.py': Indentation Error: unindent does not match any outer indentation level (<tokenize>, line 90)

Leave a Comment