长函数调用的代码应该如何设置样式?

2024-06-28 11:33:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我将在这里使用argparse作为示例,但我认为它适用于很多事情。考虑:

parser = argparse.ArgumentParser(description="This is a description of how this program works.")
subparsers = parser.add_subparsers(title="subcommands")
parser_sub1 = subparsers.add_parser("sub1",
                                    description="subcommand 1 does something something something")
parser_sub1.add_argument("arg1",
                         help="Arg1 does somethign something something.")

对20多条丑陋的线条如此。在

add_参数,尤其是add_解析器行很长,很大程度上是因为help/description字符串。但我看不出明显的方法可以把它们干净利落地缩短。如您所见,在第二行按常规方式缩进只能获得几个字符。将字符串分成多行会很快变得很尴尬。在

我在通过-m pep8运行一些代码时遇到了这个问题,它抱怨几乎每个add_参数行都超过80个字符。根本的问题似乎是,行到左括号的部分本身太长,以至于无法在后面插入字符串,即使参数之间有一个中断和缩进。我可以想出几种方法来解决这个问题:

  • 活在很长的队伍里,忽略pep8
  • 在缩进下一行并忽略pep8
  • 使用非常短的变量名来保存字符(例如ps1 = parser.add_subparsers(whatever)
  • 别名我可以保存更多的内容(例如每个块的psaa = parser_sub1.add_argument
  • 制作一堆字典字面值,并用**将它们解压到函数调用中(但是我发现dict字面值很难处理)
  • 从外部文件中以一种不太笨拙的格式(可能是YAML)读入函数调用参数,然后解包(但是如果不引用另一个文件,就无法判断代码在做什么)
  • …还有什么?在

有没有一种已知有效的方法来处理冗长的函数参数,而这些参数在自然编写时会被80个字符的约定所干扰?在


Tags: 方法字符串addparser参数argparsehelpdescription
2条回答

这在很大程度上是一个品味和意见的问题,但在这里,有两个!在

  • 很少有真正的代码坚持严格的80列建议。避免笨重、冗长的队伍是值得的,但狭隘地坚持一个源自穿孔卡片的约束是愚蠢的。PEP8也解决了这一问题:

Some teams strongly prefer a longer line length. For code maintained exclusively or primarily by a team that can reach agreement on this issue, it is okay to increase the nominal line length from 80 to 100 characters (effectively increasing the maximum length to 99 characters)

  • 对于这样的情况,最明智的做法可能是建立某种数据结构,这种结构主要是通过文本来表达的,然后通过**参数或使用循环插入到配置调用中。它使所有的文本可读,内联和在一个地方,因此容易编辑。您应该能够在代码中间得到一个看起来像docstring的blob。在
x = ('string literal broken across two lines '
...  'but it works because the parens keeps them together.')
>>> x
'string literal broken across two lines but it works because the parens keeps them together.'

>>> print('If this was already in the parens of an argument list '
...       'you are already in a context where string literal '
...       'concatenation works.')
If this was already in the parens of an argument list you are already in a context where string literal concatenation works.

相关问题 更多 >