90

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.

smci
  • 32,567
  • 20
  • 113
  • 146
HardQuestions
  • 4,075
  • 7
  • 34
  • 39
  • 8
    Your gonna want to make this a community wiki or this will probably get closed. This is a highly debatable topic that everyone has there own opinion on. – MitMaro Jul 14 '09 at 14:16
  • @MitMaro: I agree that this is highly subjective; although it's worth noting that the P.S. part is a valid question. – DrAl Jul 14 '09 at 14:20
  • @AI: Should have been two separate questions – MitMaro Jul 14 '09 at 14:22
  • 4
    It is highly subjective and a matter of opinion. Of course, the right opinion ( ;) ) is that everyone should use tabs so they can space things out as they prefer with editor preferences. – Quentin Jul 14 '09 at 14:23
  • Don't want to make a holy war from it. I will summarize add my thoughts why I should use 4 spaces instead of 2, and with samples. – HardQuestions Jul 14 '09 at 14:27
  • 24
    I see no reason whatsoever to close this question. He is asking a legitimate programming question, as programs are meant to be READ as well as written. And being subjective doesn't make it matter any less. – Daniel C. Sobral Jul 14 '09 at 14:29
  • If you were following the Ruby guidelines, you'd be using two spaces because that's what that group of fan-boys decided :) I'd imagine that you could write a Python script to read your Python code and replace two spaces with four spaces pretty easily... – BenDundee Feb 04 '14 at 17:21
  • I just saw this question on the sidebar and thought: Wait, Python 4? Did I miss something? The title could need some formatting... – tobias_k Aug 26 '16 at 21:36
  • for atom: easy setup would be to set spaces = 4 for tabs and use "soft tabs" in atom. soft tabs means when you press tab, it'll be treated as 4 spaces. – abe312 May 30 '18 at 07:13

13 Answers13

151

Everyone else uses 4 spaces. That is the only reason to use 4 spaces that I've come across and accepted. In my heart, I still want to use tabs (1 indent character per indent, makes sense, no? Separate indent from other whitespace. I don't care that tabs can be displayed as different widths, that makes no syntactic difference. The worst that can happen is that some of the comments don't line up. The horror!) but I've accepted that since the python community as a whole uses 4 spaces, I use 4 spaces. This way, I can assemble code from snippets others have written, and it all works.

Markus
  • 3,447
  • 3
  • 24
  • 26
  • 34
    "This way, I can assemble code from snippets others have written, and it all works..." AND it looks and feels as _my_ code :) – xtofl Jul 15 '09 at 04:11
  • 24
    There are a lot of people on this topic claiming that tabs are the One True Solution, because you can set them to any width you wish... that's great until continuation lines end up splayed all over the place because of the new way tabs are calculated, or your right margins overflow... I've been dealing with a ton of that in the past year in inherited code in other languages, and it makes me adore the time I get to spend going back to generally pretty uniformly-indented Python. – Mattie Apr 20 '12 at 01:06
  • 3
    I am not affiliated with Sublime Text (except bought a license awhile back), but I find it really useful to set custom preferences with `'tab_size' = 4` just for python, and default `'tab_size' = 2` for other languages (like JavaScript etc). – Antony Sep 17 '12 at 04:38
  • 2
    I cannot be more with you @Markus :) Accepting the status quo when the difference is in the end quite minimal is what draws the line with being pedantic. – Micha Mazaheri Jan 25 '17 at 11:34
  • use an editor that allows you to type tab, but output 4 spaces. Layer of indirection ftw – ahnbizcad Jul 09 '17 at 19:03
  • 2
    "A common question beginners ask is, "How many spaces should I indent?" According to the official Python style guide (PEP 8), you should indent with 4 spaces. (Fun fact: Google's internal style guideline dictates indenting by 2 spaces!)" — https://developers.google.com/edu/python/introduction?csw=1#indentation – michael Jul 29 '20 at 05:24
  • Seems like google pyguide recommends 4 spaces indentaion now: https://google.github.io/styleguide/pyguide.html#34-indentation – Dzenly Jan 05 '21 at 12:55
