Import order in python for specific packages

61 views Asked by At

I ran pylint on my codebase and it complained that from config import ConfigParser was defined before from pathlib import Path Why is this the case?

When I ran isort of the file, it agreed with pylint. From what I understand it groups imports by type

  • Native to python
  • General 3rd party
  • local packages

And in that it groups them by whether or not you use from or import and after that it wants them alphabetical.

I would have thought that config would come before pathlib, but this is not the case. What is happening here?

Before running isort

from config import ConfigParser
from pathlib import Path

After running isort

from pathlib import Path

from config import ConfigParser
2

There are 2 answers

0
Ivan Nedobezhkin On BEST ANSWER

According to isort docs the default order is the following:

  1. Future
  2. stdlib (pathlib is from stdlib)
  3. Third-party modules
  4. First-party modules
  5. Local modules (like config)

This way isort first orders imports by their category, then orders them alphabetically or by length.

0
jprebys On

The stdlib module is called configparser, so you should change your imports to:

from configparser import ConfigParser
from pathlib import Path

and isort will behave as you expect.