[Python-ideas] PEP8 dictionary indenting addition
Paul Moore
p.f.moore at gmail.com
Sun Oct 9 07:43:03 EDT 2016
On 9 October 2016 at 01:25, Steven D'Aprano <steve at pearwood.info> wrote:
> On Sat, Oct 08, 2016 at 09:26:13PM +0200, Jelte Fennema wrote:
>> I have an idea to improve indenting guidelines for dictionaries for better
>> readability: If a value in a dictionary literal is placed on a new line, it
>> should have (or at least be allowed to have) a n additional hanging indent.
>>
>> Below is an example:
>>
>> mydict = {'mykey':
>> 'a very very very very very long value',
>> 'secondkey': 'a short value',
>> 'thirdkey': 'a very very very '
>> 'long value that continues on the next line',
>> }
>
> Looks good to me, except that my personal preference for the implicit
> string concatenation (thirdkey) is to move the space to the
> following line, and (if possible) align the parts:
The proposed approach looks good to me, but I'm a strong believe that
when you get to situations this complex, the overriding rule should
always be "use your judgement". For thirdkey, it's quite possible I'd
advise splitting the value out into a named variable.
I'd probably lay this out as
# Less indent needed for keys, so thirdkey fits better in this case
mydict = {
'mykey': 'a very very very very very long value',
'secondkey': 'a short value',
'thirdkey':
'a very very very long value that continues on the next line',
}
Or
# Move the troublesome value out into a named variable
val3 = 'a very very very long value that continues on the next line'
mydict = {
'mykey': 'a very very very very very long value',
'secondkey': 'a short value',
'thirdkey': val3,
}
or if I *really* had to split val3, I might go for
# Triple-quote/backslash lets you start at the left margin.
# And I personally find space-backslash more noticeable than space-quote
# Space on the second line is often semantically less consistent
(depends on the value)
val3 = '''\
a very very very long value that \
continues on the next line'''
or even
# Just give up on trying to make it a constant
val3 = ' '.join([
"a very very very long value that",
"continues on the next line"
])
There's also the option of simply giving up on the line length
guideline for this one value, and putting the constant on one long
line.
Lots of possibilities, and which one I'd go for depends on context and
the actual content of a (non-toy) example.
Paul
More information about the Python-ideas
mailing list