我目前正在研究Black作为我们的默认格式化程序,但是,我遇到了一些格式不正确的边缘情况,我想知道是否有办法获得想要的结果。
Black的文档partially explores my problem,我有一个水平分布的字典表达式,由于希望添加行,所以我希望保持这种方式,例如:
# 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()
]
不管尾随逗号如何,哪个Black都会崩溃,如下所示:
res = [
{"id": item.id, "name": item.name,}
for item in items.select()
]
在这种情况下,是否有办法告诉Black保留水平结构?
最佳答案
您可以使用# fmt: off
/# fmt: on
功能。
如您在下面看到的:
# fmt: off
之前的列表理解# fmt: off
/# fmt: on
之间,列表理解尚未由Black # fmt: on
之后的列表理解代码(用黑色格式化后):
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黑手党的输出:
/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-code-style
关于python - 在映射理解范围内禁用字典表达式的Black格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61578899/