Python indentation borked - python

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.

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.

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.

Related

Pycharm sometimes does not indent the proper amount

I have tabs and indents|indent set to 2:
However the actual indentation is coming up as 3 - specifically inside the groupby function - which I have unindented and re-indented several times to be sure the behavior were consistent[-ly incorrect]:
Note that I have also tried the Auto-indent (Option-Command-I) - it also indents stuff to 3 spaces instead of 2. Bit strange..
Any thoughts?
The first thing you might want to check is to make sure you don't have Detect and use existing file indents for editing enabled in Settings/Preferences | Editor | Code Style. If you do, when you auto-indent, it might apply the wrong settings.
You can try to fix incorrectly formatted code by using Option+Command+L (Mac) / Control+Alt+L (PC), which is the Reformat Code option. That should fix the code and then auto-indent should work correctly.
This is most annoying problem in pycharm. Here is simple answer to this :
Just follow the path :
GO to Edit->Convert Indents->To Spaces
This will actually insert space instead of tabular character in empty space when you default enter for next line.

IndentationError when adding new line inside code [duplicate]

I am new to atom, so I opened my existing code using atom and modified few lines, then when I tried running the code with python, I get the following error:
IndentationError: unindent does not match any outer indentation level
I realized that Atom editor does indent my code differently to what I had. refer to the attached picture below showing the different indentation styles. line 1300 is the old indentation and 1301 is the one created by Atom
How can I fix this without modifying my 1000+ line code and so that atom uses the same style of indentation.
You have mixed tabs and spaces in your code. You should use spaces, always.
You can use this plugin to quickly fix your code, and please, use only spaces and 4 spaces for each level of indentation.
I had a similar error while using Atom,I fixed it using below steps.
Install notepad++
Open the file which has issue(one you have mentioned in question) in notepad++.
Go to View > Show Symbol > Show All Characters,this will show up where the tabs and where spaces are available.
Go to Edit->Blank Operations->TAB to Space to replace all tabs with spaces.
Go to View > Show Symbol > Show All Characters,confirm all tabs are replaced with spaces.
Save file and reload page,this will fix this issue.
In the newer versions of Atom, just go to settings > Editor; then scroll down to tab length and change it to 4; then change tab type to soft. This will make the tab key insert 4 spaces instead of a tab character moving forward. You still have to update your previous code using one of the above methods.
In the Atom Text Editor's top menu bar :
click the Packages tab
click Whitespace in the dropdown menu
Choose your preferred option (ie: Convert Spaces to Tabs)
And that will fix this pesky problem.

How to let pyflakes ignore some errors?

I am using SublimePythonIDE which is using pyflakes.
There are some errors that I would like it to ignore like:
(E501) line too long
(E101) indentation contains mixed spaces and tabs
What is the easiest way to do that?
Configuring a plugin in Sublime almost always uses the same procedure: Click on Preferences -> Package Settings -> Plugin Name -> Settings-Default to open the (surprise surprise) default settings. This file generally contains all the possible settings for the plugin, usually along with comments explaining what each one does. This file cannot be modified, so to customize any settings you open Preferences -> Package Settings -> Plugin Name -> Settings-User. I usually copy the entire contents of the default settings into the user file, then customize as desired, then save and close.
In the case of this particular plugin, while it does use pyflakes (as advertised), it also makes use of pep8, a style checker that makes use of the very same PEP-8 official Python style guide I mentioned in the comments. This knowledge is useful because pyflakes does not make use of specific error codes, while pep8 does.
So, upon examination of the plugin's settings file, we find a "pep8_ignore" option as well as a "pyflakes_ignore" one. Since the error codes are coming from pep8, we'll use that setting:
"pep8_ignore": [ "E501", // line too long
"E303", // too many blank lines (3)
"E402" // module level import not at top of file
]
Please note that codes E121, E123, E126, E133, E226, E241, E242, and E704 are ignored by default because they are not rules unanimously accepted, and PEP 8 does not enforce them.
Regarding long lines:
Sometimes, long lines are unavoidable. PEP-8's recommendation of 79-character lines is based in ancient history when terminal monitors only had 80 character-wide screens, but it continues to this day for several reasons: it's backwards-compatible with old code, some equipment is still being used with those limitations, it looks good, it makes it easier on wider displays to have multiple files open side-by-side, and it is readable (something that you should always be keeping in mind when coding). If you prefer to have a 90- or 100-character limit, that's fine (if your team/project agrees with it), but use it consistently, and be aware that others may use different values. If you'd like to set pep8 to a larger value than its default of 80, just modify the "pep8_max_line_length" setting.
There are many ways to either decrease the character count of lines to stay within the limit, or split long lines into multiple shorter ones. In the case of your example in the comments:
flag, message = FacebookUserController.AddFBUserToDB(iOSUserId, fburl, fbsecret, code)
you can do a couple of things:
# shorten the module/class name
fbuc = FacebookUserController
# or
import FacebookUserController as fbuc
flag, message = fbuc.AddFBUserToDB(iOSUserId, fburl, fbsecret, code)
# or eliminate it all together
from FacebookUserController import AddFBUserToDB
flag, message = AddFBUserToDB(iOSUserId, fburl, fbsecret, code)
# split the function's arguments onto separate lines
flag, message = FacebookUserController.AddFBUserToDB(iOSUserId,
fburl,
fbsecret,
code)
# There are multiple ways of doing this, just make sure the subsequent
# line(s) are indented. You don't need to escape newlines inside of
# braces, brackets, and parentheses, but you do need to outside of them.
As others suggest, possibly heed the warnings. But in those cases where you can't, you can add # NOQA to the end offending lines. Note the two spaces before the # as that too is a style thing that will be complained about.
And if pyflakes is wrapped in flake8 that allows ignoring by specific errors.
For example in a file in the project put or add to tox.ini:
[flake8]
exclude = .tox,./build
filename = *.py
ignore = E501,E101
This is possibly a duplicate with How do I get Pyflakes to ignore a statement?

