Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TabError in Python 3

Given the following interpreter session:

>>> def func(depth,width):
...   if (depth!=0):
...     for i in range(width):
...       print(depth,i)
...       func(depth-1,width)
  File "<stdin>", line 5
    func(depth-1,width)
                  ^
TabError: inconsistent use of tabs and spaces in indentation

Can someone please tell me what is the TabError in my code?

like image 834
izac89 Avatar asked Dec 20 '22 01:12

izac89


1 Answers

TL;DR: never indent Python code with TAB


In Python 2, the interpretation of TAB is as if it is converted to spaces using 8-space tab stops; 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 is - if not always a SyntaxError - not a good thing to do - simplified [*], 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 if it instead contained TABTAB, it would be considered an indentation error, even though the block would seemingly extend further.

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


[*] Well, I did lie there - it is not that simple. Python 3 actually does allow for a block indented with TABTABTABTAB inside a block indented with TABSPACESPACE. From the Python documentation:

2.1.8. Indentation

Leading whitespace (spaces and tabs) at the beginning of a logical line is used to compute the indentation level of the line, which in turn is used to determine the grouping of statements.

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.

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.

Since TABTABTABTAB indents deeper than TABSPACESPACE even if tabs were one-space wide, that indentation is actually allowed. However, this is so arcane that you might as well want to forget it and just believe what I said above... or even believe that Python doesn't allow using TAB for indentation at all.

like image 168