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
Related
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
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)
I am trying fix some indentation errors in a Python script. Is there a way to auto correct the errors online or using other utilities?
I hope this error is very familiar, but wanted to avoid this again. Does any editor help in fixing these issues?
IndentationError: expected an indented block
It's not possible in general because some cases would be ambiguous:
something = foo()
if something:
something.bar()
print("ok") # Only half indented. Should this be inside or outside of the if statement?
It's much better to find an editor with auto-indentation support and make sure you indent properly (even in languages without significant whitespaces, as it makes your code easier to read).
You can use reindent.py
For me it worked on some files but it didin't work on others.Give it a try.
reindent.py
Uasge:
reindent.py <filename>.py
Change Python (.py) files to use 4-space indents and no hard tab characters.
Also trim excess spaces and tabs from ends of lines, and remove empty lines
at the end of files.
You can use Spyder IDE
Source Menu -> Fix Indentation
This particular error usually occurs when you forget to add an indented block after a statement that needs one (i.e. if or for). You likely forgot to indent the required block or accidentally hit backspace (or something) such as
def sayhello():
print "Hello world!"
Sometimes you don't want any code after an if statement or after try/except statements, but python will require at least one line after them, so you can use the pass keyword
try:
x= 4/0
except:
pass
print x
I'm a newbie in eclipse. I want to indent all the lines of my code and formatting the open file by pressing a shortcut or something like that...
I know the CTRL+SHIFT+F (as it actually doesn't work in pydev!!)
I've been searching for hours with no success. Is there any way to do that in eclipse. kind of like CTRL+K,D in visual studio, which formats and indents all the source code lines automatically?
If you want to change from 2 space to 4 space indentation (for instance), use "Source->Convert space to tab" with 2 spaces, then "Soruce->Convert tab to space" with 4 spaces.
I ... don't think this question makes sense. Indentation is syntax in Python. It doesn't make sense to have your IDE auto-indent your code. If it's not indented properly already, it doesn't work, and the IDE can't know where your indentation blocks begin and end. Take, for example:
# Valid Code
for i in range(10):
b = i
for j in range(b):
c = j
# Also Valid Code.
for i in range(10):
b = i
for j in range(b):
c = j
There's no possible way that the IDE can know which of those is the correct version, or what your intent is. If you're going to write Python code, you're going to have to learn to manage the indentation. There's no way to avoid it, and expecting the IDE to magically clean it up and still get the desired result out of it is pretty much impossible.
Further example:
# Valid Code.
outputData = []
for i in range(100):
outputData.append(str(i))
print ''.join(outputData)
# Again, also valid code, wildly different behavior.
outputData = []
for i in range(100):
outputData.append(str(i))
print ''.join(outputData)
The first will produce a list of strings, then print the joined result to the console 1 time. The second will still produce a list of strings, but prints the cumulative joined result for each iteration of the loop - 100 print statements. The two are both 100% syntactically correct. There's no problem with them. Either of them could be what the developer wanted. An IDE can't "know" which is correct. It could, very easily incorrectly change the first version to the second version. Because the Language uses Indentation as Syntax, there is no way to configure an IDE to perform this kind of formatting for you.
Although auto-indentation is not a feature of PyDev because of the language design you should be able to indent with a simple tab. Just select the lines you want to indent and press Tab. If you want to unindent lines you have to press Shift+Tab.
Thats all.
It is much easier:
Select multiple lines
Press Tab to indent (move right), Shift + Tab to unindent (move left) all selected
lines.
Indentation is syntactically significant; consider the difference between
for i in range(5):
print i
print "done"
and
for i in range(5):
print i
print "done"
However, it certainly makes sense for the IDE to be able to normalize the existing indentation (e.g. apply a consistent number of spaces/tabs at each level).
Currently PyDev does not support such a feature; Pydev author Fabioz at one point expressed interest in adding it in the future and indicated that for now you can use the supplied reindent.py script to do it.
Obviously this is only for Pydev, but I've worked out that you can get the very useful functions "Shift Right" and "Shift Left" (mapped by default to CTRL + ALT + . and CTRL + ALT + ,) to become useful by changing their keybindings to "Pydev Editor Scope" from "Pydev View". This effectively indents/dedents all lines that you've selected as much as you'd like
I think that what you're looking for is some kind of shortcut in Eclipse/PyDev so that the selected code can be idented all at once. Just like when you create a new "if" or a "for" loop above a block of code and then need to rearrange the identation. The IDLE Editor has the "Ctrl + ]" shortcut that works exactly that way. It seems that the PyDev in Eclipse doesnt have something like that as far as I know.
One can also select the lines, right click, then shift right / shift left
It seems source formatting is still not available in PyDev.
For one off instances I found this web app does the job nicely.
http://pythoniter.appspot.com/
Like earlier said python requires to indent your code, so for other things like: space between variables passed as arguments to methods, etc., one can use ctrl+shift+f to format the code. This what is used for java, I tried for pydev and does some formatting.
This piece of code, file test.py,
if 1:
print "foo"
print "bar"
can be successfully executed with execfile("test.py") or python test.py, but when one tries to copy-paste it into a Python interpreter:
File "<stdin>", line 3
print "bar"
^
SyntaxError: invalid syntax
Why is it so? Can the interpreter by configured in such a way that it would read copy-pasted text successfully?
I guess that may affect typing in the interpreter, but that's OK for me.
Indentation is probably lost or broken.
Have a look at IPython -- it's an enhanced Python interpreter with many convenient features. One of them is a magic function %paste that allows you to paste multiple lines of code.
It also has tab-completion, auto-indentation... and many more. Have a look at their site.
Using %paste in IPython:
And copy-and-paste stuff is one of the things fixed in the Qt console. Here's using a plain old copy-and-paste of your code block that "just works" in the new IPython qtconsole:
I don't know any trick for the standard command prompt, but I can suggest you a more advanced interpreter like IPython that has a special syntax for multi-line paste:
In [1]: %cpaste
Pasting code; enter '--' alone on the line to stop.
:for c in range(3):
: print c
:
:--
0
1
2
Another option is the bpython interpreter that has an automatic paste mode (if you are typing too fast to be an human):
>>> for c in range(3):
... print c
...
0
1
2
>>>
<C-r> Rewind <C-s> Save <F8> Pastebin <F9> Pager <F2> Show Source
Do %autoindent to make automatic indentation off. After that, you can paste your code in IPython.
Continuation lines are needed when entering a multi-line construct.
--Interactive mode, The Python Tutorial (v2) (v3)
So you need to enter:
if 1:
print "foo"
print "bar"
I've yet to find a suitable explanation as to why it's different to a non-interactive session, alas.
All of the current answers suggest you change to IPython. For a Python-only solution, you can use textwrap to remove leading whitespace from lines.
For example,
>>> code=""" x='your pasted code'
y='with common indentation'"""
>>> formatted=textwrap.dedent(code)
>>> exec(formatted)
If you are like me and use Notepad++ (to copy and paste from), try to replace tabs by spaces by going to menu Settings → Preferences → Language and check the replace by spaces.
I had this problem myself for so long and I found out that python.exe recognizes spaces.
If the pasted content has any empty lines, the interpreter triggers evaluation when encountering them. If any line after an empty line has indentation, it will cause an IndentationError since any previous context has been closed.
Solutions:
Delete any empty lines before copying to clipboard.
Add any amount of indentation to empty lines (doesn't need to match code) before copying to clipboard.
Note that spaces vs. tabs does not seem to matter.
exec(pyperclip.paste())
provided you don't mind using exec. Any other third party clipboard package than pyperclip will do I guess.
One other solution I recently found for a similar problem:
$ python << EOF
if 1:
print "foo"
print "bar"
EOF