How to overcome Unindentation error in python?

I have come acros the following error many times. Can anyone help me what to do when this error comes up?
Here I am attaching a screenshot.
I use EditorConfig to solve the problem in those languages.
In .editorconfig, you can write the some rules for python
# 4 space indentation
[*.py]
indent_style = space
indent_size = 4
and save the .editorconfig in the directory.
It once happened to me when I - in order to make things shorter - cut and paste some sentences from another source. I had to rewrite them again and everything went fine. Obviously, Python is quite serious about indentantions.
I normally do "select all" in my text editer, then indent, then unindent. The editor should convert all tabs to spaces (or spaces to tabs depending on the setting in your editor.
Edited to address Steven's comment: If you are using Notepad or some such you could do a find/replace for tabs or something?

Reformat a Python file to have 4 space indentations

I'm editing a Python file that uses two spaces for programmatic indents - I prefer 4 spaces. In my .vimrc I have the following settings related to indentation:
set tabstop=4 "Indentation levels every four columns
set expandtab "Convert all tabs typed to spaces
set shiftwidth=4 "Indent/outdent by four columns
set softtabstop=4
How do I get Vim to convert all the existing 2 space indents to be 4 space indents?
In other words:
if something:
dothis()
becomes
if something:
dothis()
When I tried gg=G
def check():
for a in list:
for b in list2:
check(a, b)
while (len > MAX) :
poll()
while(len(thelist) > 0) :
poll()
return results
became
def check():
for a in list:
for b in list2:
check(a, b)
while (len > MAX) :
poll()
while(len(thelist) > 0) :
poll()
return results
In order to double the number of spaces at the beginning of every line (and only at the beginning):
:%s/^\s*/&&/g
& in replacement pattern is the matched pattern.
Probably it will not have any side-effect for you.
Pressing gg=G is the command to re-indent everything in a file. If you have other elements that can be re-indented, vim will indent these as well, which doesn't always give the desired effects. You'll have to clean these up manually if they're ugly.
Alternately, you can use the > command to indent, with ranges to go through the file somewhat efficiently manually. 99>k, for example, would indent the 99 lines below the cursor by one level.
I've found the reindent script http://pypi.python.org/pypi/Reindent/0.1.0 works well for me. Not pure vim, but really easy!
After its installed you can use it in vim with
:%! reindent
(ie pipe the entire buffer through the reindent program) and it's done.
From the command line it can be used to reindent multiple files (eg all files in a directory, or even recursively down a directory tree).
The best current way to reformat Python, fix many other issues, and also make it PEP8 compliant is to use autopep8. See this related question. So after you've installed autopep8 (e.g. pip install autopep8) in vim you do:
:%! autopep8 -
There's also a vim-autopep8 plugin to make things even simpler.
try the following substitution command:
:%s/ / /g
(To clarify: there are two spaces between the first and second '/' and four the second and third '/'.)
One helpful command when working with whitespace issues is also the
set list
command which will visually show all whitespace. Use
set nolist to unset.
The vim plugin vim-autoformat integrates the formatter autopep8 into vim automatically, if it is installed. You can format the whole file, or the visually selected part using a single keystroke.
More importantly, vim-autoformat takes the relevant settings of your .vimrc into account, e.g. if you have
set shiftwidth=4
in your .vimrc, it will pass this information on to autopep8.
Have you tried?
:retab
I'm not in front of a machine with Vim at the moment so I can't verify this.

Categories