Ambidextrous
Ambidextrous

Reputation: 820

Python indentation borked

I saw that there are similar titles to this. But my case seems a little weirder. I somehow used a mixture of PyCharm and Vim (and within Vim I have tabstop=4 and shiftwidth=2), and my Python code seems un-fixabl-y borked, indentation-wise. I first saw that in Vim everything was mis-aligned, so I re-aligned everything; but then when I run it I get an error that there's an unexpected indentation, even though in Vim everything seems perfectly aligned. Here's an example (this is how it looks like in Vim):

for f in files:
    for line in f:
        items = line.strip().split()
        items = items[2:]
        items = ' '.join(items).split(', ')

When I run it, I get:

File "getEsSynonymLSAVectors.py", line 136
    items = items[2:]
    ^
IndentationError: unexpected indent

I used PythonTidy, I used reindent, I tried :retab, I tried manual re-aligning - nothing seems to fix this. Any experiences/ advice will be appreciated.

Upvotes: 4

Views: 5763

Answers (2)

Lie Ryan
Lie Ryan

Reputation: 64923

Python treated a tab as 8 spaces by default, if you get indentation borked, you'll generally want to switch the tabs to spaces (or vice versa, but I generally find that spaces are easier to deal with). So make sure to set vim to show tab as 8 spaces wide (:set ts=8), to see what python sees.

To fix tab errors in vim, I usually do the following, first I need to be able to see the tabs, so I enabled highlight search (:set hlsearch) and search for tabs (/\t). Then I eyeball the areas that needs to be retabbed. Next, I try to find the right vim tab width setting for the file (:set ts=n and vary n until everything looks good), enable expand tab (:set et), then run the automatic tab fixing (:retab). When all else fail, retab manually.

If you're using version control, make sure to diff with the files before the changes and manually check that you didn't introduce a bug because of unintentional changes in the indentation level. If you don't use version control, keep a backup and run diff on the files.

Upvotes: 10

Froyo
Froyo

Reputation: 18487

Try something like this.

First set appropriate settings. Always use 4 spaces. So change it to tabs = 4 spaces.

First convert all spaces to tabs. And then convert all tabs to spaces. (I use Geany)

It has worked for me before many times.

Upvotes: 2

Related Questions