10

我目前正在研究将Black作为我们的默认格式化程序,但是,我遇到了一些无法很好格式化的边缘情况,我想知道是否有办法获得我想要的结果。

Black的文档部分探讨了我的问题,我有一个水平分布的字典表达式,我希望保持这种状态,因为我希望添加行,例如:

# Black would keep this as-is because of the trailing comma
TRANSLATIONS = {
    "en_us": "English (US)",
    "pl_pl": "polski",
}

但在我的情况下,字典在列表理解中:

res = [
    {
        'id': item.id,
        'name': item.name,
    }
    for item in items.select()
]

无论尾随逗号如何,哪个黑方崩溃,如下所示:

res = [
    {"id": item.id, "name": item.name,}
    for item in items.select()
]

有没有办法告诉黑方在这些情况下保持水平结构?

4

2 回答 2

6

您可以使用# fmt: off/# fmt: on功能。

如下所示:

  • 之前的列表理解# fmt: off已被 Black 格式化
  • # fmt: off/之间# fmt: on的列表理解尚未被Black格式化
  • 之后的列表理解# fmt: on已被 Black 格式化

代码(黑色格式化后):

res1 = [{"id": item[0], "name": item[1],} for item in [[5, "foo"], [6, "bar"]]]

# fmt: off
res2 = [
    {
        'id': item[0],
        'name': item[1],
    }
    for item in [[7, "fooo"], [8, "barr"]]
]
# fmt: on

res3 = [{"id": item[0], "name": item[1],} for item in [[9, "fooo0"], [10, "barrr"]]]

print(res1)
print(res2)
print(res3)

Python black 的输出:

/home/milanbalazs/.local/bin/black --fast -l 100 -v /home/milanbalazs/test.py
reformatted /home/milanbalazs/test.py
All done! ✨  ✨
1 file reformatted.

代码输出:

>>> python3 test.py 
[{'id': 5, 'name': 'foo'}, {'id': 6, 'name': 'bar'}]
[{'id': 7, 'name': 'fooo'}, {'id': 8, 'name': 'barr'}]
[{'id': 9, 'name': 'fooo0'}, {'id': 10, 'name': 'barrr'}]

Black 文档的相关部分:https ://github.com/psf/black#the-black-code-style

于 2020-05-03T18:27:27.013 回答
3

似乎黑色解决了这个问题。

在写这个答案的时候,使用黑色版本20.8b1,格式化是我希望的。

只要字典表达式的最后一项后面有一个神奇的逗号,黑色就会在列表理解中格式化代码。

res = [
    {
        "id": item.id, "name": item.name,
    }
    for item in items.select()
]

将格式化为:

res = [
    {
        "id": item.id,
        "name": item.name,
    }
    for item in items.select()
]
于 2021-03-21T11:25:54.923 回答