How to fix Python indentation


I have some Python code that have inconsistent indentation. There is a lot of mixture of tabs and spaces to make the matter even worse, and even space indentation is not preserved.

The code works as expected, but it's difficult to maintain.

How can I fix the indentation (like HTML Tidy, but for Python) without breaking the code?

8/11/2018 11:30:55 PM

Accepted Answer

Use the script that you find in the Tools/scripts/ directory of your Python installation:

Change Python (.py) files to use 4-space indents and no hard tab characters. Also trim excess spaces and tabs from ends of lines, and remove empty lines at the end of files. Also ensure the last line ends with a newline.

Have a look at that script for detailed usage instructions.

6/21/2009 7:29:15 PM

If you're using Vim, see :h retab.

                                                        *:ret* *:retab*
:[range]ret[ab][!] [new_tabstop]
                        Replace all sequences of white-space containing a
                        <Tab> with new strings of white-space using the new
                        tabstop value given.  If you do not specify a new
                        tabstop size or it is zero, Vim uses the current value
                        of 'tabstop'.
                        The current value of 'tabstop' is always used to
                        compute the width of existing tabs.
                        With !, Vim also replaces strings of only normal
                        spaces with tabs where appropriate.
                        With 'expandtab' on, Vim replaces all tabs with the
                        appropriate number of spaces.
                        This command sets 'tabstop' to the new value given,
                        and if performed on the whole file, which is default,
                        should not make any visible change.
                        Careful: This command modifies any <Tab> characters
                        inside of strings in a C program.  Use "\t" to avoid
                        this (that's a good habit anyway).
                        ":retab!" may also change a sequence of spaces by
                        <Tab> characters, which can mess up a printf().
                        {not in Vi}
                        Not available when |+ex_extra| feature was disabled at
                        compile time.

For example, if you simply type


all your tabs will be expanded into spaces.

You may want to

:se et  " shorthand for :set expandtab

to make sure that any new lines will not use literal tabs.

If you're not using Vim,

perl -i.bak -pe "s/\t/' 'x(8-pos()%8)/eg"

will replace tabs with spaces, assuming tab stops every 8 characters, in (with the original going to, just in case). Replace the 8s with 4s if your tab stops are every 4 spaces instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow