Question

I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes.

How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?

Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?

Was it helpful?

Solution

Because PEP-8 tells us to use spaces.

OTHER TIPS

Tired of chasing after indentation typos ( 8 spaces ? no, 7 oops 9 ... ) I switched my sources to 'tabs only'.

1 tab == 1 indent level, full stop

The point is: if you want to display the indentation as 4, 8 or pi / 12 character width, just change the settings in your text editor, don't mess with the code.

(Personally, I use 4 char width tab... but some would prefer 3 or 8 space, or even use variable width fonts.)

Thus spake the Lord: Thou shalt indent with four spaces. No more, no less. Four shall be the number of spaces thou shalt indent, and the number of thy indenting shall be four. Eight shalt thou not indent, nor either indent thou two, excepting that thou then proceed to four. Tabs are right out. -- Georg Brandl

USE AN EDITOR THAT DISPLAYS TAB CHARACTERS (all whitespace, for that matter). You're programming, not writing an article.

I use tabs. There's no room for a one-space error in the tabs (if you can see them). The problem IS that people use different editors, and the only common thing in the world is: tab==indent, as above. Some bloke comes in with the tab key set to the wrong number of spaces or does it manually and makes a mess. TABs and use a real editor. (This isn't just contrary to the PEP, it's about C/C++ and other whitespace-agnostic languages too).

/steps down from soapbox

My main reason for using tabs over spaces is the backspace key. If I'm on a line and I want to backspace-remove an indentation on just that one line I have to hit backspace 4x if it were spaces; whereas, I only need to hit it once if it's a tab.

I will continue to use tabs because—like was stated before—it's easier to convert from tabs to spaces, but not the other way around.

I'm thinking I want to write a simple program that converts code with spaces into code with tabs, because I freaking hate spaces. They drive me up the wall!

Oh! And using the arrow keys to navigate left and right is always a pain in the ass when it's spaces.

UPDATE: Sublime Text 3 now deletes a full soft tab with the backspace key; though, arrow-key navigation is still tedious.

Tabs vs. Spaces for Indentation

UPDATE: I now use vscode and also wrote a TabSanity extension for it to solve backspace, delete and arrow-key navigation.

TabSanity Extension in Action

The most "pythonic" way is to use 4 spaces per indentation level. The Python interpreter will however recognize spaces or tabs. The only gottcha is you must never mix spaces and tabs, pick one or the other. That said, the specification recommends spaces, most developers use spaces, so unless you have a really good reason not to, I'd say go with spaces.

So far as I can tell, here are the pros and cons of tabs vs spaces.

Pros of tabs:

  • Fewer keystrokes required to indent, unindent, and traverse the indentation. (Even if your IDE has some space-indentation cleverness it will never be as good as tabs.)
  • Different programmers can use different tab display sizes as they wish.
  • You can never have the cursor "inside" an indentation character. For example say you are copying some lines, with tabs you can click vaguely near the start of a line to start your selection and you will get all of the first tab. With spaces you're likely to miss the first space character unless you hit the tiny target between it and the margin. Similarly to remove an indentation from a line, most editors don't handle pressing backspace well if your cursor is in the middle of a four-space indentation character. It will usually remove one space. With tabs it works as expected.
  • Consistency with other languages, so you don't have to set your editor up to use, e.g. tabs for C++/Java and spaces for Python.
  • Wrong indentations can be more obvious (i.e. an extra tab is much larger than an extra space).

Cons of tabs:

  • Most Python programmers use spaces so you would be going against convention.
  • Using spaces to align multi-line statements is easier than using tabs. You could use tabs-for-indentation, spaces-for-alignment, but it seems a bit risky in Python!

There are some non-issues that are overblown by some people:

  1. You might get stray spaces in tabbed indentation that screws things up: Virtually all IDEs/editors support visualising whitespace, and it's almost as likely that you'll get stray tabs in space indentations! I can't see this being a common error anyway. Besides, most indentation errors will be caught by Python, and good IDEs should be able to highlight different indentations.

  2. You can't align things easily with tabs: This is true if you're going for character-perfect alignment, but PEP-8 recommends against this, and Python doesn't play well with multi-line statements anyway.

  3. People have difference settings for tab display size in their editors so your code will look different in different places: Yeah, that's actually a beneficial feature of tabs.

