How to edit indented codes in python? - python

Kinda new to python, coming from a C/C++ development experience. Not to rant, but the indentation and spacing things are kinda becoming the bane of my life. So here is the problem. Take this code snippet, typed sequentially, never erasing or inserting any edit between existing codes.
while condition:
line 1
line 2
line3 #outside the loop
It is working fine. But, suppose, I want to add another instruction inside the loop. (Editing using jupyter notebook and sublime, on Linux) So I add the line as
while condition:
line 1
line 1.5
line 2
line3 #outside the loop
That is when the problem starts. No matter what I try, I can never make it work. It is giving me errors like
line 2
^
IndentationError: unexpected indent
or some variations depending on the circumstances. It seems somehow adding a single line within a large and complicated nested block structure somehow totally messes up the whole thing.
I do not insert the spaces/indents manually, I just let my editor take care of that. When I hit enter, the cursor moves down to the next line, indented at the same level as the previous line (unless the previous line ends with a :, in which case it adds another indentation).
When I need to end a while loop or if block, I just hit the backspace to retract one indentation level. The blocks look perfectly okay by eye inspection, but have no clue how the interpreter sees it.
Any help, on what am I doing wrong, or at least what are the good practices to avoid this problem? Particularly, adding even a single line within an existing nested block seems nigh impossible.

You may mix of using space and tab indentation. You can use either tab or space but not both. However, it's recommend to use space as The PEP8 Python Style Guide
If you are using Visual Studio Code, you can install pylint extension to easily detect such kind of these errors. Something like this:
pylint output

