在映射理解中禁用dict表达式的黑色格式



我目前正在研究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()
]

有没有办法告诉布莱克在这种情况下保持水平结构?

您可以使用# 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 balck的输出:

/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'}]

黑色文档的相关部分:https://github.com/psf/black#the-黑码式

似乎black解决了这个问题。

在编写此答案时,使用black版本20.8b1,格式已按照我的期望完成。

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

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

将格式化为:

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

最新更新