40

I decided, that I learn a bit of Python. The first introduction says that it uses indentation to group statements. While the best habit is clearly to use just one of these what happens if I interchange them? How many spaces will be considered equal to one tab? Or will it fail to work at all if tabs and spaces are mixed?

Lukas
  • 2,232
  • 3
  • 21
  • 34

7 Answers7

44

Spaces are not treated as equivalent to tab. A line indented with a tab is at a different indentation from a line indented with 1, 2, 4 or 8 spaces.

Proof by counter-example (erroneous, or, at best, limited - tab != 4 spaces):

x = 1
if x == 1:
^Iprint "fff\n"
    print "yyy\n"

The '^I' shows a TAB. When run through Python 2.5, I get the error:

  File "xx.py", line 4
    print "yyy\n"
                ^
IndentationError: unindent does not match any outer indentation level

Thus showing that in Python 2.5, tabs are not equal to spaces (and in particular not equal to 4 spaces).


Oops - embarrassing; my proof by counter-example shows that tabs are not equivalent to 4 spaces. As Alex Martelli points out in a comment, in Python 2, tabs are equivalent to 8 spaces, and adapting the example with a tab and 8 spaces shows that this is indeed the case.

x = 1
if x != 1:
^Iprint "x is not 1\n"
        print "y is unset\n"

In Python 2, this code works, printing nothing.


In Python 3, the rules are slightly different (as noted by Antti Haapala). Compare:

Python 2 says:

First, tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight (this is intended to be the same rule as used by Unix). The total number of spaces preceding the first non-blank character then determines the line’s indentation. Indentation cannot be split over multiple physical lines using backslashes; the whitespace up to the first backslash determines the indentation.

Python 3 says:

Tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight (this is intended to be the same rule as used by Unix). The total number of spaces preceding the first non-blank character then determines the line’s indentation. Indentation cannot be split over multiple physical lines using backslashes; the whitespace up to the first backslash determines the indentation.

(Apart from the opening word "First," these are identical.)

Python 3 adds an extra paragraph:

Indentation is rejected as inconsistent if a source file mixes tabs and spaces in a way that makes the meaning dependent on the worth of a tab in spaces; a TabError is raised in that case.

This means that the TAB vs 8-space example that worked in Python 2 would generate a TabError in Python 3. It is best — necessary in Python 3 — to ensure that the sequence of characters making up the indentation on each line in a block is identical. PEP8 says 'use 4 spaces per indentation level'. (Google's coding standards say 'use 2 spaces'.)

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • @JonathanLeffler yes, the addendum starting from "it is followed by a paragraph": means in particular that the size of tabs doesn't matter, one tab matches only one tab in indentation; one space matches only one space in indentation. – Antti Haapala -- Слава Україні Feb 24 '17 at 19:24
  • Only, that the lines are displayed in tracebacks indented by 8 spaces. – Antti Haapala -- Слава Україні Feb 24 '17 at 19:24
  • The python3 "extra paragraph" quoted in the answer may sound nice, but it doesn't actually seem to work that way. A counterexample can be seen at http://pastebin.com/q6F8Fj0h (but you'll have to remove the CR before each LF). It would indent one way with tab stops at 1, and another way at tab stops 2. But python 3.6 and python 3.7 don't reject it; it runs just fine. – Bill Evans at Mariposa Nov 03 '19 at 22:42
22

Follow PEP 8 for Python style. PEP 8 says: Indentation

Use 4 spaces per indentation level.

For really old code that you don't want to mess up, you can continue to use 8-space tabs.

Tabs or Spaces?

Never mix tabs and spaces.

The most popular way of indenting Python is with spaces only. The second-most popular way is with tabs only. Code indented with a mixture of tabs and spaces should be converted to using spaces exclusively. When invoking the Python command line interpreter with the -t option, it issues warnings about code that illegally mixes tabs and spaces. When using -tt these warnings become errors. These options are highly recommended!

Klaus
  • 538
  • 8
  • 26
Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412
13

In Python 2, the interpretation of TAB is as if it is converted to spaces using 8-space tab stops (as provided by previous answers already); that is that each TAB furthers the indentation by 1 to 8 spaces so that the resulting indentation is divisible by 8.

However this does not apply to Python 3 anymore - in Python 3 mixing of spaces and tabs are always an error - tabs only match tabs and spaces only match other spaces in indentation; that is a block indented with TABSPACESPACE might contain a block indented with TABSPACESPACETAB, but not one indented with TABTABTAB, it would be considered an indentation error, even though the block would seemingly extend further:

Indentation is rejected as inconsistent if a source file mixes tabs and spaces in a way that makes the meaning dependent on the worth of a tab in spaces; a TabError is raised in that case.

I.e. the algorithm works as follows:

  • if both number of tabs and number of spaces matches the previous line (no matter the order), then this line belongs to the same block with the previous line

  • if the number of one of (tabs, spaces) is greater than on the previous line and number of the other is at least equal to those on the previous line, this is an indented block

  • the tuple (tabs, spaces) matches an indent from a previous block - this dedents to that block

  • otherwise an IndentationError or a TabError is raised.

This is why mixing tabs and spaces, or even using tabs for indentation at all would be considered a very bad practice in Python.

  • TAB SPACE SPACE doesn't match SPACE SPACE TAB, it's an IndentationError. The line "if both number of tabs and number of spaces matches the previous line (no matter the order), then this line belongs to the same block" is incorrect; order matters because tabs advance to the next multiple of 8. Python3 doesn't change this, it just disallows substituting tabs with the equivalent number of spaces. – Nick Matteo May 12 '21 at 15:48
  • @NickMatteo not sure if I made a mistake 7 years ago or if Python 3 was even *more* broken then, but even now, **8** spaces + tab matches tab + **8** spaces – Antti Haapala -- Слава Україні May 12 '21 at 21:20
  • discussion here: https://bugs.python.org/issue24260 – Antti Haapala -- Слава Україні May 12 '21 at 21:21
6

Just don't interchange them :)
Set your IDE/editor to input 4 spaces upon pressing "tab" and you are good to go.

shylent
  • 10,076
  • 6
  • 38
  • 55
5

I would recommend that you go through PEP 8 which is the 'official' Python style guide for Python code. It covers (among other things) the use of tabs/spaces.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Noufal Ibrahim
  • 71,383
  • 13
  • 135
  • 169
2

Four spaces are one tab (in my setup), but as far as I know, they are not interchanged. You can use either spaces or tabs, not both.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Amirshk
  • 8,170
  • 2
  • 35
  • 64
-2

I believe that the tab character should simply never appear in source code under any circumstances. There's no advantage to it and it's an endless source of tiny errors. - use a character string with \t if you need a tab, it has the advantage that it's self-documenting.

Here's the classic article about tabs vs spaces - I use a variant of jwz's elisp in my own .emacs file.

(I confess to personally breaking with PEP 8 by using only 2 characters' indentation - 4 characters is a lot when your lines are only 80 characters...)

Tom Swirly
  • 2,740
  • 1
  • 28
  • 44
  • 1
    [Douglas Crockford agrees](https://www.youtube.com/watch?v=MBWAP_8zxaM) (08 min 49 secs). – Peter Mortensen Jul 03 '18 at 03:01
  • Nice to be back up to zero on this comment, which for a while was my most downvoted comment here. :-) – Tom Swirly Jul 04 '18 at 08:30
  • 1
    I don't think this is an actual answer to the question by SO standards. It's completely subjective and doesn't address the question of what happens when you mix tabs/spaces. – ChrisGS Feb 08 '22 at 16:51