I've started out using spaces to be consistent with other Python code, but to be honest it is frustrating enough that I will probably change back to tabs. A lot depends on the capabilities of your IDE, but in my experience no amount of IDE support for space indentation is as good as just using tabs.

So unless you really don't like being inconsistent with most (presumably not all!) Python code, use tabs and turn on whitespace visualisation and indentation highlighting (if available). The biggest reason for me is ease of selection and the (fairly significant IMO) reduction in keystrokes. Some conventions are stupid.

Update: I have discovered that there is one editor in the whole world (excluding nonsense like Vim) that properly supports spaces as indentation: Atom. It has an option called "atomic tabstops" that makes 4 spaces behave as if it were a tab in all respects (except being able to resize it). Sadly Atom is quite a slow and bloated editor, but this is a great feature and if you are forced to use spaces it might be a good option. Hopefully one day other editors will start to support it. Here's the issue for VSCode.

I recently came across an article titled Python: Myths about Indentation which discusses this and related questions. The article has good reasons for recommending the use of spaces when writing Python code, but there is certainly room for disagreement.

I believe it's true that most Python programmers use spaces only.

Use an editor that allows you to insert spaces up to the tabstop when you press the TAB key, instead of inserting a \t character. And then forget about it.

You CAN mix tabs and spaces... BUT a tab is considered to be the same indentation as 8 spaces, so unless your editor is set up to consider a tab to be 8 spaces you're asking for trouble when mixing them.

The only inconvenience I experience with using spaces instead of tabs is that you cannot easily remove an indentation level; you have to remove four spaces instead of just one tab.

Tabs rule. Same argument for nested loops and you want to bring the outer loop "back" 1 level. Tip: If you want to convert old space-riddled python code into tabs use the TabOut utility available as an executable on http://www.textpad.com/add-ons/.

I feel very strongly that whatever the historical convention, tabs are simply a better choice and should replace spaces in every future line of Python code written. Like kicking out an incompetent tyrant. My rationale for this is: simplicty as a core value. Use two or maybe four characters for the semantic task of one? There's no justification beyond tradition, IMO.

Editor-to-editor mistake occurs when you have mixed indentation within a file. This arises as follows: a block of code is indented with 4 spaces, and then one indentation level "in", it is indented with tabs. Now the heathen who did this (mixing tabs and spaces) had it so his tabs are also 4 spaces, so he sees no problems, and Python sees no problems.

Now our victim comes along later, and he has his tabs set to 8 spaces. Now our victims thinks the code looks all whacked, and fixes it by removing one level of indentation, which now makes the code look like it is still 2 levels of indentation, but is really one level. At this point all hell breaks loose.

The lesson here is that you should never, ever, mix tabs and spaces. If you keep to this, then it is easy to reindent your code into spaces or tabs, regardless of which you personally use. The best way to ensure you don't mix tabs and spaces is to always run python with -tt, which will produce an error when tabs and spaces are mixed.

As for tabs and spaces, I personally use tabs so separate indentation from appearance - it is much easier to change the appearance of code when it is indented with tabs than it is with spaces. I know this runs contrary to what 99% of Python programmers do, but that is my personal preference, and it is easy in any case to convert a tabbed file to a spaced one. The reverse is not always true, since you can accidentally whack out 4 spaces in strings, etc.

When I was first learning Python, I was put off a little by the idea of significant white space, as most languages to use it are inflexible. That said, I was impressed by Python's ability to understand a variety of indentation styles. When considering what style to use for a new project, I think it is important to keep two things in mind.

  1. First, it is important to understand how Python interprets indentation. Bryan Oakley mentioned the possibility of off-by-one errors when using tabs, but this actually isn't possible with the default interpreter settings. There is a better explanation of this in Learning Python, from O'Reilly Media.

