Python 3中的TabError

2024-05-17 04:36:06 发布

您现在位置:Python中文网/ 问答频道 /正文

提供以下翻译会话:

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

有人能告诉我代码中的TabError是什么吗?


Tags: inforifusedefstdinlinerange
1条回答
网友
1楼 · 发布于 2024-05-17 04:36:06

TL;DR:不要用选项卡缩进Python代码


在Python 2中,the interpretation of TAB is as if it is converted to spaces using 8-space tab stops;也就是说,每个TAB都将缩进进一步扩展1到8个空格,从而使结果缩进可被8整除。

但是,这不再适用于Python 3—在Python 3 mixing of spaces and tabs is - if not always a SyntaxError - not a good thing to do—simplified[*],制表符只匹配制表符,空格只匹配缩进中的其他空格;即用制表符缩进的块空格空格可能包含用制表符空格制表符缩进的块,但是,如果它包含TABTAB,则会被视为缩进错误,即使块看起来会进一步扩展。

这就是为什么在Python中混合制表符和空格,或者使用制表符缩进at被认为是非常糟糕的做法的原因。


[*]好吧,我确实躺在那里-这没那么简单。Python 3实际上允许在用TABTABTABTAB缩进的块内使用TAB空格缩进的块。从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.

由于TABTABTABTAB缩进比TAB空格空格更深,因此即使制表符只有一个空格宽,实际上也允许缩进。不过,这太神秘了,你最好还是忘记它,相信我上面说的话。。。或者甚至认为Python根本不允许使用TAB进行缩进。

相关问题 更多 >