Skip to main content
 首页 » 编程设计

Python 什么代码约定将参数分成几行

2025年05月04日9mfrbuaa

这种将参数分成几行的惯例是什么?是否有 PEP 对此进行制裁?我没有在 PEP8 中找到它.

file_like = f(self, 
              path, 
              mode=mode, 
              buffering=buffering, 
              encoding=encoding, 
              errors=errors, 
              newline=newline, 
              line_buffering=line_buffering, 
              **kwargs) 

请您参考如下方法:

它用于 (A) Vertical Alignment在 (B) 最大行长度将被超过时使用,有时即使它不会 - 为了更好的可读性。

这些是该页面上的前 3 个示例:

Yes:

# Aligned with opening delimiter. 
foo = long_function_name(var_one, var_two, 
                         var_three, var_four) 
 
# More indentation included to distinguish this from the rest. 
def long_function_name( 
        var_one, var_two, var_three, 
        var_four): 
    print(var_one) 
 
# Hanging indents should add a level. 
foo = long_function_name( 
    var_one, var_two, 
    var_three, var_four) 

您询问的是上面第一个示例的变体,为清楚起见,每行只有一个 arg。

No:

# Arguments on first line forbidden when not using vertical alignment. 
foo = long_function_name(var_one, var_two, 
    var_three, var_four) 

并且 (C),具有给定名称的参数(关键字参数)已完成,因此您无需查找被调用函数中的参数。通常,每个可能充当被调用函数核心功能的标志或修饰符的非显而易见的参数都应作为关键字参数传递。例如:

> read_file('abc.txt', 1024, True)  # yes, you know 'abc.txt' is the filename 
> # What are the 1024 and True for? 
> # versus... 
> read_file('abc.txt', max_lines=1024, output_as_list=True)  # now you know what it does. 

附言:The answer by @falsetru没有错。最大行长度是重新格式化代码的第一个原因。至于为什么要这样对齐,那就是垂直对齐。