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.
One can remove unused import statements in the entire project or in the current file only.
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).
Also, imports are sorted alphabetically within the respective groups:
Optimizing imports in project
To optimize imports in the entire project, follow these steps:
- Place the caret at the Project tool window and do one of the following:
The Optimize Imports dialog box opens.
- If your project is under version control, the option Only VCS changed files is enabled. Select or clear this option as required.
- Click Run.
Optimizing imports in the current file
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.
To optimize imports in the currently opened file, do one of the following:
- On the main menu, choose .
- Press Ctrl+Alt+O.
- Place the caret at the import statements, click , and choose Remove unused import.
- Open the Reformat File Dialog (Ctrl+Shift+Alt+L) and select the Optimize imports check box.