VS Code Python autopep8 does not honor 2 spaces hanging indentation - python

I'm trying to get autopep8 work to properly indent Python code with 2 spaces instead of 4. I'm using VS Code with Python extension which uses autopep8 for formatting. I found here that autopep8 can be configured to use 2 spaces by
"python.formatting.autopep8Args": ["--indent-size=2"]
But it does not work for me.
My situation is like this. When I press enter, it correctly starts the next line with the same indentation as the previous line. Press enter after an open parenthesis, it correctly starts the new line with 2 more spaces. But when I paste or save (I have "editor.formatOnPaste" and "editor.formatOnSave" set to true), the annoying thing happened: all the 2-space indentation inside the parentheses became 4 (other 2-space indentation are unaffected). Why is it doing this and how can I make it 2 spaces everywhere?
====EDIT====
I found out that the pylint error Wrong hanging indentation (remove 2 spaces). [bad-continuation]. It's because my pylintrc has indent-after-paren=2. I'm wondering if autopep8 or other Python formatter can set this property?

I also had to include this in my array in settings.json, similar to yours.
"--ignore E121"
According to https://pypi.org/project/autopep8/, this setting ensures your indents are a multiple of 4. By not enforcing that, the configured tab size in VSCode is used.
E121 - Fix indentation to be a multiple of four.
That being said, your indentation is still "acceptable" according to pep8, so it actually will not change it to the 4 spaces you are expecting in your parens. I had to outdent mine one level, then when it ran again, it didn't change it.
Unfortunately this is actually just a workaround and it actually negatively affects other indention rules...
You can see in the code for pep8 that they hardcode the default tab size to be the "python way" (4 spaces) in:
https://github.com/hhatto/autopep8/blob/120537a051d7f3cbbb5c4ede19b9e515156bd3d1/autopep8.py#L104
That makes it look like the hanging indent is just not respecting the --indent-size option...

Adding --indent-size=2 --ignore=E121 worked for me.

had the same issue, here is the solution:
Navigate to library directory of your environment
Open autopep8.py
Search for "DEFAULT_INDENT_SIZE" and change it to 2

Related

why in the Python interpreter the first indentation level is set to 4 space, while the second to 8?

