Why does Python pep-8 strongly recommend spaces over tabs for indentation?


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.

Asked By: quamrana



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.

Answered By: Thomas Wouters

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.

Answered By: Benoit

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.

Answered By: sirwart

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.

Answered By: Florian Bösch

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.)

Answered By: Rod Daunoravicius

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.

Answered By: S.Lott

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.]

Answered By: user3850

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.

Answered By: quamrana

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.

Answered By: Brian

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.

Answered By: Mark Cidade

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.

Answered By: Soviut

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.

Answered By: nigratruo

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).

Answered By: treecoder

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.

Answered By: Skyler

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,
                   # ...
    # 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 = [
        # ...
    # 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.

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.

Answered By: Thane Brimhall

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.

Answered By: brian cronrath

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.

Answered By: Maxinfamily
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.