【问题标题】:Proper indentation for the second line of a multiline code with parentheses带括号的多行代码第二行的正确缩进
【发布时间】:2018-08-03 15:26:02
【问题描述】:

带括号/逗号的多行 Python 代码的第二行推荐的标准缩进是什么?

  1. 无缩进:

    plt.imshow(np.transpose(Z), extent=[0,4.2,0,48000], cmap='jet',
    vmin=-100, vmax=0, origin='lowest', aspect='auto')
    
  2. 4 个空格缩进:

    plt.imshow(np.transpose(Z), extent=[0,4.2,0,48000], cmap='jet',
        vmin=-100, vmax=0, origin='lowest', aspect='auto')
    
  3. 标识到(:

    plt.imshow(np.transpose(Z), extent=[0,4.2,0,48000], cmap='jet',
               vmin=-100, vmax=0, origin='lowest', aspect='auto')
    
  4. 另一种解决方案?

这是链接:Proper indentation for Python multiline strings 但这里的问题是特定于带括号/逗号的多行,而不是字符串。

【问题讨论】:

  • 您可以将其发布为@FHTMitchell 的答案吗? (我不知道这个 8 空格规则!)

标签: python indentation multiline parentheses pep8


【解决方案1】:

如果你关注PEP8, Indentation,那么我会选择选项 3:

# Aligned with opening delimiter.
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

我个人非常喜欢这个选项,因为它可以让我自己和其他人更清楚地阅读内容。但如果您在一家公司工作,请务必查看公司标准(每个公司可能有自己的偏好)。

【讨论】:

  • 转到此链接上的代码布局部分:legacy.python.org/dev/peps/pep-0008 并检查# Aligned with opening delimiter.
  • @Bazingaa 你是对的!为了完整起见,我将其包含在答案中。
【解决方案2】:

我永远不会使用选项 1 或 2,它们可能会产生误导。 3 如果你有足够的空间很好。

There is one more option which can be used when option 3 leaves too little room or when splitting lines using a backslash (PyCharm defaults to this in the latter situation), two indentation levels (8 spaces)

plt.imshow(np.transpose(Z), extent=[0,4.2,0,48000], cmap='jet',
        vmin=-100, vmax=0, origin='lowest', aspect='auto')

def grouper_with_prev(iterable: _Iin[_T], n: int, include_first: bool = False) \
        -> _Iout[_t.Tuple[_T, ...]]:
    """
    Returns n size chuncks of iterable with the previous n-1 elements

    """
    ...

这没有选项 1 和 2 的混淆,使您在做什么一目了然。

【讨论】:

  • 同意。 3 看起来最好,但有时没有空间。
猜你喜欢
  • 2020-09-07
  • 1970-01-01
  • 2021-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-31
  • 2019-01-24
相关资源
最近更新 更多