Basically, there is a variable (which can be changed by including a comment at the top of a source file # tab-width: ) that defines the tab width. When Python encounters a tab, it increases the indentation distance to the next multiple of tab-width. Thus if a space followed by a tab is entered along the left of the file, the next multiple of tab-width is 8. If a tab by itself is entered, the same thing happens.

In this way, it is safe, if your editor is configured properly, to use tabs, and even to mix tabs and spaces. As long as you set your editor's tab stops to the same width as the Python tab-width declaration (or 8 if it is absent). It is generally a bad idea to use an editor with a tab width of other than 8 spaces, unless you specify the tab-width in the file.

  1. Second, much of the syntactic design of Python is to encourage code readability and consistent style between programmers on the same project. That said, the question becomes, for any particular project, what will make the code the most readable by the people working on the project. Certainly it is a good idea to keep a consistent indentation style, but depending on the platform and the editor used by the project, a different style may make sense for different projects. If there is no compelling reason to not conform to PEP 8, then it makes sense to do so, because it will conform to what people expect.

I have encountered projects that use a mix of tabs and spaces successfully. Basically spaces are used to indent small sections, where the fact that it is in an indented section is relatively unimportant; while tabs are used to draw the reader's attention to a large structural feature. For example, classes begin with a tab, which simple conditional checks inside a function use two spaces.

Tabs are also useful when dealing with large blocks of text indented multiple levels. When you drop out of 3-4 levels of indentation, it is far easier to line up with the proper tab than it is to line up with the proper number of spaces. If a project doesn't use the PEP 8 recommended style, it is probably best to write a style guide into a file somewhere so that the indentation pattern remains consistent and other people can read explicitly how to configure their editor to match.

Also, Python 2.x has an option -t to issue warnings about mixed tabs and spaces and -tt to issue an error. This only applied to mixed tabs and spaces inside the same scope. Python 3 assumes -tt and so far as I've found, there is no way to disable that check.

I'm primarily a C++ programmer, but sometimes my projects include small amounts of Python. I use tabs to indent my C++ code. This means that I have three options here:

  1. Use tabs in C++ and spaces in Python. This allows my C++ files to remain as they are and I follow the PEP-8 recommendation, but I am inconsistent within my project.
  2. Change my C++ code to use spaces. This allows all of my files within my project to be consistent, and I follow the PEP-8 recommendation, but requires me to go back and change all of my C++ files. I consider this a bad thing because I prefer tabs.
  3. Use tabs in my C++ code and Python code. This makes my entire project consistent and allows me to use my preferred indentation style: tabs. The downside is that I am not following the PEP-8 standard.

For my projects, I generally go with option 3.

Experience and PEP-8 both clearly conclude that mixing spaces and TABs is to be avoided. If you want to mix them you have to visualize whitespace in the IDE - but then you loose the advantage of Python's indentation making scopes easily visible. Visualizing whitespace in an IDE clutters the display.

If it's either TABs or spaces, then it must be spaces for a simple reason: One can switch almost all IDEs and text editors to automatically replace tabs with spaces, but the opposite is not true.

Even though there are IDEs that can automatically convert leading spaces in a line to tabs, this will eventually lead to having a mixture of tabs and spaces. Consider multi line statements such as function calls with lots of parameters or doc strings. While "ascii-art" is also to be avoided it may easily happen by accident that a single space is left over after the leading tabs.

Other answers brought several arguments in favor of tabs:

  • Hitting TAB is more efficiently. Of course this is true, but all text editors allow to immediately insert the wanted number of spaces when a tab key is pressed
  • Indenting/Dedenting is easier when just having to remove one tab instead of 2/3/4/8 spaces. True, but most text editors allow to do this automatically anyway: Block select, indent/dedent are basic functionality of a programming editor, like commenting/uncommenting. If a text editor hasn't got this implemented, it should at least have an easy to use macro functionality with which one can achieve the same thing.
  • Different programmers like different indenting widths. That is true, and a clear advantage of using TABs only. The problem is interaction with other individuals and/or teams. For this to work in the real world, everybody would have to agree on all using TABs only. Since this has not happened, it does not work anyway. In a real world scenario there's a set of coding guidelines that a project agrees upon anyway, and the method of indentation is certainly one of them - even in other programming languages where the implications are "only" on a visual level.

Imho, the main point that most (if not all) answers are missing here is the interaction between teams or individuals, especially in scenarios where the list of participants is not know at the start. When code meets code either all have to use tabs or all have to use spaces. It cannot be mixed without eventually running into functionality problems. People are not perfect. Tools are not perfect. That's why imho we should not use TABs at all.

No answer is complete without the link that Greg provided in his answer already: Python: Myths about Indentation

Everyone has different preferences on how much code should be indented. Let's say you share code with someone and he or she has different preferences regarding indentation. If the indentations are in tabs, your friend can always just change the tab width in their editor settings. However, if the indentations are in spaces, your friend will actually have to change the source code if he or she want to set it to their preference. Then when you get your friend's changes, you may decide to change it back to your preference. In this case, you will either have to deal with the tedium of changing indentation levels back and forth, or one person must adopt the other's preferences in indentation level. If both you and your friend use tabs, the fact that you have different preferences is a non-issue, as you can each see different indentation levels while the code remains unchanged. That is why, in my opinion, tabs are better than spaces for indentation in all programming languages.

There's a scenario in which tabs simply don't work, namely: depending on the coding style you are using, you might need to indent some lines of code to one-space accuracy, i.e:

def foobar():
    x = some_call(arg1,
                  arg2)

In that case, using purely tabs will not work at all; using tabs for main indent and spaces for sub-indent will work but will violate the hard rule of not mixing the two.

This will not be the case however when using a coding style/conventions document that avoids situations like in the above code example.

The problem with using spaces instead of tabs is the file size becomes so incredibly large... For example, a 500 KB space-indented file could be reduced to 200 KB when swapping spaces for tabs which is why I always use tabs.

Smaller file-size means faster loading, compiling, execution (in some cases), etc.

To me, there is no point to using spaces, but if someone uses an editor which has issues with tabs, then they can replace "\t" with " " or " " or whatever...

In addition to all the arguments already listed, I find this one fairly important (from Myths about indentation):

Also, tabs often get destroyed or wrongly converted during copy&paste operations, or when a piece of source code is inserted into a web page or other kind of markup code.

Another argument (strongly environment-specific, though) against tabs is that they are sometimes missing on phone keyboards. This could probably be remedied by installing an alternative keyboard, where possible.

An argument for tabs which no one seemed to have mentioned yet is that 1 tab is 1 character (0x09, 1 byte in the file), while 4 spaces are 4 characters (4 times 0x20, 4 bytes in the file); thus, using spaces results in a 4x waste of space.

To conclude this incoherent list of arguments, I would like to cite Tim Peters answer in the Issue 7012: Tabs is better than spaces for indentation:

The Python "spaces only" standard is for distributed code. Years of early experience taught us beyond doubt that tabs caused endless problems for shared code (...)

How does that make a difference?

Some editors are configured by default to replace a single tab character with a set number of space characters, but some are not. If everyone uses spaces, this difference in default editor settings can be ignored.

Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?

Yes, there are other valid reasons as pointed out by many answers before me. "PEP-8" says so, however, is NOT one of those reasons. This comes from the self perpetuating myth that PEP-8 is the coding standard for all Python code, when in fact it's just the coding standard for the standard set of Python libraries. Some claim that PEP-8 is widely accepted, and some claim that most Python programmers use spaces instead of tabs. I would like to ask for proofs of these claims, as the number of votes on this site CLEARLY shows that tabs are preferred by the masses. I find it quite unfortunate that you have accepted "PEP8 says so" as the answer to your question, when in fact there are many other answers that actually explains the relative advantages and disadvantages of spaces and tabs.

Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?

It depends, and the answer to this final question is where I thought I could actually add some value to this thread. IMHO, regardless of the language being used, the best coding standard to use depends on the situation that you are in:

  • If you started to work on an already existing code base: don't be difficult, follow the existing coding standard
  • If a team is starting on a new project from scratch: discuss, decide on a coding standard in the beginning as a team, and stick to it
  • If you are going solo: do whatever that makes you feel the happiest and the most productive

So which situation do you fall under?

Finally to make my stance clear, for my own solo projects, I use tabs because tabs make more sense to me, and I am more productive with tabs.

I believe there is a solution to have both:

  1. Compatibility with PEP-8 and using spaces
  2. Convenience of using tab instead of 4 spaces

In Notepad++, go to "preferences"--> "tab settings" and choose "Python" from the list on the right. Then make sure "tab size: 4", and check the box "replace [tab] by space". In this case, you can simply use the tab key to indent, but Notepad++ actually transform that to 4 spaces for you.

This is PEP 8 as of July 2017:

Enter image description here

It seems this statement doesn't leave room for any other choice.

But this isn't solely what PEP 8 tells us, few lines later:

Enter image description here

In the above, the first statement expresses a preference for spaces, and the second statement acknowledges the existence of code indented with tabs and this preference for some coders.

So: PEP 8 is tab indentation tolerant. It doesn't tolerate tab and space mixed for indentation though, which, since indentation itself is mandatory, is understandable.

It may be worth mentioning that Google's Python coding style also follows the 4-space rule.

There are other various arguments and justifications in favor of either tabs or 4-space.

If you work in a company which enforce PEP 8, or regularly share your code with others who follow PEP 8, then common sense dictates 4-space. I am (was, maybe) used to tabs from C/C++. But with a properly set IDE, the difference becomes minimal.

Use spaces in place of tabs, for the sole reason that you will make more money :)

