5

I have a following python code, which contains both 4 space and 2 space indents.

class Foo(object):
    def __init__(self,
                 flag = False):
      if flag:
        print("hello")
        print("how are you?")

When I auto-indent the python code below with gg=G, the above code becomes

class Model(object):
    def __init__(self,
                 flag = False):
        if flag:
            print("hello")
        print("how are you?")

The code is wrong because the last line should be under the if block. Why is this happening?

2
  • 8
    Autoindenting Python code after the fact is just asking for trouble. Get the indentation correct when you write it instead of making something else guess what's the right indentation; this is a language that gives importance to indentation.
    – muru
    Commented Mar 19, 2016 at 18:44
  • @muru Thank you. I keep this in my mind. Actually, I am modifying a python code written by others and the code uses 2 space indentation. At first I didn't care about mixing of 2 and 4 space indentations but later I wanted to fix this.
    – hitochan
    Commented Mar 21, 2016 at 7:47

1 Answer 1

8

In this case, the auto-indentation seems confused because the def __init__() is indented by four spaces, while the others are indented by two spaces. This is valid Python, but the Vim Python indentation code doesn't seem to be advanced enough to deal with this.

In the Python source there's Tools/scripts/reindent.py, which can fix indentation. When I run it on your example it seems to work as expected.

You can use 'equalprg' to run this with =:

autocmd FileType python setlocal equalprg=/home/martin/src/Python-3.5.1/Tools/scripts/reindent.py

Some distros also package this script with the main Python package. Debian/Ubuntu puts it in the python-examples package.

There are also some other tools, like autopep8. Personally, I don't like autoformatting tools that do too much, as they break the most important style rule of all: think and do something sane.

I looked at the source of reindent.py, and it seems like a well-built script (Carpetsmoker seal of approval™). I believe autopep8 is used quite a lot, so I'll assume that works well enough too.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.