Editing Python code in Vim.

Python is relied on indentation, and if you edit python code in Vim, you may found it will mess up your indentation. Here is a simple way to fix it.

Open your file in Vim you will see something like this:

1
2
3
4
def upload(request):
c = {}
c.update(csrf(request))
print c

and enter Vim command

1
:set list

to see all white spaces. If you see something like this:

1
2
3
4
def upload(request):$
^Ic = {}$
^Ic.update(csrf(request))$
print c$

You know you have inconsistent indentation. “^I” means tab, but “print c” statement is indented by space.

How to fix this? Easy.

  1. Edit your .vimrc file to have following:

    1
    2
    3
    4
    5
    6
    set smartindent
    set expandtab
    set shiftwidth=4
    set tabstop=4
    set softtabstop=4
    set smarttab
  2. For the files having indentation issue, run Vim command to fix them:

    1
    :retab
  3. Now check the file again using “:set list”, and you will see all tabs are gone. They are places by spaces.