Sublime text editor uses tabs for indentation by default. If you initially used spaces for indentation and edit later, you would have a mix of both spaces and tabs for indentation, which is what is causing the indentation error. This is because Python 3 disallows mixing the use of tabs and spaces for indentation.
The PEP8 Python Style Guide recommends using 4 spaces per indentation level. Go back and replace the tabs with spaces, and the code will work just fine.
(PS: It's easy enough to change the default indentation settings for Sublime)

Related

Spyder IDE automatic indentation

Is there any shortcut to automatically indent marked lines in the editor? For example, in MATLAB there is the CTRL+I shortcut.
Matlab's syntax can match the opening closing statements of if,while, for etc. by looking for end statements.
In Python these are ambiguous and defined as the nested indentetation. Hence this cannot be reliably implemented as you cannot decide whether the succeeding if block belongs the the current for loop or it is the next block, if not indented properly.
If indented properly then Forzaa's answer is the answer otherwise the code is useless anyway and needs to be debugged.
First I will just reconfirm what has been said above, that python is ambiguous about what should be the correct indent. Unfortunately as coming from Matlab I also like Ctrl-I.
Though just check on how Tab and Shift-Tab work in practice, they did a little better than I expected. When I ended up having 2 tabs too much after rearranging code, one Shift-tab brought it back to proper position.

why Python string changes to italic looking in the Canopy editor when moved to new line?

This is probably an editor snag. But thought to check in case, as I do not know Python and just started to learn it.
Comparing the following
And I simply move the second field one line below by hitting return
The code in the second line became italic. I thought at first I have some syntax error or the editor is warning me about something, but there is no problem and the code run just as before. This only happens when the """ use. With a single " then the code does not become italic.
Do you think this is just an editor issue, or is the editor trying to tell something I should not be doing?
Specs:
Windows 7, Enthought Canopy 1.5.4 (64 bit)
code in plain text:
data = [r"""123""",r"""456"""]
Without being able to see the documentation for your editor, I would guess that the italics is there to signify that the line is wrapped and is not trying to warn you of anything.
As stated in PEP, "Continuation lines should align wrapped elements either vertically using Python's implicit line joining inside parentheses, brackets and braces, or using a hanging indent". wrapping lines like you're doing is completely ok and the editor shouldn't be warning you of anything.

Indentation Error: Vim creates invisible indents

As you may be able to see (from the screenshot below) there is an additional level of indentation that I did not make and there are no tabs or spaces corresponding to it. Retyping the code does not fix this. The original file was cloned from github. I am using gVim 7+ on Ubuntu 12.04 and to the best of my knowledge the original file was also written on a Linux machine.
Here's the screenshot:
I believe I have indented my code correctly but the indentation guides are showing a new indentation level and Python emits indentation errors.
I am not very clear with line endings and encodings.
I cloned https://github.com/flazzarini/conkyconfig/blob/master/tools/anowplaying.py from git://github.com/flazzarini/conkyconfig.git and viewed the file in Vim with...
:set listchars=tab:>-,trail:-,eol:$ list
...to highlight tabs, spaces and other whitespace differently.
The original author used tabs for indentation. I suspect you are using using spaces but cannot tell from your screenshot.
Invoking Python with the following option...
-tt -- issue errors about inconsistent tab usage
...will help you keep your indentation consistent.
You should probably set noexpandtab tabstop=8 shiftwidth=8 (perhaps in a modeline) to be consistent with the original source. That way, should you ever submit a patch, only the lines you've really added or updated will be submitted.

Virtual brackets in Python

(Warning: Potential flame-war starter. This is however not my goal, the point here is not to discuss the design choices of Python, but to know how to make the best out of it).
Is there a program, script, method (Unix-based, ideally), to display "virtual" brackets around blocs of code in Python, and to keep them where they are so that the code can still be executed even if indenting is broken ?
I realize that Python only uses indentation to define blocks of code, and that the final program may not contain brackets.
However, I find it very annoying that your program can stop functioning just because of an unfortunate and undetected carriage-return.
So, ideally I would be looking for a plugin in a text editor (kate, gedit...) that would:
Display virtual brackets around blocks of code in my Python program
Keep them in place
Generate dynamically the "correct" Python code with the indentation corresponding to where the brackets belong.
(no flame-war, please !)
I used an editor that does code rollups and understood Python syntax, then I looked for rollups that are in unexpected locations. I don't remember if Kate does that. It's not obvious that there is an issue, but it makes it easier when you are looking for an issue.

Is there a way around coding in Python without the tab, indent & whitespace criteria?

I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?
I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?
The answer is no.
At least, not until something like the following is implemented:
from __future__ import braces
No. Indentation-as-grammar is an integral part of the Python language, for better and worse.
Emacs! Seriously, its use of "tab is a command, not a character", is absolutely perfect for python development.
All of the whitespace issues I had when I was starting Python were the result mixing tabs and spaces. Once I configured everything to just use one or the other, I stopped having problems.
In my case I configured UltraEdit & vim to use spaces in place of tabs.
It's possible to write a pre-processor which takes randomly-indented code with pseudo-python keywords like "endif" and "endwhile" and properly indents things. I had to do this when using python as an "ASP-like" language, because the whole notion of "indentation" gets a bit fuzzy in such an environment.
Of course, even with such a thing you really ought to indent sanely, at which point the conveter becomes superfluous.
I find it hard to understand when people flag this as a problem with Python. I took to it immediately and actually find it's one of my favourite 'features' of the language :)
In other languages I have two jobs:
1. Fix the braces so the computer can parse my code
2. Fix the indentation so I can parse my code.
So in Python I have half as much to worry about ;-)
(nb the only time I ever have problem with indendation is when Python code is in a blog and a forum that messes with the white-space but this is happening less and less as the apps get smarter)
I'm currently using NotePad++. Is
there maybe an IDE that would take
care of the tabs and indenting?
I liked pydev extensions of eclipse for that.
I do not believe so, as Python is a whitespace-delimited language. Perhaps a text editor or IDE with auto-indentation would be of help. What are you currently using?
No, there isn't. Indentation is syntax for Python. You can:
Use tabnanny.py to check your code
Use a syntax-aware editor that highlights such mistakes (vi does that, emacs I bet it does, and then, most IDEs do too)
(far-fetched) write a preprocessor of your own to convert braces (or whatever block delimiters you love) into indentation
You should disable tab characters in your editor when you're working with Python (always, actually, IMHO, but especially when you're working with Python). Look for an option like "Use spaces for tabs": any decent editor should have one.
I agree with justin and others -- pick a good editor and use spaces rather than tabs for indentation and the whitespace thing becomes a non-issue. I only recently started using Python, and while I thought the whitespace issue would be a real annoyance it turns out to not be the case. For the record I'm using emacs though I'm sure there are other editors out there that do an equally fine job.
If you're really dead-set against it, you can always pass your scripts through a pre-processor but that's a bad idea on many levels. If you're going to learn a language, embrace the features of that language rather than try to work around them. Otherwise, what's the point of learning a new language?
Not really. There are a few ways to modify whitespace rules for a given line of code, but you will still need indent levels to determine scope.
You can terminate statements with ; and then begin a new statement on the same line. (Which people often do when golfing.)
If you want to break up a single line into multiple lines you can finish a line with the \ character which means the current line effectively continues from the first non-whitespace character of the next line. This visually appears violate the usual whitespace rules but is legal.
My advice: don't use tabs if you are having tab/space confusion. Use spaces, and choose either 2 or 3 spaces as your indent level.
A good editor will make it so you don't have to worry about this. (python-mode for emacs, for example, you can just use the tab key and it will keep you honest).
Tabs and spaces confusion can be fixed by setting your editor to use spaces instead of tabs.
To make whitespace completely intuitive, you can use a stronger code editor or an IDE (though you don't need a full-blown IDE if all you need is proper automatic code indenting).
A list of editors can be found in the Python wiki, though that one is a bit too exhausting:
- http://wiki.python.org/moin/PythonEditors
There's already a question in here which tries to slim that down a bit:
https://stackoverflow.com/questions/60784/poll-which-python-ideeditor-is-the-best
Maybe you should add a more specific question on that: "Which Python editor or IDE do you prefer on Windows - and why?"
Getting your indentation to work correctly is going to be important in any language you use.
Even though it won't affect the execution of the program in most other languages, incorrect indentation can be very confusing for anyone trying to read your program, so you need to invest the time in figuring out how to configure your editor to align things correctly.
Python is pretty liberal in how it lets you indent. You can pick between tabs and spaces (but you really should use spaces) and can pick how many spaces. The only thing it requires is that you are consistent which ultimately is important no matter what language you use.
I was a bit reluctant to learn Python because of tabbing. However, I almost didn't notice it when I used Vim.
If you don't want to use an IDE/text editor with automatic indenting, you can use the pindent.py script that comes in the Tools\Scripts directory. It's a preprocessor that can convert code like:
def foobar(a, b):
if a == b:
a = a+1
elif a < b:
b = b-1
if b > a: a = a-1
end if
else:
print 'oops!'
end if
end def foobar
into:
def foobar(a, b):
if a == b:
a = a+1
elif a < b:
b = b-1
if b > a: a = a-1
# end if
else:
print 'oops!'
# end if
# end def foobar
Which is valid python.
Nope, there's no way around it, and it's by design:
>>> from __future__ import braces
File "<stdin>", line 1
SyntaxError: not a chance
Most Python programmers simply don't use tabs, but use spaces to indent instead, that way there's no editor-to-editor inconsistency.
I'm surprised no one has mentioned IDLE as a good default python editor. Nice syntax colors, handles indents, has intellisense, easy to adjust fonts, and it comes with the default download of python. Heck, I write mostly IronPython, but it's so nice & easy to edit in IDLE and run ipy from a command prompt.
Oh, and what is the big deal about whitespace? Most easy to read C or C# is well indented, too, python just enforces a really simple formatting rule.
Many Python IDEs and generally-capable text/source editors can handle the whitespace for you.
However, it is best to just "let go" and enjoy the whitespace rules of Python. With some practice, they won't get into your way at all, and you will find they have many merits, the most important of which are:
Because of the forced whitespace, Python code is simpler to understand. You will find that as you read code written by others, it is easier to grok than code in, say, Perl or PHP.
Whitespace saves you quite a few keystrokes of control characters like { and }, which litter code written in C-like languages. Less {s and }s means, among other things, less RSI and wrist pain. This is not a matter to take lightly.
In Python, indentation is a semantic element as well as providing visual grouping for readability.
Both space and tab can indicate indentation. This is unfortunate, because:
The interpretation(s) of a tab varies
among editors and IDEs and is often
configurable (and often configured).
OTOH, some editors are not
configurable but apply their own
rules for indentation.
Different sequences of
spaces and tabs may be visually
indistinguishable.
Cut and pastes can alter whitespace.
So, unless you know that a given piece of code will only be modified by yourself with a single tool and an unvarying config, you must avoid tabs for indentation (configure your IDE) and make sure that you are warned if they are introduced (search for tabs in leading whitespace).
And you can still expect to be bitten now and then, as long as arbitrary semantics are applied to control characters.
Check the options of your editor or find an editor/IDE that allows you to convert TABs to spaces. I usually set the options of my editor to substitute the TAB character with 4 spaces, and I never run into any problems.
Yes, there is a way. I hate these "no way" answers, there is no way until you discover one.
And in that case, whatever it is worth, there is one.
I read once about a guy who designed a way to code so that a simple script could re-indent the code properly. I didn't managed to find any links today, though, but I swear I read it.
The main tricks are to always use return at the end of a function, always use pass at the end of an if or at the end of a class definition, and always use continue at the end of a while. Of course, any other no-effect instruction would fit the purpose.
Then, a simple awk script can take your code and detect the end of block by reading pass/continue/return instructions, and the start of code with if/def/while/... instructions.
Of course, because you'll develop your indenting script, you'll see that you don't have to use continue after a return inside the if, because the return will trigger the indent-back mechanism. The same applies for other situations. Just get use to it.
If you are diligent, you'll be able to cut/paste and add/remove if and correct the indentations automagically. And incidentally, pasting code from the web will require you to understand a bit of it so that you can adapt it to that "non-classical" setting.

Categories