Ref.: Developers Who Use Spaces Make More Money Than Those Who Use Tabs (Stack Overflow blog post).

So here I am reading all the responses and wondering how I can comply with PEP-8 without the annoyance of pounding my backspace button repeatedly just to remove indentation, and I look down at my Logitech gaming keyboard with all its fancy macro buttons and a light bulb lights up in my head.

I opened Logitech's software, defined a couple of macros for the buttons right next to the tab button, and the problem is solved.

One button adds four spaces, and the other does backspace four times. Amazing. Just amazing. So easy to hit the buttons with my pinky, too.

See, check this out:" "<-- four spaces! With one push of a button! If I could show you the backspaces I would do that too. Go get a Logitech G105 keyboard and all your problems will go away!

I'm just starting out but I find it much easier to use tabs than spaces, and do not understand the PEP-8 advocation of spaces only. Sublime Text 2 does a great job of visualizing tabs with the off-white vertical, dotted line and while there are cases of me mixing a space or two to line up elements of a list or dictionary, I have not experienced a situation where that would be detrimental thing.

I love tabs but it is somehow incompatible with another rule I like: the 80 column limit.

If one chooses 4 spaces tabs and inserts 10 tabs, then there is space left for 40 characters to fulfill the 80 column limit. If another coder prefers 8 spaces tabs, the same line will appear as 120 characters long and will not appear as a valid 80 columns line!

