200

I see on Stack Overflow and PEP 8 that the recommendation is to use spaces only for indentation in Python programs. I can understand the need for consistent indentation and I have felt that pain.

Is there an underlying reason for spaces to be preferred? I would have thought that tabs were far easier to work with.

TylerH
  • 20,799
  • 66
  • 75
  • 101
quamrana
  • 37,849
  • 12
  • 53
  • 71
  • 8
    Read the PEP discussion to know. – Bite code Sep 23 '08 at 15:52
  • 6
    I'm editing in the subjective tag since tabs vs. spaces has been known to cause lots of holy wars. :) – Jason Baker Sep 27 '08 at 16:59
  • 8
    i think the subjective tag is (for once) wrong. the question asks for the reasoning or reason behind the decision in the canoncial text about the subject! –  Oct 10 '08 at 13:49
  • 2
    PEP = Python Enhancement Proposal. – Peter Mortensen Jul 31 '09 at 21:30
  • 187
    1 level of indentation is... 1. It is completely illogical to have to agree on using N spaces when you could all use a single tab. Which, by the way, is exactly meant to do that. Indent. Once. 1 level of indentation = 1 single character, i.e. 1 single tab. And they are more handy because each coder may chose freely how to visualize it. Using spaces is dumb, I've never ever seen a single argument for it which is non stupid. – o0'. Jan 19 '12 at 14:53
  • 3
    The real question is: If 4 spaces is the norm, why does the python interpreter equal 1 tab to 8 spaces? You can indent one line with 1 tab and the next line with 8 spaces, at the code will work (tested with 2.6.5). Either, the python interpreter should *always* throw an exception when mixing tabs and spaces, or it should at least be consistent with the PEP. – tobias_k Sep 07 '12 at 13:10
  • 5
    @Lohoris, do you consider consistency stupid? If I use the convention that 1 level of indentation is 4 spaces, I don't have to know how you interpret tabs when I send you my program; when you open it, it will look to you like it looks to me. You can't say the same thing for people who don't have the same preferences for how tabs should "look". This point (consistent, predictable appearance) is a large part of the motivation for file formats like PDF, by the way. – BlueBomber Feb 22 '13 at 21:33
  • 55
    @BlueBomber and why don't you force people to have a font size and a color scheme you like, while you are at it? Still stupid. – o0'. Feb 22 '13 at 22:20
  • 3
    @Lohoris, so, the answer to my question was "yes", then? With respect to font color, etc., you know that's absurd and unrelated to my point. – BlueBomber Feb 22 '13 at 22:48
  • 27
    @BlueBomber no, no, it is EXACTLY on the same level of absurdness. – o0'. Feb 22 '13 at 22:57
  • 4
    @Lohoris, I disagree. I also happen to think that you recognize the distinction between changing a font color and having an editor spatially shift characters around on the screen, but don't want to concede it. We can agree to disagree. – BlueBomber Feb 25 '13 at 20:08
  • 2
    To align with an opening delimiter (as in the first example in PEP-8) you have to use spaces to appear consistent. Even if you can agree on the width of a tab, you can't agree on the number of characters in the function name being a multiple of that. – Ryan Haining Dec 01 '13 at 22:39
  • 28
    @BlueBomber What exactly is the difference? You're reducing a degree of freedom in another developer's configuration of their environment without achieving any noticeable benefit. If you want to be a dictator and force everyone to look at the code with an indent corresponding to 2 or 4 or 29 spaces you can still do this with tabs. Just ask your underlings to set their IDE to display tabs as corresponding to your preferred number of spaces. If you don't have the authority to do this, maybe you should let them decide for themselves how wide a unit of indentation is comfortable to their eyes. – Asad Saeeduddin Sep 23 '14 at 23:44
  • 1
    @hop right, but it's clearly sparked a holy war. Whether SO should punish subjective questions is a different matter, but clearly in the current meta this question is "not fit for SO's format" – Nathan majicvr.com Jul 11 '18 at 23:10
  • @o0'. This is an old post, but I still want to add: In the past I was pro tabs (obviously), then I was pro spaces, because of this argument: when everyone (you, your team, the world, the web, documentations, books) are on the same page, your brain adapts to the indentation and everyone globally gets faster reading code (including yourself). Yes, this would even be true for syntax highlighting. Now, I am back to spaces for one simple reason: support the the visual impaired that have different requirements for reading code and a very hard time with spaces. – Toxiro Apr 03 '22 at 20:56
  • 1
    @Toxiro So you're saying the static spaces are better than configurable tabs for visually impaired? I don't see how that makes sense. Can you explain? – trusktr May 26 '22 at 23:10
  • 1
    @trusktr Oh good that you mentioned it. My mistake, I meant “Now, I am back to tabs” not spaces (for the visual impaired). – Toxiro May 28 '22 at 01:14
  • 1
    What about this point of view: https://www.reddit.com/r/javascript/comments/c8drjo/nobody_talks_about_the_real_reason_to_use_tabs/ ?! – davidmpaz Jul 14 '22 at 07:55

18 Answers18

213

Well well, seems like everybody is strongly biased towards spaces. I use tabs exclusively. I know very well why.

Tabs are actually a cool invention, that came after spaces. It allows you to indent without pushing space millions of times or using a fake tab (that produces spaces).

I really don't get why everybody is discriminating the use of tabs. It is very much like old people discriminating younger people for choosing a newer more efficient technology and complaining that pulse dialing works on every phone, not just on these fancy new ones. "Tone dialing doesn't work on every phone, that's why it is wrong".

Your editor cannot handle tabs properly? Well, get a modern editor. Might be darn time, we are now in the 21st century and the time when an editor was a high tech complicated piece of software is long past. We have now tons and tons of editors to choose from, all of them that support tabs just fine. Also, you can define how much a tab should be, a thing that you cannot do with spaces. Cannot see tabs? What is that for an argument? Well, you cannot see spaces neither!

