python - PEP 8 是否需要函数参数中的运算符周围有空格?

标签 python coding-style pep8

我有这个代码:

some_list = range(a, b+1)

使用 pep8 plugin for vim 检查我的编码风格后,我收到了这个警告:

missing whitespace around operator

似乎为了符合 PEP 8 我应该改写这个?

some_list = range(a, b + 1)

但我读过PEP 8 - Style Guide for Python Code几次,就是找不到适用于上述警告的规则。

所以我想知道:当使用 PEP-8 样式时,函数参数中的运算符(+、-、*、/等)周围是否需要空格?

最佳答案

当你在 2013 年问的时候,你的 Vim 插件是错误的……但在 2010 年,当它被创作时是正确的。 PEP 8 有 changed on several occasions ,您的问题的答案也发生了变化。

最初,PEP 8 包含以下短语:

Use spaces around arithmetic operators

那个规则下,

range(a, b+1)

明显错误,应该写成

range(a, b + 1)

这就是 pycodestyle 的规则(Python linter,以前称为 pep8.py,提问者的 Vim plugin 在后台使用)实现了好几年。

但是,this was changed 2012 年 4 月。直截了当的语言被替换为更加模糊的建议:

If operators with different priorities are used, consider adding whitespace around the operators with the lowest priority(ies). Use your own judgment; however, never use more than one space, and always have the same amount of whitespace on both sides of a binary operator.

令人困惑的是,说明此规则的示例最初保持不变(因此与散文相矛盾)。这是 eventually fixed, but not very well ,并且这些例子仍然令人困惑,似乎暗示了比散文更严格和更少主观的规则。

仍有一条规则要求在某些特定运算符周围使用空格:

Always surround these binary operators with a single space on either side: assignment ( = ), augmented assignment ( += , -= etc.), comparisons ( == , < , > , != , <> , <= , >= , in , not in , is , is not ), Booleans ( and , or , not ).

但请注意,此规则明确说明它引用了哪些运算符和算术运算符,如 + 不在列表中。

因此,当前形式的 PEP没有规定您是否应该在 + 周围使用空格。运算符(或其他算术运算符,如 */** )。你可以自由地“使用你自己的判断”

顺便说一下,pycodestyle linter changed its behaviour in late 2012 to reflect the change in the PEP ,将有关在运算符周围使用空格的规则分为两个错误代码,E225(用于在 PEP 8 仍然需要空格周围的运算符周围使用空格失败)和 E226(用于未能在算术运算符周围使用空格),默认情况下会被忽略。考虑到他看到的错误,这里的提问者一定是在 2013 年提出这个问题时使用了稍微过时的 linter 版本。

关于python - PEP 8 是否需要函数参数中的运算符周围有空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18171560/

相关文章:

python - 在 python 中正确使用 isinstance

c - 我应该单独初始化变量而不是声明它们吗?

html - 幻灯片放映的样式问题

c# - 正确使用 Timer 类

python - 如何将函数应用于两列 Pandas 数据框

python - TFLite 的硬刷操作

python - else 和 finally 在异常处理中的目的

python - Pycharm的代码风格检查: ignore/switch off specific rules

python - 函数定义的 Pythonic 顺序是什么?

python - 如何格式化 flake8 的 Django 设置文件