result of pycharm optimize imports

Viewed 345

I used "code/optimize imports" in Pycharm and it resulted in this

import logging
import os
import re
import subprocess
from getpass import getpass
from pathlib import Path

import requests
import sys
import time
from bs4 import BeautifulSoup

why is it in this order? why is there a blank line?

1 Answers

Maybe it uses isort (https://pypi.org/project/isort/):

  1. import is before from x import y

  2. Than the imports are sorted alphabetically.

  3. And lastly the imports are grouped by the type of the import. The blank line between your imports is the separator between Python Standard Library imports and Third Party imports.

    isort parses specified files for global level import lines (imports outside of try / except blocks, functions, etc..) and puts them all at the top of the file grouped together by the type of import:

    • Future
    • Python Standard Library
    • Third Party
    • Current Python Project
    • Explicitly Local (. before import, as in: from . import x)
    • Custom Separate Sections (Defined by forced_separate list in configuration file)
    • Custom Sections (Defined by sections list in configuration file)

    Inside of each section the imports are sorted alphabetically. isort automatically removes duplicate python imports, and wraps long from imports to the specified line length (defaults to 79).

Edit:

Group imports by type is recommended also in PEP8 (https://www.python.org/dev/peps/pep-0008/#imports)

Related