I have the following lines in my .vimrc
:
" comment line, selection with Ctrl-N,Ctrl-N
au BufEnter *.py nnoremap <C-N><C-N> mn:s/^\(\s*\)#*\(.*\)/\1#\2/ge<CR>:noh<CR>`n
au BufEnter *.py inoremap <C-N><C-N> <C-O>mn<C-O>:s/^\(\s*\)#*\(.*\)/\1#\2/ge<CR><C-O>:noh<CR><C-O>`n
au BufEnter *.py vnoremap <C-N><C-N> mn:s/^\(\s*\)#*\(.*\)/\1#\2/ge<CR>:noh<CR>gv`n
" uncomment line, selection with Ctrl-N,N
au BufEnter *.py nnoremap <C-N>n mn:s/^\(\s*\)#\([^ ]\)/\1\2/ge<CR>:s/^#$//ge<CR>:noh<CR>`n
au BufEnter *.py inoremap <C-N>n <C-O>mn<C-O>:s/^\(\s*\)#\([^ ]\)/\1\2/ge<CR><C-O>:s/^#$//ge<CR><C-O>:noh<CR><C-O>`n
au BufEnter *.py vnoremap <C-N>n mn:s/^\(\s*\)#\([^ ]\)/\1\2/ge<CR>gv:s/#\n/\r/ge<CR>:noh<CR>gv`n
The shortcuts preserve your cursor position and your comments as long as they start with #
(there is space after #). For example:
# variable x
x = 0
After commenting:
# variable x
#x = 0
After uncomennting:
# variable x
x = 0