PEP8的E128:连续行缩进不足以实现视觉缩进是什么?

问题:PEP8的E128:连续行缩进不足以实现视觉缩进是什么?

刚刚用Sublime Text(使用Sublime Linter)打开了一个文件,并注意到了一个我以前从未见过的PEP8格式错误。这是文本:

urlpatterns = patterns('',
    url(r'^$', listing, name='investment-listing'),
)

它标记了第二个参数,即开始的行 url(...)

我本来打算在ST2中禁用此检查,但是在忽略它之前,我想知道自己在做错什么。你永远不会知道,如果它看起来很重要,我什至可以改变我的方式:)

Just opened a file with Sublime Text (with Sublime Linter) and noticed a PEP8 formatting error that I’d never seen before. Here’s the text:

urlpatterns = patterns('',
    url(r'^$', listing, name='investment-listing'),
)

It’s flagging the second argument, the line that starts url(...)

I was about to disable this check in ST2 but I’d like to know what I’m doing wrong before I ignore it. You never know, if it seems important I might even change my ways :)


回答 0

如果在第一行上放置任何内容,PEP-8建议您在括号内缩进一行,因此应该在括号内缩进:

urlpatterns = patterns('',
                       url(r'^$', listing, name='investment-listing'))

或不将任何参数放在起始行上,然后缩进一个统一级别:

urlpatterns = patterns(
    '',
    url(r'^$', listing, name='investment-listing'),
)

urlpatterns = patterns(
    '', url(r'^$', listing, name='investment-listing'))

我建议您通读PEP-8-您可以浏览其中的很多内容,而且与某些技术性更高的PEP相比,它很容易理解。

PEP-8 recommends you indent lines to the opening parentheses if you put anything on the first line, so it should either be indenting to the opening bracket:

urlpatterns = patterns('',
                       url(r'^$', listing, name='investment-listing'))

or not putting any arguments on the starting line, then indenting to a uniform level:

urlpatterns = patterns(
    '',
    url(r'^$', listing, name='investment-listing'),
)

urlpatterns = patterns(
    '', url(r'^$', listing, name='investment-listing'))

I suggest taking a read through PEP-8 – you can skim through a lot of it, and it’s pretty easy to understand, unlike some of the more technical PEPs.


回答 1

对于这样的语句(由PyCharm自动格式化)也是如此:

    return combine_sample_generators(sample_generators['train']), \
           combine_sample_generators(sample_generators['dev']), \
           combine_sample_generators(sample_generators['test'])

它将发出相同的样式警告。为了摆脱它,我不得不将其重写为:

    return \
        combine_sample_generators(sample_generators['train']), \
        combine_sample_generators(sample_generators['dev']), \
        combine_sample_generators(sample_generators['test'])

This goes also for statements like this (auto-formatted by PyCharm):

    return combine_sample_generators(sample_generators['train']), \
           combine_sample_generators(sample_generators['dev']), \
           combine_sample_generators(sample_generators['test'])

Which will give the same style-warning. In order to get rid of it I had to rewrite it to:

    return \
        combine_sample_generators(sample_generators['train']), \
        combine_sample_generators(sample_generators['dev']), \
        combine_sample_generators(sample_generators['test'])