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 tell me what a TabError in my code?

+4
source share
1 answer

TL DR: never backtrack Python code with TAB


In Python 2, the interpretation of TAB looks as if it were converted to spaces using 8-spatial tabs ; that is, each TAB extends the indent by 1 to 8 spaces, so the resulting indent is divided by 8.

However, this does not apply to Python 3 anymore - in Python 3 mixing spaces and tabs - if not always SyntaxError - not very good do - simplified [*], tabs correspond only to tabs and spaces that correspond only to other spaces in the indent; that is, an indented block with TAB SPACE SPACE may contain an indented block with TAB SPACE SPACE TAB , but if it contains TAB TAB , the indentation error will be considered, although the block will apparently expand further.

This is why mixing tabs and spaces or using tabs in general for indentation in reads is considered very bad practice in Python.


[*] Well, I was lying there - it's not so simple. Python 3 really allows you to indent a block with TAB TAB TAB TAB inside an indented block TAB SPACE SPACE . From the Python documentation :

2.1.8. Indentation

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

The tabs are replaced (from left to right) with one to eight spaces in such a way that the total number of characters before and including the replacement is a multiple of eight (this should be the same rule that Unix uses). The total number of spaces preceding the first non-blank character then determines the indentation of the lines. Indentation cannot be divided into several physical lines using a backslash; a space before the first backslash defines the indent.

Indentation is rejected as inconsistent if the source file mixes the tabs and spaces so that the value depends on the value of the bookmark in spaces ; in this case, a TabError is created.

Since TAB TAB TAB TAB indentation is deeper than TAB SPACE SPACE , even if the tabs were one-dimensional, this indentation is indeed allowed. However, it is so mysterious that you can also forget about it and just believe what I said above ... or even assume that Python does not allow TAB to be indented at all.

+10
source

Source: https://habr.com/ru/post/1496970/


All Articles