使用黑色格式化程序嵌套长列表和集合

Nesting long lists and sets using black formatter

python 黑色格式化程序可以嵌套长列表和集合吗?例如:

输入

coworkers = {"amy", "bill", "raj", "satoshi", "jim", "lifeng", "jeff", "sandeep", "mike"}

默认输出

coworkers = {
    "amy",
    "bill",
    "raj",
    "satoshi",
    "jim",
    "lifeng",
    "jeff",
    "sandeep",
    "mike",
}

期望的输出

coworkers = {
    "amy", "bill", "raj", "satoshi", "jim",
    "lifeng", "jeff", "sandeep", "mike",
}

这是不可能的,因为 Black 使用的编码风格可以看作是 PEP 8 的严格子集。请阅读文档 here。具体来说:

As for vertical whitespace, Black tries to render one full expression or simple statement per line. If this fits the allotted line length, great.

# in:
j = [1,
     2,
     3
]

# out:
j = [1, 2, 3]

If not, Black will look at the contents of the first outer matching brackets and put that in a separate indented line.

# This piece of code is written by me, it isn't part of the original doc
# in
j = [1, 2, 3, 4, 5, 6, 7]

# out
j = [
    1, 2, 3, 4, 5, 6, 7
]

If that still doesn’t fit the bill, it will decompose the internal expression further using the same rule, indenting matching brackets every time. If the contents of the matching brackets pair are comma-separated (like an argument list, or a dict literal, and so on) then Black will first try to keep them on the same line with the matching brackets. If that doesn’t work, it will put all of them in separate lines.

针对这个讨厌的黑色功能

的一些解决方法

以下代码在black下不变

#demo.py
coworkers = (
    {}
    + {"amy", "bill", "raj", "satoshi", "jim", "lifeng", "jeff", "sandeep", "mike"}
    + {"john", "hans", "silvester", "gringo", "arold"}
)
$ black demo.py 
All done! ✨  ✨
1 file left unchanged.

请注意:

  1. 你需要空的{}
  2. 将“john”放入上一组将导致换行行为,因为已达到最大行长度(黑色默认为 88)
  3. 不要在你的集合中添加尾随逗号https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html#the-magic-trailing-comma
  4. 下的更多信息