【问题标题】:How to handle reformatting of nested function calls with multi line string arguments如何使用多行字符串参数处理嵌套函数调用的重新格式化
【发布时间】:2018-08-15 07:50:32
【问题描述】:

我们使用oitnb 设置了我们的python 代码库的自动格式化,使用配置文件中的multi-line-unwrap 选项。在此之前,我们对所有带有--meld 的文件进行了初始传递,并插入了适当的fmt: no cmets。

虽然我们使用了 unwrap 选项,但这些 cmets 最常插入带有 .format() 函数的圆形多行字符串。这会重新格式化而不改变:

print('first:  {a}\nsecond: {b}\nthird:  {c}'.format(a=1, b=2, c=3))

但我们无法真正看到打印的元素是否对齐。我们倾向于使用:

print("""\
first:  {a}
second: {b}
third:  {c}
""".format(a=1, b=2, c=3))

但这会被使用oitnb 修改为:

print("""\
first:  {a}
second: {b}
third:  {c}
""".format(
        a=1, b=2, c=3
    )
)

当这样的打印出现在函数或类方法中时,情况会更糟,因为我们随后用dedent 包装:

def main():
    print(dedent("""\
        first:  {a}
        second: {b}
        third:  {c}
    """.format(a=1, b=2, c=3)))

我们也可以解开format 参数吗?或者其他一些新代码的解决方案,所以我们不需要使用 fmt cmets?

【问题讨论】:

  • # fmt: no 不会做任何事情。你需要使用# fmt: off

标签: python formatting multiline oitnb


【解决方案1】:

没有选项可以解开附加到多行字符串的方法,但我会考虑解开它(或添加一个新选项来这样做)。展开嵌套例程,其中内部例程具有多行字符串将更加困难。

目前 IMO 最好的方法是将字符串分配给一个变量,其名称足够短,不会导致函数调用行中的换行:

def main():
    fmt_s = """\
        first:  {a}
        second: {b}
        third:  {c}
    """
    print(dedent(fmt_s.format(a=1, b=2, c=3)), end="")

重新格式化(假设您没有将 line-length 设置为非常低的值,因此也是如此:

def main():
    fmt_s = dedent("""\
        first:  {a}
        second: {b}
        third:  {c}
    """)
    print(fmt_s.format(a=1, b=2, c=3), end="")

在申请 .format() 之前,请注意这两个版本 dedent 我发现他几乎总是你想要的,因为它可以防止你必须包含尽可能多的空格作为你的 multi-行字符串在作为format-arguments 一部分的任何换行符之后具有前导空格。你的例子在format-ting 之后出现了变化。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-09
    • 1970-01-01
    • 2015-04-22
    • 2020-04-30
    • 2011-04-09
    • 1970-01-01
    • 1970-01-01
    • 2021-09-10
    相关资源
    最近更新 更多