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

The first group, “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 the same organisation, but are installed as a separate package.

from airflow.utils.helpers import chain
import requests

The third group, “Local application/library specific imports”

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

from . import settings
from .my_package import my_function

Putting it together

from typing import Any
import os

from airflow.utils.helpers import chain
import requests

from . import settings
from .my_package import my_function

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

Within each group, sort the imports alphabetically. This is not part of the style guide, just my recommendation, to make the maintainer’s job easier.