简体   繁体   English

具有多行值的 PEP8 多行字典

[英]PEP8 multi-line dict with multi-line value

I use Black for Python, which conforms to PEP8 .我使用 Black for Python,它符合 PEP8 It removes the indentation from the second line of a two line long value string:它从两行长值字符串的第二行中删除缩进:

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

to:到:

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

A colleague questioned this change, and I am wondering if there is any resource/reference that I can use to backup Black's decision to format the code like?一位同事质疑此更改,我想知道是否有任何资源/参考可用于备份 Black 对代码进行格式化的决定?

Couldn't find something in PEP8 -- Style Guide for Python Code and The Black code style .PEP8 -- Style Guide for Python CodeThe Black code style 中找不到内容。

Demo 演示

Related, but doesn't answer my question: What is the proper way to format a multi-line dict in Python?相关,但没有回答我的问题: 在 Python 中格式化多行 dict 的正确方法是什么?


PS: # fmt: off prevents Black from formatting line, but I don't want to use it, since my team doesn't use Black in general. PS: # fmt: off阻止黑色格式化行,但我不想使用它,因为我的团队一般不使用黑色。

The Black code style was the right place to check and you are right, it's not super clear for this use-case. Black 代码风格是检查的正确位置,你是对的,这个用例不是很清楚。 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.我可以说,如果您不将值的字符串拆分为两个字符串,那么 Black 会将其放在您可能更喜欢的一行上。 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 .我不确定 Black 是否有一个很好的方法来知道它何时可以在有意义的情况下将 2 个字符串连接为一个 - 请参阅此处的讨论。

eg例如

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

Using parentheses will make value more readable too perhaps?使用括号可能也会使值更具可读性? (this is my go-to usually) eg (这通常是我的首选)例如

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

By the way, noticed black didn't replace your single quotes with double quotes;顺便说一下,注意到黑色没有用双引号替换你的单引号; is that a setting you are using for your projects?这是您用于项目的设置吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM