在 Python 中链接方法时正确的换行样式

发布于 2024-12-12 19:49:18 字数 468 浏览 3 评论 0原文

我有一些这样的代码。休息时间应该在经期之前还是之后?

# before
my_var = somethinglikethis.where(we=do_things).where(we=domore).where(we=everdomore)

# this way
my_var = somethinglikethis.where(we=do_things) \
                          .where(we=domore) \
                          .where(we=everdomore)

# or this way
my_var = somethinglikethis.where(we=do_things). \
                           where(we=domore). \
                           where(we=everdomore)

I have some code like this. Should the break occur before the periods or after?

# before
my_var = somethinglikethis.where(we=do_things).where(we=domore).where(we=everdomore)

# this way
my_var = somethinglikethis.where(we=do_things) \
                          .where(we=domore) \
                          .where(we=everdomore)

# or this way
my_var = somethinglikethis.where(we=do_things). \
                           where(we=domore). \
                           where(we=everdomore)

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

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

发布评论

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

评论(3

撞了怀 2024-12-19 19:49:19

PEP 8 建议使用括号,这样您就不需要 \,并温和地建议在二元运算符之前而不是之后断开。因此,格式化代码的首选方式如下:

my_var = (somethinglikethis
          .where(we=do_things)
          .where(we=domore)
          .where(we=everdomore))

两个相关段落是来自 最大行长度 部分:

换行长行的首选方法是在圆括号、方括号和大括号内使用 Python 的隐式续行符。通过将表达式括在括号中,可以将长行分成多行。应优先使用这些内容而不是使用反斜杠来继续行。

...以及整个 应该在二元运算符之前还是之后换行? 部分:

应该在二元运算符之前还是之后换行?

几十年来,推荐的风格是在二元运算符之后中断。
但这会以两种方式损害可读性:操作员往往会得到
分散在屏幕上的不同列中,每个操作员都是
离开其操作数并移至上一行。这里,眼睛
必须做额外的工作来判断添加了哪些项目以及哪些是
减去:

# 否:运算符远离操作数
收入=(工资总额+
          应税利息 +
          (股息 - 合格_股息) -
          ira_扣除 -
          学生贷款利息)

为了解决这个可读性问题,数学家和他们的出版商
遵循相反的约定。唐纳德·高德纳 (Donald Knuth) 解释了传统的
他的计算机和排版系列中的规则是:“虽然公式
在一个段落中总是在二元运算和关系之后中断,
显示的公式总是在二元运算之前中断”

遵循数学传统通常会得到更多结果
可读代码:

# 是:易于将运算符与操作数匹配
收入=(工资总额
          + 应税利息
          +(股息 - 合格_股息)
          - ira_扣除
          - 学生贷款利息)

在Python代码中,允许在二进制文件之前或之后中断
运算符,只要约定在本地一致即可。对于新的
建议使用 Knuth 的代码风格。

请注意,如上面的引用所示,PEP 8 曾经给出了关于在哪里突破运算符的相反建议,如下引用以供后代使用:

换行长行的首选方法是使用 Python 的隐含行
括号、方括号和大括号内的延续。长线可以
通过将表达式括在括号中来分成多行。这些
应优先使用反斜杠来继续行。
确保适当缩进续行。首选地点
突破二元运算符是在该运算符之后,而不是在其之前。
一些例子:

类矩形(Blob):

    def __init__(自身,宽度,高度,
                 颜色='黑色',强调=无,突出显示=0):
        如果(宽度 == 0 且高度 == 0 且
            颜色 == '红色' 且强调 == '强' 或
            突出显示> 100):
            raise ValueError("对不起,你输了")
        如果宽度 == 0 且高度 == 0 且 (颜色 == '红色' 或
                                           重点是无):
            raise ValueError("我不这么认为——值为 %s, %s" %
                             (宽度、高度))
        Blob.__init__(自身,宽度,高度,
                      颜色、强调、突出)

PEP 8 recommends using parenthesis so that you don't need \, and gently suggests breaking before binary operators instead of after them. Thus, the preferred way of formatting you code is like this:

my_var = (somethinglikethis
          .where(we=do_things)
          .where(we=domore)
          .where(we=everdomore))

The two relevant passages are this one from the Maximum Line Length section:

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.

... and the entire Should a line break before or after a binary operator? section:

Should a line break before or after a binary operator?

For decades the recommended style was to break after binary operators.
But this can hurt readability in two ways: the operators tend to get
scattered across different columns on the screen, and each operator is
moved away from its operand and onto the previous line. Here, the eye
has to do extra work to tell which items are added and which are
subtracted:

# No: operators sit far away from their operands
income = (gross_wages +
          taxable_interest +
          (dividends - qualified_dividends) -
          ira_deduction -
          student_loan_interest)

To solve this readability problem, mathematicians and their publishers
follow the opposite convention. Donald Knuth explains the traditional
rule in his Computers and Typesetting series: "Although formulas
within a paragraph always break after binary operations and relations,
displayed formulas always break before binary operations"

Following the tradition from mathematics usually results in more
readable code:

# Yes: easy to match operators with operands
income = (gross_wages
          + taxable_interest
          + (dividends - qualified_dividends)
          - ira_deduction
          - student_loan_interest)

In Python code, it is permissible to break before or after a binary
operator, as long as the convention is consistent locally. For new
code Knuth's style is suggested.

Note that, as indicated in the quote above, PEP 8 used to give the opposite advice about where to break around an operator, quoted below for posterity:

The preferred way of wrapping long lines is by using Python's implied line
continuation inside parentheses, brackets and braces. Long lines can be
broken over multiple lines by wrapping expressions in parentheses. These
should be used in preference to using a backslash for line continuation.
Make sure to indent the continued line appropriately. The preferred place
to break around a binary operator is after the operator, not before it.
Some examples:

class Rectangle(Blob):

    def __init__(self, width, height,
                 color='black', emphasis=None, highlight=0):
        if (width == 0 and height == 0 and
            color == 'red' and emphasis == 'strong' or
            highlight > 100):
            raise ValueError("sorry, you lose")
        if width == 0 and height == 0 and (color == 'red' or
                                           emphasis is None):
            raise ValueError("I don't think so -- values are %s, %s" %
                             (width, height))
        Blob.__init__(self, width, height,
                      color, emphasis, highlight)
吃素的狼 2024-12-19 19:49:19

FWIW, autopep8 (带有 --aggressive 标志)产生了这个来自你的原始代码:

my_var = somethinglikethis.where(
    we=do_things).where(
    we=domore).where(
    we=everdomore)

但我同意——巴斯蒂安的解决方案更优雅。

FWIW, autopep8 (with an --aggressive flag) produced this from your original code:

my_var = somethinglikethis.where(
    we=do_things).where(
    we=domore).where(
    we=everdomore)

But I agree -- Bastien's solution is more elegant.

幼儿园老大 2024-12-19 19:49:19

做有效的事情。

另外,请查看有关 Python 中缩进神话的白皮书。可以找到这里

它开始于:

“空格在 Python 源代码中很重要。”

不,一般来说不是。只有语句的缩进级别是
重要(即语句最左边的空白)。
在其他地方,空格并不重要,可以随意使用
就像,就像任何其他语言一样。您还可以插入空行
任何地方都不包含任何内容(或仅包含任意空格)。

我希望这有帮助。

Do what works.

Also, check out this whitepaper on the myths of indentation in Python. That can be found here.

It starts out with:

"Whitespace is significant in Python source code."

No, not in general. Only the indentation level of your statements is
significant (i.e. the whitespace at the very left of your statements).
Everywhere else, whitespace is not significant and can be used as you
like, just like in any other language. You can also insert empty lines
that contain nothing (or only arbitrary whitespace) anywhere.

I hope that helps.

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