May I be so bold to suggest to get a better editor? One of these high tech ones, that were released some 10 years ago already, that display invisible characters? (sarcasm off)

Using spaces causes a lot more deleting and formatting work. That is why (and all other people that know this and agree with me) use tabs for Python.

Mixing tabs and spaces is a no-no and no argument about that. That is a mess and can never work.

Nayuki
  • 17,911
  • 6
  • 53
  • 80
nigratruo
  • 2,229
  • 1
  • 13
  • 2
  • 55
    To add to that, take a look at your keyboard, the TAB key's symbol clearly portrays indentation - it's the key's indented purpose not SPACE's. PEP8 recommends to use spaces is a mistake IMHO but it is just a recommendation - http://en.wikipedia.org/wiki/Tab_character#Tab_characters – Daniel Sokolowski May 23 '13 at 14:21
  • 50
    Agreed with this post entirely. Using spaces is for fools who enjoy getting tripped up on those 1 space off indentation errors. If your indentation was off by 1 tab, I guarantee you'd notice it. – Sepero Jun 06 '13 at 10:37
  • Nobody can use tabs exclusively: tabs and spaces are always used in combination and this leads to inconsistency. For consistency's sake only one type of character should be used and that is: the space! (just because it is an atomic character you cannot divide it and you cannot resize it). – Zingam Dec 27 '15 at 14:25
  • 23
    @Zingham _Nobody can use tabs exclusively: tabs and spaces are always used in combination and this leads to inconsistency._ I and thousands of others are using them quite consistently every day. Tabs for indentation, spaces for alignment. Exactly which part of this concept do you find so terribly hard to grasp, and why are you convinced that it is impossible to apply it consistently? – antred Jan 22 '16 at 14:11
  • No matter how hard I try, I find spaces irritating and requires multiple key presses or cognition instead of the simple Tab, which is what the damn key does for me. I'm bereft without tab! – disruptive Jul 09 '16 at 15:54
  • 1
    The actual problem with tabs is that you cannot get exact indendation to-the-character recommended by the same PEP8 under the comment "# Aligned with opening delimiter." That only is the reason to prefer spaces: to get the indentation correct! – user541905 Feb 06 '17 at 10:17
  • 11
    The question is **"Why does Python pep-8 strongly recommend spaces over tabs for indentation?"**. This answer does not ever mention anything about the PEP8. ||| Instead of trying to answer the question... this answer comes across to me as one huge condescending **primarily opinion** piece. There are 276 words used to say "tabs are better than spaces and here's why...". – Trevor Boyd Smith Sep 25 '18 at 18:49
  • What about this point of view: https://www.reddit.com/r/javascript/comments/c8drjo/nobody_talks_about_the_real_reason_to_use_tabs/ ?! – davidmpaz Jul 14 '22 at 07:55
  • All "modern editors" as well as the interpreter know what leading spaces (and tabs) signify. Seems like, "in the 21st century", it would not be so difficult to create a function in those modern editors that would allow you to define the displaying length of (multiples of) leading spaces. Then the issue raised in the answer becomes moot and the argument irrelevant, and people can continue to argue over other very important issues concerning tabs and spaces in the 21st century. – Lu Kas Sep 28 '22 at 10:47
  • Despite me having a preference for tabs over spaces for indent - I couldn't find a formatter for vs code that would properly format a python file with tabs for indent - even passing in config args - exp: "python.formatting.autopep8Args": [ "--indent-tabs", "--indent-size=4" ], – Tim Feb 28 '23 at 15:38
  • That's exactly why I prefer PyCharm to VS Code. All the other devs use VS on my team, but I stick to JetBrains. Right in preferences you can choose tabs or spaces, how many spaces a tab will be, smart tabs etc, and you can also easily convert tabs to spaces or vice-versa straight from the menu so you're never chasing "mixed indentation" exceptions. VS Code really seems like a heavily plugin dependent text editor to me, but PyCharm and Webstorm legit IDEs. But to each their own. (and I'm aware this could easily become another big debate) – user2233949 Jul 28 '23 at 20:53
142

The answer was given right there in the PEP [ed: this passage has been edited out in 2013]. I quote:

The most popular way of indenting Python is with spaces only.

What other underlying reason do you need?

To put it less bluntly: Consider also the scope of the PEP as stated in the very first paragraph:

This document gives coding conventions for the Python code comprising the standard library in the main Python distribution.

The intention is to make all code that goes in the official python distribution consistently formatted (I hope we can agree that this is universally a Good Thing™).

Since the decision between spaces and tabs for an individual programmer is a) really a matter of taste and b) easily dealt with by technical means (editors, conversion scripts, etc.), there is a clear way to end all discussion: choose one.

Guido was the one to choose. He didn't even have to give a reason, but he still did by referring to empirical data.

For all other purposes you can either take this PEP as a recommendation, or you can ignore it -- your choice, or your team's, or your team leaders.

