Python borked indentation

I saw that there are similar names. But my case looks a little weirder. I've used a mixture of PyCharm and Vim somehow (and inside Vim I have tabstop = 4 and shiftwidth = 2) and my Python code seems to be un-fixabl-y borked, indented. I saw for the first time that everything was wrong in Wim, so I aligned everything again; but then when I run it I get an error that there is unexpected indentation even though everything looks perfectly consistent in Vim. Here's an example (what 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've used PythonTidy , I've used reindent

, I've tried :retab

, I've tried manual re-alignment - nothing seems to fix it. Any experiences / advice would be appreciated.

+3


source to share


2 answers


Python treated a tab as 8 spaces by default, if you get indentation you usually want to switch tabs to spaces (or vice versa, but I usually find spaces easier to deal with). So make sure vim displays the tab as 8 spaces ( :set ts=8

) to see what python sees.

To fix tab errors in vim, I usually do the following: I need to see the tabs first, so I turned on the search highlighting ( :set hlsearch

) and did a tab search ( /\t

). Then I go through the areas that need to be canceled. Then I'll try to find the correct vim bookmark width setting for the file ( :set ts=n

and change n

until everything looks good), enable the expand tab ( :set et

), then run the auto-commit of the tabs ( :retab

), When all else fails, reload manually.



If you are using a version control tool, make sure you have files scattered before the changes, and manually check that you have not entered an error due to unintentional indentation level changes. If you are not using version control, save a backup and run diff on the files.

+8


source


Try something like this.

Set the appropriate settings first. Always use 4 spaces. So change it to tabs = 4 spaces.



Convert all spaces to tabs first. And then convert all tabs to spaces. (I am using Geany)

It has worked for me many times.

+2


source







All Articles