While coding python I'm using only 2 spaces to indent, sure PEP-8 really recommend to have 4 spaces, but historically for me it's unusual.
So, can anyone convince me to use 4 spaces instead of 2? What pros and cons?
P.S. And finally, what's easy way to convert all existing codebase from 2 spaces to 4 spaces?
P.P.S. PEP-8 Also srictly recommend not using tabs for indention. read here
So, to summarize:
Pros:
- Have more space to arrange when wraping string more than 80 lines long.
- Can copy code from snippets and it just works.
Cons:
- With deeper level of nested statements you have less space for actual code.
Thanks.
One reason is that if you use less spaces for indentation, you will be able to nest more statements (since line length is normally restricted to 80).
Now I'm pretty sure that some people still disagree on how many nested constructs should be the maximum.
If you want to write python code together with other programmers it becomes a problem if you use a different indention as them. Most Python programmers tend to use 4-space indention.
I like the fact that four space characters nicely indents the inner code of a function, because def + one space makes four characters.
I think the real question is why spaces and not tabs.
Tabs are clearly better:
Advantages of spaces:
Any decent editor (emacs, vim) will abstract this whole nonsense out for you. It will work equally well with spaces or tabs, and it can be configured to use any number of spaces (or any number of space-widths for a tab character). It can also convert between the different formats without too much trouble (see the
:retab
command in vim).If you're trying to convert source formatting in bulk, I recommend you take a look at the indent utility.
That said, I can't resist answering the other question... My preference has always been for tabs, since it bypasses the whole issue and everyone can view the source code with the widths set as they see fit. It's also a lot less typing when you're working in editors that aren't helpful with converting it. As far as 2 vs 4 spaces, that's purely cosmetic.
There's no "better" indentation. It's a religious holy-war topic. Four is nice because it's enough to make the indentation clear, but not so much that your whole screen is mostly whitespace and you have to scroll horizontally to read half the program.
It also has the upside of being a "half-tab" w/r to the historical definition of a "tab."
Other than that, use whatever your group likes. It's like chocolate vs. vanilla.
An easy way to switch is to use an editor that has tab and space-tab support. Convert all your leading space-tabs to tabs, set the tab size to four, and then convert leading tabs back to space-tabs.
Pretty easy to do with a python script too. Just count all the leading spaces, then add the same amount to the beginning of the line and write it back out.