89

I like the fact that four space characters nicely indents the inner code of a function, because def + one space makes four characters.

def·foo():
····pass
Ionuț G. Stan
  • 176,118
  • 18
  • 189
  • 202
  • 44
    And I like the fact that three space characters nicely indent the inner code of an `if` statement, because `if` + one space make three characters. – Alexander Shukaev Nov 25 '18 at 16:26
66

I think the real question is why spaces and not tabs.

Tabs are clearly better:

  • It makes nearly impossible to have inconsistent indentation (I've seen code that normally has 4 spaces indents, but then some parts happen to be one space off, it's difficult to tell by simple inspection if there are 7 or 8 spaces... That wouldn't happen with tabs, unless you set your tabstop to 1 space).
  • Tab is a logical semantic representation for indentation, it allows you (and any other developer) to choose to display as many "spaces" (or rather columns) you want without messing with other people's preferences.
  • It is also less keystrokes if you happen to have only "notepad" (or other dummy editor) at hand.
  • Adding and removing tabs is a symmetric operation. Most IDE's may insert automatically 4 spaces when hitting the tab key, but usually they remove just 1 space when hitting backspace (un-indent operation is still accessible as shift-tab, but that's a two key combination) or you use the mouse to click in the middle of the indentation and delete one character.
  • They take only 1 byte rather than 4 (multiply by thousands of lines and you save a few KB! :p)
  • You have one less thing to settle an agreement, because if you decide to go for spaces, then the discussion starts again to choose how many (although the consensus seems to be around four).

Advantages of spaces:

  • Guido likes them.
  • You cannot easily type a tab here, it transfers the focus (although you can paste one).
