具有多行值的 PEP8 多行字典

PEP8 multi-line dict with multi-line value

我为 Python 使用黑色,conforms to PEP8。它从两行长值字符串的第二行删除缩进:

mydict = {
    'key0': 'value0',
    'key1': 'long-two-lines-string-value1-does-not-fit-in-one-line-has-to-continue'
            'value1'
}

至:

mydict = {
    'key0': 'value0',
    'key1': 'long-two-lines-string-value1-does-not-fit-in-one-line-has-to-continue'
    'value1',
}

一位同事质疑这一变化,我想知道是否有任何 resource/reference 可以用来支持 Black 格式化代码的决定,例如?

无法在 PEP8 -- Style Guide for Python Code and The Black code style 中找到内容。

Demo

相关,但没有回答我的问题:What is the proper way to format a multi-line dict in Python?


PS: # fmt: off 阻止 Black 格式化行,但我不想使用它,因为我的团队一般不使用 Black。

The Black code style was the right place to check and you are right, it's not super clear for this use-case. I can say if you don't split the string of the value into two strings then Black will put it on one line which you may prefer. I'm not sure Black has a good way to know when it can concatenate 2 strings to one when it makes sense - see discussion here.

例如

mydict = {
    "key0": "value0",
    "key1": "long-two-lines-string-value1-does-not-fit-in-one-line-has-to-continue value1",
}

也许使用括号也会使值更具可读性? (这是我通常 go-to) 例如

mydict = {
    "key0": "value0",
    "key1": (
        "long-two-lines-string-value1-does-not-fit-in-one-"
        "line-has-to-continue value1"
    ),
}

顺便说一句,注意到黑色没有用双引号替换你的单引号;这是您用于项目的设置吗?