If you want to define a 80 column limit, then you have to choose a length for a tab. In this case having x spaces or a tab of length x does not really make a difference.

Edit: related thread: Maintaining Maximum Line Length When Using Tabs Instead of Spaces?

I think one of the main benefits to using spaces is that you remove variability in how your source code is rendered across the plethora of external tools which have to interact with the source beyond one's choice editor and whatever settings they've configured it in.

As some concrete examples consider the rendering of Python docstrings in a tooltip in Visual Studio Code, or in a diff tool like Beyond Compare or WinMerge, performance or code coverage tools, etc. Basically all these various other interfacing tooling can each have different settings for how tabs are interpreted and it can be annoying and at times disorienting to find things vastly different or pushed way off screen among the toolsets you may dive in and out of.

In a nutshell you define alignment in the source rather than wrangling down a uniform configuration for the suite of tools in your arsenal. Spaces are strictly interpreted in a monospace font to give reliable and consistent alignment across the full span of tooling due to the font's definition, not a third party's tab rendering implementation/configuration.

Another angle to this is in copying leading tabs source to run at a terminal where the tab character can trigger an inadvertent tab completion. For example, if you copy the following Python source (tabs used as indentation),

cmd_create_db = '''CREATE TABLE test (
    Col1 INTEGER,
    Col2 INTEGER,
    Col3 TEXT)'''

you may see something like follows (seen at Visual Studio Code's integrated terminal)...

>>> cmd_create_db = '''CREATE TABLE test (
... .DS_StoreCol1 INTEGER,
... .DS_StoreCol2 INTEGER,
... .DS_StoreCol3 TEXT)'''
>>> cmd_create_db
'CREATE TABLE test (\n.DS_StoreCol1 INTEGER,\n.DS_StoreCol2 INTEGER,\n.DS_StoreCol3 TEXT)'

(Aside: I had wondered if this observation of consistency across tooling is a mark of a discriminating mind of a sharp developer looking to order the world that may indicate a hint at the salary difference found on Stack Overflow.)

I use two space indentation and an editor (kwrite) that inserts spaces instead of tabs when I hit the tab key.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top