2

This is the mess of imports currently at the top of my file:

import argparse
from copy import deepcopy
from functools import cmp_to_key, partial
from itertools import chain
import math
from multiprocessing import Pool
import os
import re
from typing import Dict, List, Set, Tuple
import xml.etree.ElementTree as ET

from third_party import Tool

I organised them alphabetically, by package (?) name.

I think it looks extremely ugly.

What are the standard ways to organise this section?

PEP8 (which I have read) is not helpful in this case:

Imports should be grouped in the following order:

Standard library imports.
Related third party imports.
Local application/library specific imports.
You should put a blank line between each group of imports.

2 Answers 2

6

Imports should be grouped in the following order:

Standard library imports.
Related third party imports.
Local application/library specific imports.
You should put a blank line between each group of imports.

python.org - pep-0008 - #imports

Pep8 also cites Barry's GNU Mailman style guide which offers more detailed ordering guidance:

Imports should be grouped, with the order being:

  1. non-from imports for standard and third party libraries
  2. non-from imports from the application
  3. from-imports from the standard and third party libraries
  4. from-imports from the application

From-imports should follow non-from imports. Dotted imports should follow non-dotted imports. Non-dotted imports should be grouped by increasing length, while dotted imports should be grouped alphabetically.

GNU Mailman Coding Style Guide

Over the years I've found the most important thing is to get everyone organizing these the same way. Because often very organized imports look like chaos to those who don't already know how they're organized.

2
  • Barry's 1, 2, 3, and 4 are all different groups? If this is the case, then he (surprisingly? and against PEP8...) groups standard library and third parties together.
    – minseong
    Commented Oct 25, 2020 at 15:48
  • 2
    I think of it as imposing two super groupings: from and non-from. Under which you can follow pep8 groupings twice over. Commented Oct 25, 2020 at 15:52
0

Start using isort, it has sane defaults. And set it up to autorun on save on your IDE or as a pre-commit hook to make your life easier.

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