我们已经使用配置文件中的multi-line-unwrap
选项,使用oitnb
设置了Python代码库的自动格式化。在此之前,我们使用 --meld
对所有文件进行了初始传递,并插入了适当的 fmt: no
注释。
尽管我们使用展开选项,但这些注释最常使用 .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 注释?
最佳答案
没有选项可以解开附加到多行字符串的方法,但我会考虑解开它(或添加一个新选项来执行此操作)。展开内部例程具有多行字符串的嵌套例程将会更加困难。
目前 IMO 最好的方法是将字符串分配给一个变量,名称足够短,不会导致函数调用行中的换行:
def main():
fmt_s = """\
first: {a}
second: {b}
third: {c}
"""
print(dedent(fmt_s.format(a=1, b=2, c=3)), end="")
重新格式化相同(假设您没有将行长度设置为非常低的值,因此:
def main():
fmt_s = dedent("""\
first: {a}
second: {b}
third: {c}
""")
print(fmt_s.format(a=1, b=2, c=3), end="")
请注意,在应用.format()
之前,这两个版本都dedent
。我发现他的几乎总是你想要的,因为它防止您必须在属于 format
参数的任何换行符后面包含与多行字符串一样多的空格作为前导空格。您的示例在 format
-ting 之后缩进。
关于python - 如何处理具有多行字符串参数的嵌套函数调用的重新格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51854839/