python - 在映射理解范围内禁用字典表达式的Black格式化

标签 python formatting python-black

我目前正在研究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功能。

如您在下面看到的:

  • Black
  • 格式化了# fmt: off之前的列表理解
  • # fmt: off/# fmt: on之间,列表理解尚未由Black
  • 格式化
  • 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/

    相关文章:

    Python WSGI 输出错误

    r - 使用 R markdown 中的 flextable R 包并排对齐多个表格

    google-colaboratory - 用于 google colab 的代码格式化程序,如 nb_black

    python - Docker:通过共享PID namespace 从UID获取主机用户名

    python - 如何将二进制数组打乱特定数量

    python - 从 pandas 数据框转换为 LabeledPoint RDD

    c++ - double 到固定宽度的字符串转换

    css - 格式化 CSS 文件(压缩/解压缩)

    python - 是否可以将 Black 作为 API 调用?

    visual-studio-code - 用于 vscode 的 Python 黑色格式化程序未格式化