let's take the really simple case of two nested for loops
after pressing return and tab the first time, I get an indentation level where 1 tab equals 4 spaces
after pressing return and tab the second time, I get an indentation level where 1 tab equals 9 spaces
this is rather annoying when I want to copy a piece of code from a script and run it on the interpreter, as it returns the
TabError: inconsistent use of tabs and spaces in indentation
I did some googling but you can imagine what the keywords "python", "interpreter", "indentation" returns: nothing useful
Is there a way to correct this? Thanks
EDIT
just try yourselves:
open a terminal
run python command
then type for i in range(3):
press Enter
then press Tab once, to get to the right indentation level
then type for j in range(3):
press Enter again
then press Tab twice, to get to the (expected) indentation level
if, like me, you have a Mac, chances are that the second Tab hit in the last step above, will yield 8 spaces, instead of 4
This causes problems when copying lines of code written with an IDE
(I'm using Sublime 3, with the option translate_tabs_to_spaces set to True)
I was hoping someone could identify some flag/options/setting of my interpreter which could solve this issue
Title question :
Because you are at 2nd indentation level since you have a loop inside a loop.
Tabulation/space error :
Python uses only indentation to interpret which block belongs to the code. No "BEGIN...END" , no brackets. So indentation IS information.
The rule is "indentation must be uniform", so either everything is spaces (1,2,4.. as you want) or everything is tabulations.
For more information, refer to the Python style guideline (PEP8) here :
https://www.python.org/dev/peps/pep-0008/
By using an IDE ( such as Spyder, for example) tabs will automatically be replaced by spaces. I recommend you to use one, especially if you are a new to python.

Stop Jupyter auto-indenting new lines a large, non-integer amount of tabs?

Running Jupyter (core:4.4.0, notebooks:5.7.8) python3 notebooks on OSX.
The notebook seems to get easily confused about how to auto-indent new lines. Specifically, my more complex cells that have nested indentations for defs, ifs, whiles (etc) cause Jupyter to use a weird 4.5-tab auto-indent that doesn't match any of my indentation levels and leads to lots of wasted keypresses to fix the indent on EVERY. SINGLE. NEW. LINE.
To be clear, I'm not asking how to change the default tab spacing, I'm asking how to stop jupyter autoindenting to something insane when I hit 'return' to make a new line.
One potential source of error is my use of f-strings; Jupyter sometimes screws up the syntax highlighting for hashes and nested quotes eg. print(f"Output for #{myNum} | {myDict['namedItem']}").
Any tips on what might cause the issue would welcome.
Answer: Yes it is f-string literals. Nested quotations in an f-string will screw up the indentation in cell, setting the new line default to start of the quote in the f-string.
eg.
print(f"Output for #{myNum} | {myDict['namedItem']}")
# Newline starts here
# and here
# Manual de-indent here for readibility.
x=5 # and manually force python code to an indent where it actually runs
# Default newline is still here though
# And will stay here for the rest of the cell
f-strings generically break the CodeMirror syntax highlighter underlying jupyter notebooks, known since Jan 2017. There have been some minor fixes to make it break less badly, but the problem is not fixed -- see recent Git issues
EDIT: Since Jan 2020 jupyter 6.0.2, this should be fixed via an update to CodeMirror 5.48.4.

Python indentation in Spacemacs with hard tabs is off

Let me preface by saying that I am a relatively new emacs/spacemacs convert from vim, so my my knowledge is still pretty basic.
I have spacemacs set up with the python layer, with the additional package of dtrt-indent listed in dotspacemacs-additional-packages. And setting
(dtrt-indent-mode t)
in the dotspacemacs/user-config. I need the dtrt-indent as I am working on a few projects (in python and lua) where I am not the one who sets the indentation rules.
This configuration works fine for python files with soft-tabs of varying length. This configuration also works for lua files that have hard tabs.
When I open a python file indented with hard tabs something seems to get messed up, it appears to think that the indentation is two hard tabs. Meaning, if I have code like this (pretend that the 4 spaces are tabs):
def func():| <--- Cursor
print 'line'
and press enter, I get:
def func():
| <--- Cursor
print 'line'
The status line prints dtrt-indent's message saying:
Note: indent-tabs-mode adjusted to t
Note: As stated I'm pretty new at this, and my spacemacs configuration is pretty sparse. There is nothing else in my user-config, I have not custom layers, I don't even have any additional packages other than dtrt-indent.
EDIT:
python-indent-offset is set to 8
indent-tabs-mode is set to t
tab-width is set to 4
Try M-x whitespace-mode and repeat this experiment. What do you see? Did you indent with spaces or with tabs?
I'm guessing you'll see something like this:
def·func():
········
» print·'line'
This would mean you have python-indent-offset set to 8, indent-tabs-mode set to nil (aka indent with spaces), and tab-width set to 4.
If that's not the case, what are the values of those variables (C-h v python-indent-offset, etc.)?
If that is the case, you can fix the problem by running
(setq-default python-indent-offset 4)

Indentation error in simple python

Update: The original question was posted using C-RET to run the lines, which produces the error. I get no such error using The menu Python > Eval region, which successfully evaluates the script.
However, using the menu for every execution is really annoying, and moreover I can't run the present line alone with that method. So my problem remains.
Forgive me if I'm missing something obvious, but I can't figure this out.
This code is giving me an IndentationError. I can't imagine what's going on.
for x in range(0, 3):
print "We're on time %d" % (x)
Here's everything related to python in my emacs.el
;; elpy
(add-to-list 'package-archives
'("elpy" . "http://jorgenschaefer.github.io/packages/"))
(package-initialize)
(elpy-enable)
You've mixed tabs and spaces. This can lead to some confusing errors.
I'd suggest using only tabs or only spaces for indentation.
Using only spaces is generally the easier choice. Most editors have an option for automatically converting tabs to spaces. If your editor has this option, turn it on.
You can paste your code in notepad to see.
All commands from menu have a command-name callable via M-x COMMAND RET.
In this case M-x python-send-region RET

Unexpected Indent when defining variable

I'm new to Python and it just confounds me with Indentation errors. In the following images, why does the first one work and the second one give me an indentation error?
Works:
Doesn't work: (Notice extra tree-expander that pops up in Notepad++)
Error:
File ".\sigma.py", line 14
for val in vs:
^
IndentationError: unexpected indent
I'm using Notepad++ and there are no spaces/tabs issues anywhere. Also, tried it out on the Python console typing it in exactly the same way in the 2nd image. It works fine. I'm guessing there's a very logical explanation to this, but coming from a strong-typed background (>5 years in Java), this feels like an unnecessary error.
You are mixing tabs and spaces. Don't do this, it creates inconsistent indentation problems.
Run your script through the tab checker:
python -tt script.py
and fix any and all tabs (replace with spaces), then configure your editor to only use spaces.
For Notepad++, see:
Convert tabs to spaces in Notepad++
How does one configure Notepad++ to use spaces instead of tabs?

Categories

Resources