我知道我应该将 Python 代码保持在 79 列,但是如何缩进连续行呢?

发布于 2024-09-13 17:37:50 字数 548 浏览 8 评论 0原文

我知道 Python 的标准行宽约定是 79 个字符。我知道行可以通过多种方式继续,例如自动字符串连接、括号和反斜杠。似乎没有明确定义的是溢出文本应该如何格式化。我要把它一直推回到第 1 栏吗?到原始行开始的那一栏?到括号的开头(如果适用)?例如,假设我有这样的内容:


        self.someLongAttributeName = {'someLongKeyName':'someLongValueName',
                                      'anotherLongKeyName':'anotherLongValueName'}

假设我上面使用的格式符合 79 个字符的限制,那么第二行的缩进是否正确?

现在假设如上所示的第一行是 > 79 个字符。在这种情况下,情况应该如何?

注意:我知道很多人不同意 79 个字符的约定。虽然我尊重这个问题的每一方都有很多优点和缺点,但这场辩论与我的问题无关。我问的是如何遵循惯例,而不是我是否应该遵循惯例,所以请不要在回复中宣扬放弃惯例的好处。谢谢。 =)

I am aware that the standard Python convention for line width is 79 characters. I know lines can be continued in a number of ways, such as automatic string concatenation, parentheses, and the backslash. What does not seem to be as clearly defined is how exactly the overflowing text should be formatted. Do I push it all the way back to col 1? To the col where the original line starts? To the start of the parentheses (if applicable)? For example, say I have something like this:


        self.someLongAttributeName = {'someLongKeyName':'someLongValueName',
                                      'anotherLongKeyName':'anotherLongValueName'}

Supposing that the format I used above would fit the 79 character limit, is the indentation of the second line correct?

Now suppose that the first line as shown above is > 79 characters. How should things look in that case?

NOTE: I know that a lot of people disagree with the 79-character convention. While I respect that there are a lot of pros and cons to each side of the issue, this debate is not relevant to my question. I am asking how to follow the convention, not whether or not I should, so please do not espouse the advantages of abandoning it in your reply. Thanks. =)

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

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

发布评论

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

评论(7

云淡月浅 2024-09-20 17:37:50

假设我上面使用的格式符合 79 个字符的限制,那么第二行的缩进是否正确?

是的,这就是 PEP 8 在示例中的显示方式:

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)

但是当左括号/大括号已经接近第 79 列时,我通常只是利用这一点:

Two good reasons to break a particular rule:

(1) When applying the rule would make the code less readable, even for
    someone who is used to reading code that follows the rules.
[...]

并执行类似

self.some_long_attribute_name = {
    'someLongKeyName': 'someLongValueName',
    'anotherLongKeyName': 'anotherLongValueName'
}

或的操作

long_object_name.do_something_with_long_name(
    long_expression_returning_is_first_arg,
    long_expression_returning_is_second_arg
)

Supposing that the format I used above would fit the 79 character limit, is the indentation of the second line correct?

Yes, that's how PEP 8 shows it in 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)

But when the opening parenthesis/brace is already close to the 79th column, I usually just exploit this:

Two good reasons to break a particular rule:

(1) When applying the rule would make the code less readable, even for
    someone who is used to reading code that follows the rules.
[...]

And do something like

self.some_long_attribute_name = {
    'someLongKeyName': 'someLongValueName',
    'anotherLongKeyName': 'anotherLongValueName'
}

or

long_object_name.do_something_with_long_name(
    long_expression_returning_is_first_arg,
    long_expression_returning_is_second_arg
)
陌路终见情 2024-09-20 17:37:50

http://www.python.org/dev/peps/pep-0008/< /a>
请参阅最大行长度

将所有行限制为最多 79 行
字符。

周围还有很多设备
限制为 80 个字符
线路;另外,将窗口限制为 80
字符使得有可能拥有
几个并排的窗口。这
此类设备上的默认换行
破坏了视觉结构
代码,使得更难
理解。因此,请限制
所有行最多 79
人物。对于流动的长块
文本(文档字符串或注释),
将长度限制为 72 个字符
推荐。

长包裹的首选方式
lines 是通过使用 Python 隐含的 line
括号内继续,
括号和大括号。如果有需要的话,
你可以添加一对额外的
表达式两边有括号,但是
有时使用反斜杠看起来
更好的。确保缩进
适当地继续行。这
休息的首选地点
二元运算符是
运算符之后,而不是之前。一些例子:

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)

http://www.python.org/dev/peps/pep-0008/
See Maximum Line Length

Limit all lines to a maximum of 79
characters.

There are still many devices around
that are limited to 80 character
lines; plus, limiting windows to 80
characters makes it possible to have
several windows side-by-side. The
default wrapping on such devices
disrupts the visual structure of the
code, making it more difficult to
understand. Therefore, please limit
all lines to a maximum of 79
characters. For flowing long blocks
of text (docstrings or comments),
limiting the length to 72 characters
is recommended.

