Python - How to Group Imports

Published on Nov. 16, 2017, 10:01 a.m.

In case you were ever wondering, here is the standard way to group your imports.

# Standard library imports
import os
import sys

# 3rd party modules
from django.http import HttpResponseRedirect
from django.shortcuts import render

# My project-wide modules
from blog.settings import THEME
from lib.util import get_http_referer

# From separate application modules (within my project)
from analytics.models import PageRequest
from common.contexts import get_common_view_context
from .models import Category, Post

We want to have the standard library imports at the very top. Next, we want to use our top level 3rd party modules (related to our project).

Then, we have some imports that are first project-wide and then followed by the imports for adjacent application modules. I prefer to put the relative imports (see from .models import ...) last.

So, the standard is to start off far and work your way to the code at hand.

Hope this helps.

If this blog is helpful, please consider helping me pay it backward with a coffee.

Buy Me a Coffee at