问题
I use Black for Python, which conforms to 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?
Couldn't find something in PEP8 -- Style Guide for Python Code and The Black code style.
Demo
Related, but doesn't answer my question: What is the proper way to format a multi-line dict in Python?
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.
回答1:
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.
e.g
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) e.g.
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?
来源:https://stackoverflow.com/questions/64286651/pep8-multi-line-dict-with-multi-line-value