The preferred way of wrapping long
lines is by using Pythons implied line
continuation inside parentheses,
brackets and braces. If necessary,
you can add an extra pair of
parentheses around an expression, but
sometimes using a backslash looks
better. 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-09-20 17:37:50

即使在 Python 之外,我也一直对 C 代码执行此操作,这样我就可以(如 PEP 所说)在监视器上并排打开 2-3 个文件并查看所有文件。

反斜杠运算符 \ 在 Python 和 C 中用作行继续运算符,但我更喜欢尝试使用括号 () 或大括号 {} 将行分组 (或者 Python 列表的方括号 []),无论什么都是最方便的。如果我决定要在一个长连续块的中间添加另一行,我不想担心任何愚蠢的“陷阱”:缺少 \ 或更糟糕的是,在\ 使延续无效。

对于长条件语句,我喜欢双缩进,这样更明显的是该代码不是新块的一部分。

if (somethingLong == x or
        somethingElse == y or
        somethingOld == z or
        x < y < z or
        doIt.now()):
    pass

Even beyond Python, I do this all the time for my C code so I can (as the PEP says) have 2-3 files open on a monitor side-by-side and see them all.

The backslash operator \ works as a line continuation operator in Python as well as C, but I prefer to try to group lines with parenthesis () or braces {} (or brackets [] for Python lists), whatever is most convenient. If I decide I want to add another line in the middle of a long continuing block, I don't want to worry about any stupid 'gotchas': missing a \ or worse, some errant space after the \ invalidating the continuation.

For long conditionals, I like to double-indent so it's more obvious that that code isn't part of the new block.

if (somethingLong == x or
        somethingElse == y or
        somethingOld == z or
        x < y < z or
        doIt.now()):
    pass
仙气飘飘 2024-09-20 17:37:50

PEP 8中有一个例子:

class Rectangle(Blob):

    def __init__(self, width, height,
        # more code
        Blob.__init__(self, width, height,
                      color, emphasis, highlight)

在我看来,这表明你的例子是正确的。我认为你应该在打开括号( { )后打破示例的第一行,如下所示:

    self.someLongAttributeName = {
                 'someLongKeyName':'someLongValueName',
                 'anotherLongKeyName':'anotherLongValueName'
    }

如果它太长。我不知道它是否是“pythonic”,但应该是熟悉和可读的。

In PEP 8 there is an example:

class Rectangle(Blob):

    def __init__(self, width, height,
        # more code
        Blob.__init__(self, width, height,
                      color, emphasis, highlight)

Which, to my eye, suggests that your example is correct. I think you should break first line of the example after opening bracket ( { ) like so:

    self.someLongAttributeName = {
                 'someLongKeyName':'someLongValueName',
                 'anotherLongKeyName':'anotherLongValueName'
    }

if it is too long. I don't know if it is 'pythonic', but should be familiar and readable.

笑叹一世浮沉 2024-09-20 17:37:50

长包裹的首选方式
行是通过使用Python的隐含
线
括号、方括号和大括号内的延续。如果有需要的话,

可以在表达式周围添加一对额外的括号,但是
有时
使用反斜杠看起来更好。确保缩进续行
适当地。破解二进制文件的首选位置
运算符是
运算符之后,而不是在其之前。

The preferred way of wrapping long
lines is by using Python's implied
line
continuation inside parentheses, brackets and braces. If necessary,
you
can add an extra pair of parentheses around an expression, but
sometimes
using a backslash looks better. Make sure to indent the continued line
appropriately. The preferred place to break around a binary
operator is
after the operator, not before it.

沉溺在你眼里的海 2024-09-20 17:37:50

我很确定这个问题之前已经在这里得到了回答,但我现在找不到它了。

简短的答案是 PEP8 不包括如何格式化对象文字,除了冒号之前应该有零个空格,之后有一个空格。

我这样做:

obj = {
     'foo': 1,
     'bar': 2,
     'bas': 3,
}

I was pretty sure this was answered here before, but I can't find it now so..

The short answer is that PEP8 does not cover how to format object literals, other than that colons should have zero spaces before and one space after.

I do them like this:

obj = {
     'foo': 1,
     'bar': 2,
     'bas': 3,
}
浅笑轻吟梦一曲 2024-09-20 17:37:50

这样做的好技巧也是这样:

my_long_string="""
This are
many lines of text
"""

a = [a in my_long_string.split() if a]

有些人喜欢在打开三重引号后使用 \,而不是过滤空行,但我真的很讨厌那些野兽。

对于你的具体例子,我同意cji。

Good trick is also to do like this:

my_long_string="""
This are
many lines of text
"""

a = [a in my_long_string.split() if a]

Some people prefer to use \ after opening triple quote and not filter empty lines, but I really hate those beasts.

For your particular example I agree with cji.

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