private static void removeFormerImport(@NotNull final PsiFile usageFile, boolean addImport) {
    if (usageFile instanceof PyFile && addImport) {
      final PsiFile contextFile = FileContextUtil.getContextFile(usageFile);
      final PsiFile file = ObjectUtils.chooseNotNull(contextFile, usageFile);
      TypeEvalContext context = TypeEvalContext.codeAnalysis(file.getProject(), file);

      final PyUnresolvedReferencesVisitor visitor = new SimplePyUnresolvedReferencesInspection.Visitor(null,
                                                                                                       new SimplePyUnresolvedReferencesInspection(), context);
      usageFile.accept(new PyRecursiveElementVisitor() {
        @Override
        public void visitPyElement(@NotNull PyElement node) {
          super.visitPyElement(node);
          node.accept(visitor);
        }
      });

      visitor.optimizeImports();
    }
  }
private static void removeFormerImport(@NotNull final PsiFile usageFile, boolean addImport)