Unless otherwise specified PEP 8 standards should be written for all Python code. The easiest way to get up to speed with PEP 8 standards is using the flake8 python linter.
For more info on PEP 8 standards check out the official guide: https://www.python.org/dev/peps/pep-0008/. The Lightning Kite style guide will only outline a few of the most common PEP 8 standards.
$ pip install flake8
$ flake8 coolproject
coolproject/mod.py:97:1: F401 'shutil' imported but unused
coolproject/mod.py:625:17: E225 missing whitespace around operato
coolproject/mod.py:729:1: F811 redefinition of function 'readlines' from line 723
coolproject/mod.py:1028:1: F841 local variable 'errors' is assigned to but never used
poll.get_unique_voters()
, not poll.getUniqueVoters
).
example_variable = "Variables use underscores"
def example_function():
"""
Function names also use underscores
"""
pass
class ClassName():
"""
Classes use InitialCaps
"""
def some_function():
pass
def another_function():
"""
Functions and methods only need one space
"""
pass
class SomeClass():
"""
Class definitions should have two spaces
"""
pass
class AnotherClass():
pass
# Correct field naming and class Meta placement
class Person(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=40)
class Meta:
verbose_name_plural = 'people'
# Model with choices field
class MyModel(models.Model):
DIRECTION_UP = 'U'
DIRECTION_DOWN = 'D'
DIRECTION_CHOICES = (
(DIRECTION_UP, 'Up'),
(DIRECTION_DOWN, 'Down'),
)
In Django views, the first parameter in a view function should be called request
.
def my_view(request, foo):
# ...
In Django template code, put one (and only one) space between the curly brackets and the tag contents.
<div>
<span>{{ variable }}</span>
</div>
We like to alphabetize our imports and split them up into 4 main sections: Python libraries, django code, third party libraries, and our application code.
import os # Python libraries
import sys
from django import forms # Django code
from django.core.conf import settings
from rest_framework import serializers # Other third party libraries
from .models import User # Our application code