306

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?


Some editor-specific advice:

3
  • can you review this link and provide your inputs on how to use reindent.py module--stackoverflow.com/questions/12132481/installing-reindent-python/… Commented Aug 26, 2012 at 18:05
  • As mentioned below by @andy-hayden look at this related question - basically autopep8 provides indentation and much much more: stackoverflow.com/questions/14328406/… Commented Dec 1, 2014 at 9:41
  • 3
    This is an insanely useful question, I find myself needing to do this quite often. It's not about "recommending a tool" so much as "how to do it". Commented Feb 22, 2016 at 6:20

15 Answers 15

302

Use the reindent.py 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.


NOTE: If your linux distro does not have reindent installed by default with Python:

Many linux distros do not have reindent installed by default with python --> one easy way to get reindent is to do pip install reindent.

p.s. An alternative to pip is to use your distros package manager (i.e. apt-get, yum, dnf) but then you need to figure out what package has the command line tool because each distro has the tool in a different package.

Sign up to request clarification or add additional context in comments.

18 Comments

Unfortunately, it's not part of the normal Python install on Debian and Ubuntu; it's split out into the python-examples package.
Excellent! So all that Debian and Ubuntu users need do is to apt-get that package. Alternatively, the script is also at svn.python.org/view/python/trunk/Tools/scripts/… .
@Shay Erlichmen: Try "python -tt yourscript.py"
Fedora/RedHat/CentOS users should install the "python-tools" package.
Just to add to ephemient's comment: once python-examples is installed, you'll find reindent in /usr/share/doc/pythonX.X/examples/Tools/scripts/reindent.py.
|
70

I would reach for autopep8 to do this:

$ # see what changes it would make
$ autopep8 path/to/file.py --select=E101,E121 --diff

$ # make these changes
$ autopep8 path/to/file.py --select=E101,E121 --in-place

Note: E101 and E121 are pep8 indentation (I think you can simply pass --select=E1 to fix all indentation related issues - those starting with E1).

You can apply this to your entire project using recursive flag:

$ autopep8 package_dir --recursive --select=E101,E121 --in-place

See also Tool to convert Python code to be PEP8 compliant.

3 Comments

this is awesome... I've been looking for a tool like ruby's rubocop for python
autopep8 fails if the syntax is incorrect. you can confirm that using python -tt <file.py>
doesnt work, left mix of tabs and spaces for me
63

autopep8 -i script.py

You can use autopep8

autopep8 automagically formats Python code to conform to the PEP 8 nullstyle guide. It uses the pep8 utility to determine what parts of the nullcode needs to be formatted. autopep8 is capable of fixing most of the nullformatting issues that can be reported by pep8.

pip install autopep8
autopep8 script.py    # print only
autopep8 -i script.py # write file

3 Comments

i have just one line code with "import os" and 4 spaces before it but its not indenting that one ....any reason why
@pkm 4 spaces (or any indention that is a multiple of 4) is part of the PEP8
doesnt work on mine. just leaves tabs and spaces as is
62

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

:ret

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" file.py

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

Comments

18

Using Vim, it shouldn't be more involved than hitting Esc, and then typing...

:%s/\t/    /g

...on the file you want to change. That will convert all tabs to four spaces. If you have inconsistent spacing as well, then that will be more difficult.

3 Comments

can you track down the original coder(s) and apply enhanced interrogation techniques? There is nothing worse than inconsistently indented code.
@Ben The inconsistent indention is the least of our problems from that guy :)
What happens if tabs are in other places, such as in a string literal?
11

There is also PythonTidy (since you said you like HTML Tidy).

It can do a lot more than just clean up tabs though. If you like that type of thing, it's worth a look.

Comments

8

On most UNIX-like systems, you can also run:

expand -t4 oldfilename.py > newfilename.py

from the command line, changing the number if you want to replace tabs with a number of spaces other than 4. You can easily write a shell script to do this with a bunch of files at once, retaining the original file names.

2 Comments

Note that using the same file doesn't work and leaves you with an empty file, but this answer actually works and I use it when I need to convert my tabs to spaces. Could anyone explain the downvote? I'll up it +1.
Is there any possible way to recover the overwritten file? Just used the above method and my day's worth of code vanished facepalm. Thanks
6

The reindent script did not work for me, due to some missing module. Anyway, I found this sed command which does the job perfect for me:

sed -r 's/^([  ]*)([^ ])/\1\1\2/' file.py

1 Comment

Illegal options -r.
5

If you're lazy (like me), you can also download a trial version of Wingware Python IDE, which has an auto-fix tool for messed up indentation. It works pretty well. http://www.wingware.com/

Comments

3

Try Emacs. It has good support for indentation needed in Python. Please check this link http://python.about.com/b/2007/09/24/emacs-tips-for-python-programmers.htm

3 Comments

python-mode is nice for writing Python, but nothing at the link describes how to fix indentation in an existing file.
M-x untabify will turn tabs into space in emacs
The link is (effectively) broken. It redirects to a page with the title "C Programming Language for Beginners " (!).
2

Try IDLE, and use Alt + X to find indentation.

Comments

0

I have a simple solution for this problem. You can first type ":retab" and then ":retab!", then everything would be fine

1 Comment

Type ":retab" in what context. In Vim?
0

In case of trying to find tool to make your 2-space indented python script to a tab indented version, just use this online tool:

https://www.tutorialspoint.com/online_python_formatter.htm

Comments

0

There is also a Google awesome project called YAPF

It can automatically reformat the whole project or check if the project has correct indentation/format. I used that in a commercial project and I recommend that.

Comments

0

In my case, the indentation issue was caused by Vim's auto-indent feature.

Issue

When copying from Notepad (Windows)

for item in week_data:
    ts = int(item["timestamp"])
    dt = datetime.fromtimestamp(ts, tz=my_zone)

And pasting into Vim on Ubuntu Linux (via PuTTY terminal):

for item in week_data:
        ts = int(item["timestamp"])
            dt = datetime.fromtimestamp(ts, tz=my_zone)

Solution

In vim, run:

:set paste

The :set paste disables automatic indenting, line wrapping, and other automatic formatting features during paste. It tells vim: "I am pasting content, don’t mess with indentation or formatting, just insert it exactly as-is."

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.