加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

用Python关闭括号

发布时间:2020-12-20 11:05:46 所属栏目:Python 来源:网络整理
导读:PEP 8有相互矛盾的代码示例(在我看来),我很好奇定位闭括号的惯例是什么. 在 indentation的顶部,它们与参数在同一条线上.在底部附近讨论定位,而是说: The closing brace/bracket/parenthesis on multiline constructs may either line up under the first no
PEP 8有相互矛盾的代码示例(在我看来),我很好奇定位闭括号的惯例是什么.
在 indentation的顶部,它们与参数在同一条线上.在底部附近讨论定位,而是说:

The closing brace/bracket/parenthesis on multiline constructs may
either line up under the first non-whitespace character of the last
line of list[…] or it may be lined up under the first character of the
line that starts the multiline construct[…]

这与上面的代码示例直接冲突.
你在哪里通常将你的结束括号放在多行语句中,你认为在惯例方面最佳做法是什么?

为了清楚起见,这里是代码示例,它们展示了这些差异.

foo = long_function_name(
    var_one,var_two,var_three,var_four)

result = some_function_that_takes_arguments(
    'a','b','c','d','e','f',)

result = some_function_that_takes_arguments(
    'a',)

解决方法

你提到的两个部分是不同的,第一部分是关于一个块后面的连续行(例如多行def或if语句),而第二部分是关于关闭效果和函数调用的括号和圆括号.在启动块时,您不希望将右括号放在下一行的开头,因为返回到原始缩进会传达块的结尾.一些看起来很奇怪的例子:

def long_function_foo(
    var_one,var_four
):
    print('This code really looks out of place')

def long_function_bar(
   var_one,var_two
):
    print('and so does this one')

PEP8允许他们称之为垂直对齐,并且各种PEP中的许多示例使用此约定,该约定已成为Python IDE的自动化功能:

def long_function_name(var_one,var_four,var_five):
    """Documentation would go here,which makes it look better."""
    print(var_one + var_two + var_three)

但我个人避免它.这是一个基于意见的主题,但我不喜欢依靠特定数量的空格进行对齐.维护和过度依赖IDE智能缩进是很繁琐的.我更喜欢这种符号,这是PEP8所允许的,但似乎并不受欢迎.注意用于区分函数体的双缩进:

def long_function_name(
        alpha,bravo,charlie,delta,echo,foxtrot,hotel,indiana):
    """Documentation would go here."""
    print(var_one + var_two + var_three)

当涉及到函数调用和赋值时,PEP8没有明确的答案.有人可能会缩进右括号,作为模仿下一条指令缩进时块如何结束的方法.

foo = bar(
    1,2,3
    )

垂直对齐非常受欢迎,我承认它看起来不错,但我再次不想在我的代码的未来读者上强制缩进大小,所以我避免这样做:

foo = bar(1,3,5,6,7,8,9,10,11,12,13,14)

或者也可以将右括号/括号放在左边:

foo = bar(
    1,3
)

来自C,Java和JavaScript背景,我使用第二个选项.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读