fortran
  • 74,053
  • 25
  • 135
  • 175
  • 2
    I like the way you said it transfers the focus. – Gibbs Mar 12 '15 at 05:00
  • Spaces also render the same way on different platforms. – ggorlen Apr 04 '23 at 18:44
  • This answer hasn't really aged well IMO. Most of these pros for tabs are addressed by modern IDEs that can insert either a tab or a tab's worth of spaces whenever you press the tab key and can not only configure how many spaces makes a tab but can also convert between the two conventions on the fly. And the size point is pretty minor unless you have literally millions of lines of Python sitting on your computer or are worried about deployment storage (in which case, that's what minification utilities are for). – Abion47 May 02 '23 at 18:41
17

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.

Christopher
  • 8,815
  • 2
  • 32
  • 41
  • We did the same thing in Emacs. That way the programmers could see the spacing they preferred without forcing it on the rest of the group. – Kelly S. French Jul 14 '09 at 14:37
  • I know this is a very old answer, but I would just like to dispute the statement 'There's no "better" indentation.' For the reasons listed in the answer by @fortran (and honestly *many* other reasons I can think of), tabs are clearly a better indentation and I'm frustrated space as indent is still and ever was a thing. The only advantages I can actually think of spaces are some text boxes tab out when writing online code and spaces are easier to type (which is bogus because that is no longer the case after typing multiple spaces and tab is far from the most difficult key a coder uses). – dallin Nov 04 '22 at 01:23
  • I would also argue 4 spaces is objectively better than 2 for code clarity as well. At least for me, I've always found it very difficult to tell what column a new unindented line is on and what code it lines up with, unless there's only a couple lines in the indention level. Additionally, this has become an accessibility issue for me recently as I have developed a genetic condition that affects my eyes and visual processing that has made this even harder. – dallin Nov 04 '22 at 01:32
16

The PEP isn't the boss of you. If it's already consistently 2-space indented, there's no reason to change all your code to conform to it. You could follow it going forward if you really think it's that vital, but, frankly, I don't. You're better off going with whatever convention provides you (and your coworkers) the most comfort both in reading and writing.

Pesto
  • 23,810
  • 2
  • 71
  • 76
  • 1
    Agreed. Make your own convention for your code. I use 2 spaces everywhere, no matter what the language is, so for me all of mine code is consistent. Take alien code style guidelines, e.g. PEP, with a grain of salt and adapt them for your needs. 4 spaces per indentation is dumb waste of horizontal space and those who invented this should go and buy everyone top resolution monitors if they like this convention so much. – Alexander Shukaev Nov 25 '18 at 16:22
7

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.

rmeador
  • 25,504
  • 18
  • 62
  • 103
6

Also one of reasons is: when you have some long line (longer than 80 symbols) and want to split it in 2 you will have only 1 space to indent, that is a bit confusing:

if code80symbolslong and somelongvariablegoeshere and somelongerthan80symbols \
 and someotherstatementhere:
  # some code inside if block
  pass

if code80symbolslong and somelongvariablegoeshere and somelongerthan80symbols \
  and someotherstatementhere:
    # some code inside if block
    pass
HardQuestions
  • 4,075
  • 7
  • 34
  • 39
  • 11
    You shouldn't do that. If your indentation is 4 spaces you should never have indentations of less than that. In my opinion the "and" line should be indented one two more levels than the "if" line. – TimK Feb 07 '16 at 19:30
5

If you're the only coder working on your source file and there are no coding standards that enforce a particular style, use whatever you're comfortable with. Personally (and in line with our coding standard), I use hard tabs so that whoever is looking at the code can use their own preference.

To make a change, you simply need to change all start-of-line spaces to ones that are twice as large. There are many ways to do this; in the Vim text editor, I can think of two: firstly:

:%s/^\(\s\{2}\)\+/\=repeat(' ', len(submatch(0))*2)

This is a simple regular expression that looks for one or more pairs of spaces at the start of the line and replaces them with twice as many spaces as were found. It can be extended to do all files by opening vim with:

vim *.py

(or the equivalent), followed by (untested):

:argdo %s/^\(\s\{2}\)\+/\=repeat(' ', len(submatch(0))*2)/ | w

Alternatively:

" Switch to hard tabs:
:set noexpandtab
" Set the tab stop to the current setting
:set tabstop=2
" Change all spaces to tabs based on tabstop
:retab!
" Change the tab stop to the new setting
:set tabstop=4
" Go back to soft tabs
:set expandtab
" Replace all the tabs in the current file to spaces
:retab

Of course, many other tools will offer similar features: I would be surprised if something like sed, awk, perl or python couldn't do this very easily.

DrAl
  • 70,428
  • 10
  • 106
  • 108
5

Identation and general coding style standards vary from language to language, project to project. There is one reason for adopting a coding style standard: so that the code look uniform, no matter who wrote it. That improves legibility in the project, and, to put it bluntly, it looks better.

There is one reason that is not valid when adopting a coding style standard: because you like it. Coding standards exists precisely because people's preferences vary, and if left to their own, chaos would ensue, to the detriment of all.

If you are writing code for yourself alone, which no one will ever read, go ahead and write it whatever you like. Otherwise, following the accepted standard of your community will make your code much more agreeable to everyone else's eyes. And remember, too, that if you DO decide to contribute code to a community in the future, you'll have an easier time if you are used to their coding style already.

As for changing the tab size, there are are many source code formatters out there which support Python, and most programmer's editors and IDEs also have this capability. You probably have it already, it's just a matter of consulting the documentation for the editor you are using.

Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681
2

It is easier to visually identify long nested code blocks with 4 spaces. Saves time when debugging.

  • Agreed. For a language like C I'd rather use two, actually, but in C the visual clue provided by indentation is less important than it is in Python. – user1071847 Sep 19 '17 at 14:43
1

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.

Bastien Léonard
  • 60,478
  • 20
  • 78
  • 95
1

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.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
Christian
  • 25,249
  • 40
  • 134
  • 225
0

using 4 spaces or 2 spaces is entirely up to you. 4 spaces is just a convention. What is most important, don't mix tabs and spaces. Use the space bar

ghostdog74
  • 327,991
  • 56
  • 259
  • 343