But if I may give you one advice: don't mix'em ;-) [ed: Mixing tabs and spaces is no longer an option.]

  • 13
    Agreed. Consistency is more important than tabs vs. X spaces vs. Y spaces. – Mike Clark Dec 10 '10 at 06:20
  • 21
    makes me wonder... why does the standard library have so many mixedCase method names? – Kyle Wild Feb 23 '11 at 19:22
  • 6
    @dorkitude: a) nobody is perfect. b) historical reasons. –  May 03 '12 at 14:55
  • 12
    So then why did so many programmers choose to use spaces before PEP-8? That's what I really want to know. The advantages of tabs seem obvious to me, but not spaces. – einnocent Mar 01 '14 at 00:40
  • @KyleWild my guess is that a lot has been directly translated from Java. An example is the logging module. – Pithikos May 27 '15 at 17:15
  • 22
    ["My recommendation is to always use tabs on the Mac -- then it will look good on the Mac and at least parse correctly everywhere. For the same reason I recommend always using tabs on Unix as well \(thus indenting by 8 positions there\), but the majority of Python users seem to be against me."](http://legacy.python.org/search/hypermail/python-1994q2/0205.html)—Guido van Rossum, 1994 – noumenal Aug 12 '16 at 12:53
  • 5
    @noumenal: the problems with (long obsolete) OSs and editors mentioned in this post should make it clear that its arguments have no relevance today. –  Aug 12 '16 at 15:42
  • 1
    How can editors display 4 spaces as if it were 2 spaces? I've only ever seen editors be able to do that for tabs. Tabs are superior. They are shorter, atomic (a single character is a single level of indentation). It's not a matter of taste, and it isn't splitting hairs. Tabs accommodates everyone's varying tastes as users can set their editor to render tabs in whatever number of spaces they want. Spaces are inflexible and will force every editor to render them as n spaces. other does not. One is like a polymorphic method call. The other is concretely one variant method call only. – ahnbizcad Apr 23 '21 at 10:31
  • @ahnbizcad pretty sure lots of editors can do that actually but it's obviously something easier to implement using tabs – CervEd May 04 '21 at 12:01
  • 1
    can you name me one? ive never seen a single editor. – ahnbizcad Jun 21 '21 at 15:27
  • some editors like vscode support insertion of 4 or 2 spaces on pressing of tab button. this is not the default behavior, you should specify in it vs code settings. pressing shift+tab deletes those spaces. this will just reduce the key presses but will not help with indentation rendering – Manohar Bhat Sep 25 '21 at 17:49
  • vim probably can, using the conceal feature – tbrugere Dec 08 '21 at 01:42
  • What about this point of view: https://www.reddit.com/r/javascript/comments/c8drjo/nobody_talks_about_the_real_reason_to_use_tabs/ ?! – davidmpaz Jul 14 '22 at 07:55
43

I personally don't agree with spaces over tabs. To me, tabs are a document layout character/mechanism while spaces are for content or delineation between commands in the case of code.

I have to agree with Jim's comments that tabs aren't really the issue, it is people and how they want to mix tabs and spaces.

That said, I've forced myself to use spaces for the sake of convention. I value consistency over personal preference.

Edit 2022: Use spaces. Follow the language conventions and those set in the particular project you're working on. Use a linter to ensure those conventions are maintained. Format on save. Lint on commit. This will reduce "bikeshedding" on a team. As I mentioned so many years ago, consistency over personal preference!

Bikeshedding, also known as Parkinson’s law of triviality, describes our tendency to devote a disproportionate amount of our time to menial and trivial matters while leaving important matters unattended.

Soviut
  • 88,194
  • 49
  • 192
  • 260
  • 4
    I tried to force myself to use spaces too, but editor (at least Eclipse + PyDev) wise tabs wins especially if you enable show invisible characters. And I can easily set tabs to be 4, 8, 6 spaces visually. So in my code at least I value personal preference, and stick to spaces if that is the established convention in existing code base. – Daniel Sokolowski May 16 '13 at 18:29
  • 3
    That's fine as long as you're not coding in a team. Once you're in a team, you agree upon a single convention and stick to it. – Soviut May 16 '13 at 20:22
  • 1
    @Soviut That seems mostly like wishful thinking to me. In all the teams I've ever been in, the official party line was "use spaces". The reality was that virtually every file was a total mess of both tabs and spaces, and even in files that consistently used only spaces or only tabs, the indentation was still all over the place. – antred Jun 16 '15 at 21:40
  • Yeah but that's what I meant. Some consensus is eventually reached and enforced. Like you said, it's usually "just use spaces". – Soviut Jun 18 '15 at 04:52
  • 1
    this is the main reason why I prefer tabs. It just makes sense to have separate characters for layout and word delimiting – woojoo666 Jun 28 '16 at 04:33
  • Tabs are used to delimit words in all sorts of situations, though. The key takeaway is that spaces are always interpreted the same way, tabs are not. No matter what editor you use, spaces will always look the same. – Soviut Jun 28 '16 at 04:37
  • Which is the reason why spaces are just plain wrong – o0'. Apr 08 '22 at 14:30
  • @o0'. The reason for spaces is mostly a different one. People tend to say that it is a matter of taste, but it is not. Sharing code online, writing documentations and working in huge teams together with multiple companies, you really want to prevent individuality for the simple reason that you brain adapts to the indention size and learns to process it faster. To improve the overall performance you want to have the indention size the same everywhere. – Toxiro May 28 '22 at 10:46
  • @Toxiro using spaces has the opposite results of what you claim. With tabs you can chose the tab size and having it consistent everywhere. With spaces you are forced to how many spaces the others chose to use. – o0'. May 30 '22 at 23:34
  • @o0'. No, that is exactly what you do NOT want in huge teams. You have code documentation online. Your company documentation and official programming language documentation, you have code reviews in video calls world wide, you have meetings, pair programming and so on. You really really do NOT want everyone to choose their own style. As I said, because only then, everyone can read code together without having to adapt their brains to the current style. This improves performance for everyone. It is mandatory to set the indention to e.g. 4 spaces without anyone being able to alter it. – Toxiro Jun 01 '22 at 11:55
  • @o0'. This is exactly the same as using Corporate Design for documents. Code is written once, but read multiple times and it is many times not read on your personal computer in your personal configured editor. Furthermore it is often read together by multiple people. You want to force everyone to look at documents, code, web sites that looks similar in order to scan everything really fast. – Toxiro Jun 01 '22 at 11:59
  • @o0'. it's not an attack on individuality, it's a push for code consistency. Express yourself through your code operation, not how you format it. If you want to get a book published, you have to follow normal publishing standards for layout, margins, typesetting, etc. to maximize readability. it's the words on the page that make it a good story, NOT how they're laid out. – Soviut Jun 01 '22 at 15:23
  • @Soviut still irrelevant. Consistency? 1 indentation level = 1 tab. What's more consistent than that? 4 spaces? 3 spaces? 5 spaces? It's ridiculous, it's just wrong. – o0'. Jun 03 '22 at 00:34
  • @o0'. it's consistency with the rest of the industry. Everyone has established a convention and those conventions are backed up by formatters (prettier, for example) and linters (eslint, for example). Ignoring them means you're bike shedding and wasting everyone's time. – Soviut Jun 03 '22 at 18:40
  • @o0'. There is nothing consistent about 1 tab. It can have every size, so people's brains have to adapt every time reading code that is not within their personal configured editor. – Toxiro Jun 05 '22 at 11:30
  • @o0'. Obviously tab is the cleaner solution, but since it has an inconsistent width, it is not usable when many users have to work together. – Toxiro Jun 05 '22 at 11:33
  • @Toxiro tab is consistent: 1 tab is 1 tab is 1 tab. Spaces are inconsistent. – o0'. Jul 10 '22 at 09:23
  • @o0'. Sorry, but are you really interested in a discussion here? I gave you a lot of arguments why it is inconsistent and you just say it is consistent without any explanation and without taking my arguments into account... – Toxiro Jul 11 '22 at 10:14
  • @o0'. 1 tab is 1 tab. Yes, and one route is one route, but that does not make the length of a route consistent neither does that argument make the length of a tab consistent. – Toxiro Jul 11 '22 at 10:16
33

The reason for spaces is that tabs are optional. Spaces are the actual lowest-common denominator in punctuation.

Every decent text editor has a "replace tabs with spaces" and many people use this. But not always.

While some text editors might replace a run of spaces with a tab, this is really rare.

Bottom Line. You can't go wrong with spaces. You might go wrong with tabs. So don't use tabs and reduce the risk of mistakes.

S.Lott
  • 384,516
  • 81
  • 508
  • 779
  • 25
    I would never vow to do something the wrong way just because a lot of others (people, text editors, etc.) also happen to be it the wrong way. In 2015, a text editor that doesn't handle tabs well belongs in the garbage can. – antred Nov 08 '15 at 15:13
  • 11
    "You can't go wrong with spaces. You might go wrong with tabs". I've found that to be 100% topsy-turvy incorrect. In my experience: "You can't go wrong with Tabs. You might go wrong with spaces" ... especially when sharing code. – cmroanirgo Apr 11 '17 at 06:59
  • 13
    So someone has finally said it : use spaces because it's the lowest common denominator. The same rule has gotten us to hold on to MBR, BIOS, and paper forms at government offices. Except that these actually have conceptual problems, while tabs vs spaces is a 100% stupid user problem. – Milind R Jun 18 '17 at 09:38
  • 8
    This seems to me a Argumentum ad populum: fallacious argument that concludes that a proposition is true because many or most people believe it. Because every editor can replace tabs with spaces then spaces are the right choice is a fallacy!! – Djunzu Oct 31 '17 at 15:02
32

The main problems with indentation occur when you mix tabs and spaces. Obviously this doesn't tell you which you should choose, but it is a good reason to to recommend one, even if you pick it by flipping a coin.

However, IMHO there are a few minor reasons to favour spaces over tabs:

  • Different tools. Sometimes code gets displayed outside of a programmer's editor. Eg. posted to a newsgroup or forum. Spaces generally do better than tabs here - everywhere spaces would get mangled, tabs do as well, but not vice-versa.

  • Programmers see the source differently. This is deeply subjective - its either the main benefit of tabs, or a reason to avoid them depending on which side you're on. On the plus side, developers can view the source with their preferred indentation, so a developer preferring 2-space indent can work with an 8-space developer on the same source and still see it as they like. The downside is that there are repercussions to this - some people like 8-space because it gives very visible feedback that they're too deeply nested - they may see code checked in by the 2-indenter constantly wrapping in their editor. Having every developer see the code the same way leads to more consistency wrt line lengths, and other matters too.

  • Continued line indentation. Sometimes you want to indent a line to indicate it is carried from the previous one. eg.

    def foo():
        x = some_function_with_lots_of_args(foo, bar, baz,
                                            xyzzy, blah)
    

    If using tabs, theres no way to align this for people using different tabstops in their editor without mixing spaces and tabs. This effectively kills the above benefit.

Obviously though, this is a deeply religious issue, which programming is plagued with. The most important issue is that we should choose one - even if thats not the one you favour. Sometimes I think that the biggest advantage of significant indentation is that at least we're spared brace placement flamewars.

Also worth reading is this article by Jamie Zawinski on the issue.

Brian
  • 116,865
  • 28
  • 107
  • 112
  • 4
    The alignment is trivial though. I simply use the brackets like a block and indent each arg. Also, in your example you very well can use spaces since you're inside an argument list and you can stack as many spaces in there as you want. – Soviut May 16 '09 at 17:44
  • 4
    @Soviut: If you indent with spaces, the alignment is messed up as soon as it's viewed with a different tab size. The only way to preserve it is to use tabs to the indent level, and then spaces for the rest - ie mix spaces and tabs, which leads to its own problems. – Brian May 16 '09 at 20:19
  • 1
    Yeah, which is why i tend to just use the python convention of block indenting on my arguments anyways. Sure, they may not line up with the open brace, but its still clear which line or command they belong to. JQuery syntax operates on a similar principle. – Soviut May 17 '09 at 04:20
  • If I need to add arguments to a function, I generally do one of three things, depending on the project / situation: just keep going, letting the text wrap (I see text wrap as something the text editor should be handling, not the programmer); enter the arguments that would make it wrap on a new line with one extra level of indentation than the text immediately after it (so if the function definition starts at 0 indent, the body would be 1-level indent, so the remaining arguments would go at 2-level indent); or, best of all... – David Stone Nov 29 '11 at 18:16
  • If I need to wrap the arguments of my function, I often rewrite my function so I don't need to put that many arguments in. If I need a whole bunch of arguments, my function may be doing too much, or I may benefit from grouping similar arguments into a class. Perhaps the problem can just be solved with smart defaults for the function. If I'm passing 10 arguments into a function, I consider that a sign to look very closely at what it's doing. – David Stone Nov 29 '11 at 18:17
  • 4
    @Brian: I don't see how that leads to any problems. It's exactly the right way, tabs for indentation, spaces for alignment. It's not at all the same as mixing spaces and tabs for __indentation__. – antred Feb 04 '15 at 17:28
  • 1
    @antred: It doesn't matter what you *call* it, that's still mixing tabs and spaces, which is explicitly forbidden by PEP8. Python 3 even treats that as an error. – coredumperror Apr 27 '16 at 19:02
  • 4
    @CoreDumpError Uh no, it certainly doesn't. I know that because Python 3 never complains about any of my scripts, and I use tabs for indentation / spaces to align all the damned time. Also, PEP8 cannot "forbid" anything, as it's merely a recommendation (and a harebrained one, in my opinion). – antred Apr 27 '16 at 23:41
31

The problem with tabs is that they are invisible, and people can never agree on the width of tabs. When you mix tabs and spaces, and you set tabstops at something other than Python (which uses tabstops every 8 spaces) you will be seeing the code in a different layout than Python sees it. And because the layout determines blocks, you will be seeing different logic. It leads to subtle bugs.

If you insist on defying PEP 8 and using tabs -- or worse, mixing tabs and spaces -- at least always run python with the '-tt' argument, which makes inconsistent indentation (sometimes a tab, sometimes a space for the same indentation level) an error. Also, if possible, set your editor to display tabs differently. But really, the best approach is not to use tabs, period.

Thomas Wouters
  • 130,178
  • 23
  • 148
  • 122
  • 58
    It's true that tabs are invisible and people can't agree on the width of tabs. But the same is also true for spaces. When you mix tabs and spaces, things go wrong. But why are you blaming that situation on tabs and not spaces? – Jim Sep 23 '08 at 14:01
  • 51
    No, the same is not true for spaces. People can agree on the width of spaces. – Rafał Dowgird Sep 23 '08 at 14:49
  • 1
    Indeed: we're not talking about the width of *indentation*, but how wide the tab *displays*. A space is always the same width, a tab by itself is always a consistent width, but the combination of tabs mixed with spaces is not. – Thomas Wouters Sep 23 '08 at 14:53
  • 34
    A single space may always be the same width, but indentation with spaces is not always the same width. I fail to see how agreeing to use tabs n spaces wide is any different to agreeing to indent with n spaces. – Jim Sep 23 '08 at 14:57
  • 2
    Here's why: with tabwidth at 4 spaces, four spaces followed by a tab will be as wide as 2 tabs. With tabwidth at 8 spaces, which Python uses, the same four spaces followed by a tab will only be as wide as *one* tab. Mix the two styles in a block and the code will do the wrong thing. – Thomas Wouters Sep 23 '08 at 16:37
  • 31
    Yes, I know the problems mixing the two can cause. What I don't understand is why some people blame that on tabs. The problem is mixing them, not tabs in particular. You could solve the problem by replacing tabs with spaces, but you could also solve the problem by replacing spaces with tabs. – Jim Sep 23 '08 at 18:09
  • 3
    The problem is your editor might use tabs 8 wide, and mine might use 6 wide. That means when we share code things get messed up. The reason everyone uses spaces is because everyone else uses spaces. It may seem arbitrary, and it is. But it's still a very, very good reason. – Harley Holcombe Sep 23 '08 at 22:52
  • 10
    Yes, I might use 8-wide tab indentation and you might use 6-width tab indentation. Just like I might use 8 spaces to indent, while you might use 6 spaces to indent. In *both* cases, you have to agree on indentation width. Once more, they are equal, yet tabs get the blame. Why? – Jim Sep 24 '08 at 02:46
  • 81
    And no, if I use 8-wide tabs and you use 6-wide tabs, and we share code, it doesn't get messed up. It's all just a single tab to the Python interpreter. – Jim Sep 24 '08 at 02:47
  • 2
    Tabs get picked on because it's tabs that people don't see. People see spaces. People in general don't expect tabs. Tabs lose because they show like spaces, and spaces don't show like tabs. It's not something you can change, and it's silly to get worked up about it. Don't use tabs and it'll be fine. – Thomas Wouters Sep 24 '08 at 14:13
  • 16
    What do you mean by, "people see spaces"? Spaces to indent are just as visible/invisible as tabs to indent. I'm not getting worked up about it, I'm just looking for an explanation that makes sense. – Jim Sep 24 '08 at 15:13
  • There isn't an explanation other than "this is what happens". It's not about the theoretical value or absolute preference. It's what happens when you mix tabs and spaces, and which people blame. It's about how people, when they see something indented by tabs, do not see tabs, but see spaces. – Thomas Wouters Sep 24 '08 at 22:43
  • 9
    So in other words, you're saying "don't use tabs", and then blaming everybody else except you when you realise you can't back that statement up? – Jim Sep 25 '08 at 21:34
  • 3
    No. I'm explaining why you mustn't use tabs: because it confuses *other people*. And quite frequently yourself and your editor. This is not a matter of opinion, this is a very frequent problem among many people using tabs. Which is why PEP-8, the styleguide for the standard library, forbids tabs. – Thomas Wouters Sep 25 '08 at 23:17
  • 12
    Have you even *read* PEP-8? It *doesn't* forbid tabs. And don't tell me what confuses me and my editor. You know what, I give up. You are clearly attempting to push your own preference, and then, when you are questioned on it, passing the buck. – Jim Sep 26 '08 at 00:55
  • 3
    The short comment size requires me to not repeat what I said before, so I can't elaborate every point in every comment. Please *read* what I have *actually stated* in this entire thread, because you clearly misunderstand it all, and resort to ad hominem attacks instead. – Thomas Wouters Sep 26 '08 at 08:30
  • 11
    read this http://kymair.com/archives/45 - I like tabs, because they allow configuration for personal views and they're easier to type; 1 tab == 1 indention. Maybie there should be a new character, I call spabs :D – Joschua Jun 11 '10 at 23:53
  • [read this](http://stackoverflow.com/questions/120926/why-does-python-pep-8-strongly-recommend-spaces-over-tabs-for-indentation/6965294#6965294) -- tabs are not bad -- but spaces have an advantage – treecoder Aug 06 '11 at 06:56
  • 9
    Not agreeing on the width of tabs is a _feature_ not a bug; you can choose the level of indentation you prefer without modifying the code at all. – Jack Aidley Feb 01 '13 at 16:58
  • Sublime Text says "Hi" for tou people claiming tabs are invisible. – This company is turning evil. Feb 03 '14 at 19:10
  • 1
    ["Use 4 spaces per indentation level."](http://legacy.python.org/dev/peps/pep-0008/#indentation) Doesn't this (from PEP 8) contradict "Python uses tabstops every 8 spaces"? – Carl G Apr 21 '14 at 16:19
  • 6
    @ThomasWouters If there are people out there who call themselves programmers yet are confused by the concept of using tabs for indentation, maybe they should have picked a different profession. – antred Jun 16 '15 at 21:44
  • 1
    @Jim : vertical alignment in code is important beyond the first visible char in each line. Many programmers align comments, function args, etc. With tabs, only leading white-space guarantees visual consistency. If you use spaces, you're always vertically consistent across all users, preference settings and apps as long as you use a fixed-width (monospace) font. – arielf Oct 16 '15 at 23:06
  • 2
    @arielf The conversation is about indentation, not alignment. Indentation and alignment are two separate things. You should not use tabs for alignment, only indentation. – Jim Oct 20 '15 at 11:03
  • @Jim that's the point I was trying to convey. If you use spaces for indentation you never run into an issue with alignment, not so with tabs. What would you suggest to use when there's an alignment need? Compromise on the 'always tabs' argument? Use leading tabs and trailing spaces (which doesn't work)? It's a slippery slope from here. – arielf Oct 20 '15 at 17:06
  • 3
    @arielf If you use tabs for indentation you never run into an issue with alignment either. Use tabs for indentation, use spaces for alignment. It works just fine for everybody regardless of indentation width preference. – Jim Oct 21 '15 at 10:48
18

Note that the use of tabs confuses another aspect of PEP 8:

Limit all lines to a maximum of 79 characters.

Let's say, hypothetically, that you use a tab width of 2 and I use a tab width of 8. You write all your code so your longest lines reach 79 characters, then I start to work on your file. Now I've got hard-to-read code because (as the PEP states):

The default wrapping in most tools disrupts the visual structure of the code

If we all use 4 spaces, it's ALWAYS the same. Anyone whose editor can support an 80 character width can comfortably read the code. Note: The 80 character limit is a holy war in and of itself, so let's not start that here.

Any non-sucky editor should have an option to use spaces as if they were tabs (both inserting and deleting), so that really shouldn't be a valid argument.

Thane Brimhall
  • 9,256
  • 7
  • 36
  • 50
11

The answer to the question is: PEP-8 wants to make a recommendation and has decided that since spaces are more popular it will strongly recommend spaces over tabs.


Notes on PEP-8

PEP-8 says 'Use 4 spaces per indentation level.'
Its clear that this is the standard recommendation.

'For really old code that you don't want to mess up, you can continue to use 8-space tabs.'
Its clear that there are SOME circumstances when tabs can be used.

'Never mix tabs and spaces.'
This is a clear prohibition of mixing - I think we all agree on this. Python can detect this and often chokes. Using the -tt argument makes this an explicit error.

'The most popular way of indenting Python is with spaces only. The second-most popular way is with tabs only.'
This clearly states that both are used. Just to be ultra-clear: You should still never mix spaces and tabs in same file.

'For new projects, spaces-only are strongly recommended over tabs.'
This is a clear recommendation, and a strong one, but not a prohibition of tabs.


I can't find a good answer to my own question in PEP-8. I use tabs, which I have used historically in other languages. Python accepts source with exclusive use of tabs. That's good enough for me.

I thought I would have a go at working with spaces. In my editor, I configured a file type to use spaces exclusively and so it inserts 4 spaces if I press tab. If I press tab too many times, I have to delete the spaces! Arrgh! Four times as many deletes as tabs! My editor can't tell that I'm using 4 spaces for indents (although AN editor might be able to do this) and obviously insists on deleting the spaces one at a time.

Couldn't Python be told to consider tabs to be n spaces when its reading indentations? If we could agree on 4 spaces per indentation and 4 spaces per tab and allow Python to accept this, then there would be no problems.
We should find win-win solutions to problems.

quamrana
  • 37,849
  • 12
  • 53
  • 71
  • 1
    What editor are you using? Most I've used have an option to dedent on backspace (emacs behaves this way for instance), regardless of the implementation of the indenting. – Brian Sep 27 '08 at 17:36
  • You're right - I don't see an option to dedent on backspace, but you can probably deal with it using shift-tab, or reduce indent (ctrl-shift-i by default) instead. – Brian Sep 27 '08 at 20:15
  • I'm just trying PyScripter which seems loads better at using spaces when you press tab and removing them in 4's when you press backspace. – quamrana Aug 23 '09 at 19:11
  • 33
    **"I have to delete the spaces! Arrgh! Four times as many deletes as tabs!"** - This is the single reason I use tabs for everything, and why I think people who use spaces are insane. :) I've never had problems, except when I paste something in from the web that uses spaces. Then a simple find-replace fixes that. – Aphex Jan 13 '11 at 15:43
4

I've always used tabs in my code. That said, I've recently found a reason to use spaces: When developing on my Nokia N900 internet tablet, I now had a keyboard without a tab key. This forced me to either copy and paste tabs or re-write my code with spaces. I've run into the same problem with other phones. Granted, this is not a standard use of Python, but something to keep in mind.

Skyler
  • 909
  • 1
  • 10
  • 24
2

Since python relies on indentation in order to recognize program structure, a clear way to identify identation is required. This is the reason to pick either spaces or tabs.

However, python also has a strong philosophy of only having one way to do things, therefore there should be an official recommendation for one way to do indentation.

Both spaces and tabs pose unique challenges for an editor to handle as indentation. The handling of tabs themselves is not uniform across editors or even user settings. Since spaces are not configurable, they pose the more logical choice as they guarantee that the outcome will look everywhere the same.

Florian Bösch
  • 27,420
  • 11
  • 48
  • 53
  • 11
    And since every editor also may chose its color scheme, do you think they should mandate also which color scheme to use? – o0'. Jan 19 '12 at 14:55
  • 11
    Yes but doesn't this inconsistency actually make more sense? Because it is simply a matter of visual preference. If I prefer a larger "looking" indent in my editor I can set my tabs to be 8 spaces, if I prefer less I can set it to 2. That way the code, without actually changing the formatting, better suits the individual who is observing it. – dennmat Apr 22 '13 at 13:32
  • 10
    I agree with dennmat- If I visually prefer 2 spaces, and Guido visually prefers 4 spaces, then the logical choice is to use tab indentation. – Sepero Jun 06 '13 at 10:21
2

JWZ says it best:

When [people are] reading code, and when they're done writing new code, they care about how many screen columns by which the code tends to indent when a new scope (or sexpr, or whatever) opens...

...My opinion is that the best way to solve the technical issues is to mandate that the ASCII #9 TAB character never appear in disk files: program your editor to expand TABs to an appropriate number of spaces before writing the lines to disk...

...This assumes that you never use tabs in places where they are actually significant, like in string or character constants, but I never do that: when it matters that it is a tab, I always use '\t' instead.

Community
  • 1
  • 1
Mark Cidade
  • 98,437
  • 31
  • 224
  • 236
  • 10
    I'd do the contrary: tabs have a semantic meaning for indentation, so it is more sensed to have tabs stored and spaces displayed. The user could chose a formatting style and the editor would expand tabs accordingly. – AkiRoss Sep 27 '13 at 10:35
  • 1
    You still have the problem of mixed tabs and spaces, as well as one author using 1 column per tab and indenting 4+ times, which would look crazy in a text editor set to display each tab character as 4 columns wide. Tabs for indentation make the most sense in a variable-width text editor, like a word processor using proportionally-spaced fonts. Not so much with a fixed-width text editor. – Mark Cidade Sep 27 '13 at 16:04
  • 2
    No, I was meaning that a text editor should be able to parse the language grammar and *understand* when a tabulation is occurring, so that tabs could be used as only formatting mean and there would be no need of using spaces for indentation. "tab" is not required to have a fixed width, and I find generally shameful that with today's techniques (e.g. machine learning), formatting is still a problem for programmers. Everything should be automated and it should be automated and transparent. – AkiRoss Sep 28 '13 at 11:32
  • I don't see how it would be able to understand that. – Mark Cidade Sep 29 '13 at 00:20
0

The most significant advantage I can tell of spaces over tabs is that a lot of programmers and projects use a set number of columns for the source code, and if someone commits a change with their tabstop set to 2 spaces and the project uses 4 spaces as the tabstop the long lines are going to be too long for other people's editor window. I agree that tabs are easier to work with but I think spaces are easier for collaboration, which is important on a large open source project like Python.

sirwart
  • 2,444
  • 2
  • 15
  • 7
  • 3
    this is wrong: this happens only if you mix tabs and spaces, and you would equally solve it by forcing everyone to use tabs instead of spaces. – o0'. Jan 19 '12 at 14:54
0

You can have your cake and eat it to. Set your editor to expand tabs into spaces automatically.

(That would be :set expandtab in Vim.)

Rod Daunoravicius
  • 2,488
  • 1
  • 16
  • 10
0

Besides all the other reasons already named (consistency, never mixing spaces and tabs etc) I believe there are a few more reasons for the 4 spaces convention to note. These only apply to Python (and maybe other languages where indentation has meaning). Tabs may be nicer in other languages, depending on individual preferences.

  1. If an editor doesn't show tabs (which happens, depending on the configuration, in quite a few), another author might assume that your code uses 4 spaces, b/c almost all of the Python code being publicly available does; if that same editor happens to have a tab width of 4, nasty things may happen - at least, that poor person will lose time over an indentation issue that would have been very easy to avoid by sticking to the convention. So for me, the number one reason is to avoid bugs with consistency.

  2. Reframing the question of which is better, tabs or spaces, one should ask which the advantages of tabs are; I've seen plenty posts praising tabs, but few compelling arguments for them; good editors like emacs, vi(m), kate, ... do proper indentation depending on the semantics of your code - even without tabs; the same editors can easily be configured to unindent on backspace etc.

  3. Some people have very strong preferences when it comes to their freedom in deciding the look/ layout of code; others value consistency over this freedom. Python drastically reduces this freedom by dictating that indentation is used for blocks etc. This may be seen as a bug or a feature, but it sort of comes with choosing Python. Personally, I like this consistency - when starting to code on a new project, at least the layout is close to what I'm used to, so it's fairly easy to read. Almost always.

  4. Using spaces for indentation allows "layout tricks" that may facilitate to comprehend code; some examples of these are listed in PEP8; eg.

    foo = long_function_name(var_one, var_two,
                             var_three, var_four)
    
    # the same for lists
    a_long_list = [1,
                   2,
                   # ...
                   79]
    
    # or dictionaries
    a_dict = {"a_key": "a_value",
              "another_key": "another_value"}
    

    Of course, the above can also be written nicely as

    foo = long_function_name(
        var_one, var_two,
        var_three, var_four)
    
    # the same for lists
    a_long_list = [
        1,
        2,
        # ...
        79]
    
    # or dictionaries
    a_dict = {
        "a_key": "a_value",
        "another_key": "another_value"}
    

    However, the latter takes more lines of code and less lines are sometimes argued to be better (b/c you get more on a single screen). But if you like alignment, spaces (preferably assisted by a good editor) give you, in a sense, more freedom in Python than tabs. [Well, I guess some editors allow you to do the same w/ tabs ;) - but with spaces, all of them do...]

  5. Coming back to the same argument that everybody else makes - PEP 8 dictates (ok, strongly recommends) spaces. If coming to a project that uses tabs only, of course, you have little choice. But because of the establishment of the PEP 8 conventions, almost all Python programmers are used to this style. This makes it sooooo much easier to find a consensus on a style that is accepted by most programmers... and having individuals agree on style might be very hard otherwise.

  6. Tools that help enforcing style are usually aware of PEP 8 without extra effort. That's not a great reason, but it's just nice to have things work ~out of the box.

0

My guess is that most the linux text editors make defaults look ridiculously large by default. I can't think of any other good reason to use spaces over tabs.

-1

The universal problem with tabs is that they can be represented differently in different environment.
In a given editor, a tab might be 8 spaces or it might be 2.
In some editors, you can control this, while in others you can't.

Another issue with tabs is how they are represented in printed output. I believe most printers interpret a tab as 8 spaces.

With spaces, there is no doubt. Everything will line up as the author intended.

Benoit
  • 37,894
  • 24
  • 81
  • 116
  • 15
    Another one who has fundamentally misunderstood the tab... get a mechanical typewriter and play with it for a while, really! 1 tab is not equal to 8 spaces! it is equal to _up_to_8_spaces_! otoh: with proportional fonts, tabs are the _only_ way to guarantee alignment. –  Oct 10 '08 at 14:14
  • 5
    "In a given editor, a tab might be 8 spaces or it might be 2". If I like 4-spaces and my friend likes 8-spaces or 2-spaces or 3-spaces or, etc. Then we can both agree on tabs because (being dediciated _indentation_ characters,) the editor knows what they are and can display them accordingly. I see the code with 4-space wide indents, you see it with 8-space wide indents, our weird friend uses his 3-spaces, and everything's cool. The circumstances (especially in Python!) where the tab width itself would ever matter are so rare that even space-proponents rarely bring them up. – JamesTheAwesomeDude Mar 27 '15 at 00:31
  • using tabs (which can have different spacings depending on the editor) are less of a problem when they are at the beginning of a line. however it is problematic when they are in the middle of a line of code as they align the next character to a multiple of the tab spacing, they do not insert a fixed spacing. the space of a tab when placed after another statement can be anything up to the tab spacing. so with a tab space of 8, a tab could result in 1,2,3,4,5,6,7 or 8 characters spacing to the next character on the line. This can make some code unreadable. – EmbeddedSoftwareEngineer Oct 14 '21 at 21:09
-1

Well, I would say that there is not such "recommendation" in the PEP 8. It is stated as a recommendation since they won't prohibit you to write tabs but since code must be written in the most standardized way, use spaces we must.

That said, if I were the one to write the standard guide, I would recommend tabs since they are a modern and more practical way to indent code.

Finally, I'll stress, I am not encouraging anybody to use tabs, instead, I am saying that all of us should use spaces as stated in the style guide.

Maxinfamily
  • 13
  • 1
  • 4
-1

On the discussion between Jim and Thomas Wouters in the comments.

The issue was... since the width of tabs and spaces both can vary -- and since programmers can't agree on either width -- why is it that tabs bear the blame.

I agree with Jim on that -- tabs are NOT evil in and of themselves. But there is a problem...

With spaces I can control how "MY OWN CODE" looks in EVERY editor in the world. If I use 4 spaces -- then no matter what editor you open my code in, it will have the same distance from the left margin. With tabs I am at the mercy of the tab-width setting for the editor -- even for MY OWN CODE. And I don't like that.

So while it is true that even spaces can't guarantee consistency -- they at least afford you more control over the look of your OWN code everywhere -- something that tabs can't.

I think it's NOT the consistency in the programmers writing the code -- but the consistency in editors showing that code -- that spaces make easier to achieve (and impose).

Community
  • 1
  • 1
treecoder
  • 43,129
  • 22
  • 67
  • 91
  • 10
    You’re “at the mercy of the tab-width setting for the editor”? If your editor doesn’t let you set the tab‐width you want, you may be using notepad.exe – user137369 Apr 14 '13 at 12:59
  • 5
    @zigg That’s absolutely irrelevant to the argument, since he (she?) is talking specifically about **his/her own code** (that information is even bolded, in italics, and all caps). Nowhere to the discussion is sharing code relevant. – user137369 Aug 04 '13 at 19:26
  • 2
    Editors aren't the only tools to view code with. There are also diffs, tracebacks, Github and other web pages, and so on that will all choose some tab width out of your control (probably 8). – RemcoGerlich Nov 23 '15 at 22:22
  • 2
    I see your point. You indeed control how everyone sees your code (regarding indentation). Your next step is to control the font type and coloring that everyone will use to see your code. After that, you are prepared to dominate the world itself and not only code editors!! – Djunzu Oct 31 '17 at 15:15