PyCharm 4.5.3 Help

Optimizing Imports

On this page:


Sooner or later, some of the imported classes or packages become redundant to the code.

Typically, you have to stop what you are doing, scroll to the head of the file, find the unused imports, and remove them. It is rather easy to forget to remove imports when you remove usages.

PyCharm provides the Optimize Imports feature, which enables you, whenever it is convenient, to remove unused imports from your current file, or from all files in the current directory at once. This helps you avoid unused, excessive and duplicating imports in your project.

Besides cleaning the code from the unused imports, PyCharm formats the existing import statements according to the Style Guide for Python Code. So doing, PyCharm splits import statements into separate lines, and sorts them into groups (refer to the Imports section for details).

One way of dealing with unused import is to use the quick-fix that appears when you set the caret at the highlighted unused import . However, you can optimize imports in a larger scope as described below.

Optimizing imports

To optimize imports, follow these steps:

  1. Do one of the following:
    • On the main menu, choose Code | Optimize Imports.
    • Press Ctrl+Alt+O.
  2. In the Optimize Imports dialog box, specify where you want PyCharm to remove unused import statements from.
    • To have unused imports removed from the current file, select the File option.
    • To have unused imports removed from all files in the current directory, select the All files in directory... option.
  3. Click Run.

See Also

Last modified: 5 August 2015