Python:使用 4 个空格进行缩进。 为什么?

发布于 2024-07-27 18:47:46 字数 1433 浏览 6 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

月亮邮递员 2024-08-03 18:47:47

政治公众人物不是你的老板。 如果它已经一致地缩进 2 个空格,则没有理由更改所有代码以符合它。 如果你真的认为这很重要,你可以继续关注它,但坦率地说,我不这么认为。 你最好遵循任何能让你(和你的同事)在阅读和写作方面最舒适的惯例。

The PEP isn't the boss of you. If it's already consistently 2-space indented, there's no reason to change all your code to conform to it. You could follow it going forward if you really think it's that vital, but, frankly, I don't. You're better off going with whatever convention provides you (and your coworkers) the most comfort both in reading and writing.

淡笑忘祈一世凡恋 2024-08-03 18:47:47

任何像样的编辑器(emacs、vim)都会为你抽象出这一切废话。 它同样适用于空格或制表符,并且可以配置为使用任意数量的空格(或制表符的任意数量的空格宽度)。 它还可以在不同格式之间进行转换,而不会太麻烦(请参阅 vim 中的 :retab 命令)。

如果您尝试批量转换源格式,我建议您查看 缩进 实用程序。

也就是说,我无法抗拒回答另一个问题...我的偏好一直是选项卡,因为它绕过了整个问题,每个人都可以查看源代码,并设置他们认为合适的宽度。 当您使用对转换没有帮助的编辑器时,输入的内容也会少得多。 至于 2 与 4 空间,这纯粹是装饰性的。

Any decent editor (emacs, vim) will abstract this whole nonsense out for you. It will work equally well with spaces or tabs, and it can be configured to use any number of spaces (or any number of space-widths for a tab character). It can also convert between the different formats without too much trouble (see the :retab command in vim).

If you're trying to convert source formatting in bulk, I recommend you take a look at the indent utility.

That said, I can't resist answering the other question... My preference has always been for tabs, since it bypasses the whole issue and everyone can view the source code with the widths set as they see fit. It's also a lot less typing when you're working in editors that aren't helpful with converting it. As far as 2 vs 4 spaces, that's purely cosmetic.

不及他 2024-08-03 18:47:47

标识和通用编码风格标准因语言、项目而异。 采用编码风格标准的原因之一是:无论是谁编写的,代码看起来都是统一的。 这提高了项目的易读性,而且,坦率地说,它看起来更好。

采用编码风格标准时有一个无效的原因:因为您喜欢它。 编码标准的存在正是因为人们的偏好不同,如果放任自流,混乱就会随之而来,损害所有人的利益。

如果您只是为自己编写代码,而没有人会阅读,那么请继续编写您喜欢的任何代码。 否则,遵循社区公认的标准将使您的代码更容易被其他人接受。 还要记住,如果您决定将来向社区贡献代码,如果您已经习惯了他们的编码风格,那么您会更轻松。

至于更改制表符大小,有许多支持Python的源代码格式化程序,并且大多数程序员的编辑器和IDE也具有此功能。 您可能已经拥有它,只需查阅您正在使用的编辑器的文档即可。

Identation and general coding style standards vary from language to language, project to project. There is one reason for adopting a coding style standard: so that the code look uniform, no matter who wrote it. That improves legibility in the project, and, to put it bluntly, it looks better.

There is one reason that is not valid when adopting a coding style standard: because you like it. Coding standards exists precisely because people's preferences vary, and if left to their own, chaos would ensue, to the detriment of all.

If you are writing code for yourself alone, which no one will ever read, go ahead and write it whatever you like. Otherwise, following the accepted standard of your community will make your code much more agreeable to everyone else's eyes. And remember, too, that if you DO decide to contribute code to a community in the future, you'll have an easier time if you are used to their coding style already.

As for changing the tab size, there are are many source code formatters out there which support Python, and most programmer's editors and IDEs also have this capability. You probably have it already, it's just a matter of consulting the documentation for the editor you are using.

脱离于你 2024-08-03 18:47:47

还有一个原因是:当你有一些长行(超过 80 个符号)并且想要将其分成 2 时,你将只有 1 个空格来缩进,这有点令人困惑:

if code80symbolslong and somelongvariablegoeshere and somelongerthan80symbols \
 and someotherstatementhere:
  # some code inside if block
  pass

if code80symbolslong and somelongvariablegoeshere and somelongerthan80symbols \
  and someotherstatementhere:
    # some code inside if block
    pass

Also one of reasons is: when you have some long line (longer than 80 symbols) and want to split it in 2 you will have only 1 space to indent, that is a bit confusing:

if code80symbolslong and somelongvariablegoeshere and somelongerthan80symbols \
 and someotherstatementhere:
  # some code inside if block
  pass

if code80symbolslong and somelongvariablegoeshere and somelongerthan80symbols \
  and someotherstatementhere:
    # some code inside if block
    pass
