3

I am working on a large project in python that has lots of imports.

  1. Some imports are system imports - these are easy, usually just absolutely imported.
  2. Some imports are third-party. These can have long, clunky absolute names, but clearly named single functions (requiring from ... import statements). Finally, some have canonical aliases (import numpy as np).
  3. Some imports are from my own package, which has 2 levels of heierarchy: 1 top level containing subdirectories with code.

Given all this, the most readable import scheme I could come up with is the following:

import aaa_sys
import bbb_sys

import aaa_third
from bbb_third import bb
import ccc_third as cc
import ddd_third

import .aaa_local
import .bbb_local
import ..aaa_remote.aaa_remote_module
import ..bbb_remote.bbb_remote_module

In other words, regardless of the type of import (absolute or aliasing or selective importing), I alphabetically import first the system, then third party, and finally package libraries.

Is there an industry-accepted approach to this? Something akin to Google C++ header import order.

4

if you are looking for a more detailed standard than pep8, see https://github.com/PyCQA/flake8-import-order

from their README

The following styles are directly supported,

  • cryptography - see an example
  • google - style described in Google Style Guidelines , see an example
  • smarkets - style as google only with import statements before from X import ... statements, see an example
  • appnexus - style as google only with import statements for packages local to your company or organisation coming after import statements for third-party packages, see an example
  • edited - see an example
  • pycharm - style as smarkets only with case sensitive sorting imported names
  • pep8 - style that only enforces groups without enforcing the order within the groups

You can also add your own style

2

I'm not a python expert, so I may be missing something, but the only import order standard I'm aware of is PEP8:

Imports should be grouped in the following order:

  1. standard library imports
  2. related third party imports
  3. local application/library specific imports

You should put a blank line between each group of imports.

Some tools such as pylint will warn you if your code breaks this suggestion.

It seems this is pretty much what you're doing already. The standard doesn't say, but sorting alphabetically within each group makes sense to me as well.

  • Yeah, I'm aware of PEP8 - unfortunately, as you mention, it's a bit ambiguous about the ordering within each of the blocks. – VF1 Jan 27 '17 at 16:38
  • 1
    Does PEP specify the order for private vs public imports? (import _tkinter vs import unittest) – Steven M. Vascellaro May 25 '18 at 15:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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