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 :)

up vote 363 down vote accepted

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 - it's not a long document, and it's pretty easy to understand, unlike some of the more technical PEPs.

  • 5
    Anybody know why Django does this; is there a good reason? It seems that it would be just as easy to follow PeP-8. – TheHerk Mar 22 '14 at 1:35
  • 4
    This is so ubiquitous in Django code I've seen (plus it's all over their docs) that it arguably supersedes PEP-8, after all it says "Many projects have their own coding style guidelines. In the event of any conflicts, such project-specific guides take precedence for that project." – Nick T May 13 '14 at 22:04
  • 5
    @TheHerk the rationale is probably that the first argument to patterns() is unique (a prefix for everything else specified), and all the other arguments are url patterns which are basically the same. – Nick T May 13 '14 at 22:06
  • 6
    @NickT You are mis-reading PEP-8 - PEP-8 recommends following the existing convention where a given project uses it - but in this case the code is not going into Django, it's going into your project using Django - there is no need to follow their convention. The aim of that rule is to keep consistency inside code-bases. – Gareth Latty May 17 '14 at 14:34
  • 23
    Note that PEP8 also states that you should ignore PEP8 where it makes sense to do so, and I would argue that in this case in makes sense. Feel free to disagree for your own projects. In any case this will soon be a moot point as using patterns() will be deprecated in Django 1.8: docs.djangoproject.com/en/dev/releases/1.8/… – Tom Carrick Jul 29 '14 at 10:16

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.