青巷忧颜 2024-08-03 18:47:47

如果您是唯一处理源文件的编码人员,并且没有强制执行特定样式的编码标准,请使用您喜欢的任何方式。 就我个人而言(并且符合我们的编码标准),我使用硬选项卡,以便任何查看代码的人都可以使用自己的偏好。

要进行更改,您只需将所有行起始空间更改为两倍大即可。 有很多方法可以做到这一点; 在 Vim 文本编辑器中,我可以想到两个:第一:

:%s/^\(\s\{2}\)\+/\=repeat(' ', len(submatch(0))*2)

这是一个简单的正则表达式,它在行开头查找一对或多对空格,并用找到的空格的两倍替换它们。 它可以扩展为通过打开 vim 来执行所有文件:(

vim *.py

或等效的),然后是(未经测试):

:argdo %s/^\(\s\{2}\)\+/\=repeat(' ', len(submatch(0))*2)/ | w

或者:

" Switch to hard tabs:
:set noexpandtab
" Set the tab stop to the current setting
:set tabstop=2
" Change all spaces to tabs based on tabstop
:retab!
" Change the tab stop to the new setting
:set tabstop=4
" Go back to soft tabs
:set expandtab
" Replace all the tabs in the current file to spaces
:retab

当然,许多其他工具将提供类似的功能:如果像 sed< 这样的东西,我会感到惊讶/code>、awkperlpython 无法轻松做到这一点。

If you're the only coder working on your source file and there are no coding standards that enforce a particular style, use whatever you're comfortable with. Personally (and in line with our coding standard), I use hard tabs so that whoever is looking at the code can use their own preference.

To make a change, you simply need to change all start-of-line spaces to ones that are twice as large. There are many ways to do this; in the Vim text editor, I can think of two: firstly:

:%s/^\(\s\{2}\)\+/\=repeat(' ', len(submatch(0))*2)

This is a simple regular expression that looks for one or more pairs of spaces at the start of the line and replaces them with twice as many spaces as were found. It can be extended to do all files by opening vim with:

vim *.py

(or the equivalent), followed by (untested):

:argdo %s/^\(\s\{2}\)\+/\=repeat(' ', len(submatch(0))*2)/ | w

Alternatively:

" Switch to hard tabs:
:set noexpandtab
" Set the tab stop to the current setting
:set tabstop=2
" Change all spaces to tabs based on tabstop
:retab!
" Change the tab stop to the new setting
:set tabstop=4
" Go back to soft tabs
:set expandtab
" Replace all the tabs in the current file to spaces
:retab

Of course, many other tools will offer similar features: I would be surprised if something like sed, awk, perl or python couldn't do this very easily.

初心 2024-08-03 18:47:47

更容易直观地识别具有 4 个空格的长嵌套代码块。 节省调试时间。

It is easier to visually identify long nested code blocks with 4 spaces. Saves time when debugging.

撧情箌佬 2024-08-03 18:47:47

使用 4 个空格还是 2 个空格完全取决于您。 4个空格只是一个约定。 最重要的是,不要混合使用制表符和空格。 使用空格键

using 4 spaces or 2 spaces is entirely up to you. 4 spaces is just a convention. What is most important, don't mix tabs and spaces. Use the space bar

土豪我们做朋友吧 2024-08-03 18:47:47

原因之一是,如果缩进使用较少的空格,您将能够嵌套更多的语句(因为行长度通常限制为 80)。

现在我很确定有些人仍然不同意最多应该有多少嵌套结构。

One reason is that if you use less spaces for indentation, you will be able to nest more statements (since line length is normally restricted to 80).

Now I'm pretty sure that some people still disagree on how many nested constructs should be the maximum.

木森分化 2024-08-03 18:47:47

如果你想与其他程序员一起编写 python 代码,那么如果你使用与他们不同的缩进,就会出现问题。
大多数 Python 程序员倾向于使用 4 空格缩进。

If you want to write python code together with other programmers it becomes a problem if you use a different indention as them.
Most Python programmers tend to use 4-space indention.

誰ツ都不明白 2024-08-03 18:47:46

其他人都使用 4 个空间。 这是我遇到并接受的使用 4 个空格的唯一原因。 在我心里,我仍然想使用制表符(每个缩进 1 个缩进字符,有意义,不是吗?将缩进与其他空格分开。我不在乎制表符可以显示为不同的宽度,那语法上没有区别。最糟糕的情况是有些注释不一致!)但我已经接受了,因为整个 Python 社区都使用 4 个空格,所以我也使用 4 个空格。 这样,我可以从其他人编写的片段中组装代码,并且一切正常。

