How to group Python imports?

python

A key part of the PEP-8 Style Guide for Python Code is the Imports section.

This part on grouping imports is particularly important.

Imports should be grouped in the following order:

  • Standard library imports.
  • Related third party imports.
  • Local application/library specific imports.

PEP-8: The Style Guide for Python Code

“Standard library imports”

This refers to imports from Python’s built-in standard library.

from typing import Any
import os

“Third party” confuses a lot of people. These imports could be maintained by yourself or your organisation, but are installed as a separate package.

from airflow.utils.helpers import chain
import requests

“Local application/library specific imports”

I take this to mean “imports from the same repository”.

from . import settings
from .my_package import my_function

Separate groups with a blank line

Be sure to separate the groups with a blank line.

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

PEP-8: The Style Guide for Python Code

Import order

Within each group, sort imports alphabetically. (This is not part of the style guide, just my recommendation.)

from z_package import (
    a_module,
    b_module,
    c_module,
)
import a_package

Putting it all together

"""Module-level docstring"""
from typing import Any
import os

from airflow.utils.helpers import chain
import requests

from . import settings
from .my_package import my_function


# Code starts here after two blank lines.