Python – Best Practices for Import Order

coding-stylepython

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.

Best Answer

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.

Related Topic