Everyone else uses 4 spaces. That is the only reason to use 4 spaces that I've come across and accepted. In my heart, I still want to use tabs (1 indent character per indent, makes sense, no? Separate indent from other whitespace. I don't care that tabs can be displayed as different widths, that makes no syntactic difference. The worst that can happen is that some of the comments don't line up. The horror!) but I've accepted that since the python community as a whole uses 4 spaces, I use 4 spaces. This way, I can assemble code from snippets others have written, and it all works.

野却迷人 2024-08-03 18:47:46

我喜欢这样一个事实:四个空格字符可以很好地缩进函数的内部代码,因为 def + 一个空格可以构成四个字符。

def·foo():
····pass

I like the fact that four space characters nicely indents the inner code of a function, because def + one space makes four characters.

def·foo():
····pass
以往的大感动 2024-08-03 18:47:46

我认为真正的问题是为什么是空格而不是制表符。

制表符显然更好:

  • 它几乎不可能出现不一致的缩进(我见过通常有 4 个空格缩进的代码,但有些部分恰好是一个空格,很难通过简单的方式来判断检查是否有 7 个或 8 个空格...制表符不会发生这种情况,除非您将制表位设置为 1 个空格)。
  • Tab 是缩进的逻辑语义表示,它允许您(和任何其他开发人员)选择显示您想要的任意数量的“空格”(或更确切地说是列),而不会造成混乱和其他人的喜好。
  • 如果您手头碰巧只有“记事本”(或其他虚拟编辑器),那么击键次数也会减少。
  • 添加和删​​除选项卡是一个对称操作。 大多数 IDE 可能会在按 Tab 键时自动插入 4 个空格,但通常在按 Backspace 时仅删除 1 个空格(取消缩进操作仍可通过 Shift-Tab 进行访问,但这是两个按键组合)或者您使用鼠标单击在缩进的中间删除一个字符。
  • 它们只占用 1 个字节而不是 4 个字节(乘以数千行,您可以节省几 KB!:p)
  • 您少了一件需要达成协议的事情,因为如果您决定使用空格,那么讨论将再次开始以选择有多少(尽管共识似乎是在四个左右)。
  • 最后:你认为自己比理查德·亨德里克斯更好吗?

空间的优点:

  • Guido 喜欢它们。
  • 您无法在此处轻松键入选项卡,它会转移焦点(尽管您可以粘贴选项卡)。

I think the real question is why spaces and not tabs.

Tabs are clearly better:

  • It makes nearly impossible to have inconsistent indentation (I've seen code that normally has 4 spaces indents, but then some parts happen to be one space off, it's difficult to tell by simple inspection if there are 7 or 8 spaces... That wouldn't happen with tabs, unless you set your tabstop to 1 space).
  • Tab is a logical semantic representation for indentation, it allows you (and any other developer) to choose to display as many "spaces" (or rather columns) you want without messing with other people's preferences.
  • It is also less keystrokes if you happen to have only "notepad" (or other dummy editor) at hand.
  • Adding and removing tabs is a symmetric operation. Most IDE's may insert automatically 4 spaces when hitting the tab key, but usually they remove just 1 space when hitting backspace (un-indent operation is still accessible as shift-tab, but that's a two key combination) or you use the mouse to click in the middle of the indentation and delete one character.
  • They take only 1 byte rather than 4 (multiply by thousands of lines and you save a few KB! :p)
  • You have one less thing to settle an agreement, because if you decide to go for spaces, then the discussion starts again to choose how many (although the consensus seems to be around four).
  • And lastly: do you think you are better than Richard Hendricks?

Advantages of spaces:

  • Guido likes them.
  • You cannot easily type a tab here, it transfers the focus (although you can paste one).
离鸿 2024-08-03 18:47:46

没有“更好”的缩进。 这是一个宗教圣战话题。 4 很好,因为它足以使缩进清晰,但又不会太多,以至于整个屏幕大部分都是空白,并且您必须水平滚动才能阅读一半的程序。

它还有一个优点,那就是成为“半选项卡”,符合“选项卡”的历史定义。

除此之外,使用你的团队喜欢的任何东西。 这就像巧克力与香草。

一种简单的切换方法是使用支持制表符和空格制表符的编辑器。 将所有前导空格制表符转换为制表符,将制表符大小设置为四,然后将前导制表符转换回空格制表符。

使用 python 脚本也很容易完成。 只需计算所有前导空格,然后将相同的数量添加到行的开头并将其写回即可。

There's no "better" indentation. It's a religious holy-war topic. Four is nice because it's enough to make the indentation clear, but not so much that your whole screen is mostly whitespace and you have to scroll horizontally to read half the program.

It also has the upside of being a "half-tab" w/r to the historical definition of a "tab."

Other than that, use whatever your group likes. It's like chocolate vs. vanilla.

An easy way to switch is to use an editor that has tab and space-tab support. Convert all your leading space-tabs to tabs, set the tab size to four, and then convert leading tabs back to space-tabs.

Pretty easy to do with a python script too. Just count all the leading spaces, then add the same amount to the beginning of the line and write it back out.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文