gpt4 book ai didi

python - 了解 Python 解释器 -t (-tt) 选项

转载 作者:太空狗 更新时间:2023-10-30 02:04:03 24 4
gpt4 key购买 nike

我想弄清楚选项 -t 和 -tt 的作用。

来自文档:

Issue a warning when a source file mixes tabs and spaces for indentation in a way that makes it depend on the worth of a tab expressed in spaces. Issue an error when the option is given twice (-tt).

我不明白,尤其是加粗的句子,这是什么意思?制表符是制表符 ('\t') 空格是空格 (' '),在 ascii 表中它们也有 2 个不同的代码。

我会举个例子来更好地解释我自己。我代码:

if True:
print('hello') # here a tab that my editor represents with 4 spaces
print('world') # here just used 4 spaces

现在这段代码,我试过了,在 Python3 和 Python2 中都不起作用,那么 -t 有什么作用?

你能给我解释一下吗?

最佳答案

用作缩进时,制表符必须被解释为等同于多个空格。 多少 空格取决于您如何配置编辑器,以及同一行中制表符之前的空格数。这是因为制表符代表跳转到下一个制表位。如果您使用 2 个空格加一个制表符,则表示跳转到第 8 列,就好像您插入了 6 个空格一样。

此外,有些人将制表位设置为相当于 4 个空格,其他人将其设置为与 8 个空格相同。然后这些人也以不同的方式在缩进中使用制表符。您可以在一个缩进级别使用 4 个空格,然后在下一个缩进级别使用 8 个空格的制表符,然后使用制表符加 4 个空格,等等。或者您可以在所有缩进级别使用制表符,将制表符大小设置为代表 4 个空格。

Python 需要处理制表符和空格的混合,然后希望您能始终如一地使用它;例如您没有先使用 4 个空格,然后 一个制表符来缩进您认为相当于 12 个空格的缩进。当您不一致时,Python 很容易出错。

-t-tt通过对所有线路进行更严格和彻底的测试,选项指出您可能在哪里犯了这个错误。

在各种制表符大小以及混合制表符和空格之间,您很容易产生令人困惑的结果,这就是 Python Style Guide (PEP 8) 的原因。强烈建议您使用空格:

Spaces are the preferred indentation method.

Tabs should be used solely to remain consistent with code that is already indented with tabs.

在 Python 3 中,混用制表符和空格进行缩进现在是错误的。

准确地说:Python 开始时假设您使用 8 个空格作为制表符。查看Indentation documentation词法分析规范的一部分:

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 2 还会寻找 Emacs 和 VI 风格的配置注释;如果分词器找到带有 tab-width: 的评论, :tabstop= , :ts=set tabsize=在其中,后跟数字,例如:

# -*- tab-width: 4 -*- (emacs)
# :tabstop=4 (vi)

或类似的变体,然后 Python 从中设置制表符大小。此支持已从 Python 3 中删除。

如果您随后混合可能不一致的制表符和空格,请使用-t , 正文 <filename>: inconsistent use of tabs and spaces in indentation写入sys.stderr一次为那个文件。如果您使用 -tt , 一个 TabError exception而是被提出。

关于python - 了解 Python 解释器 -t (-tt) 选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25054257/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com