boolean (@NotNull PsiFile file, @NotNull String name, @Nullable String asName, @Nullable ImportPriority priority, @Nullable PsiElement anchor, final @Nullable PsiElement insertBefore) { if (!(file instanceof PyFile)) { return false; } final List<PyImportElement> existingImports = ((PyFile)file).getImportTargets(); final List<PyImportStatementBase> importsAllowedToReuse = getImportsAllowedToReuse(insertBefore); for (PyImportElement existingImport : existingImports) { if (importsAllowedToReuse != null && !importsAllowedToReuse.contains(existingImport.getContainingImportStatement())) { continue; } final String existingName = Objects.toString(existingImport.getImportedQName(), ""); if (name.equals(existingName) && Objects.equals(asName, existingImport.getAsName())) { return false; } } final PyElementGenerator generator = PyElementGenerator.getInstance(file.getProject()); final LanguageLevel languageLevel = LanguageLevel.forElement(file); final PyImportStatement importNodeToInsert = generator.createImportStatement(languageLevel, name, asName); final PsiElement insertParent; if (insertBefore == null || insertBefore.getParent() == null) { final PyImportStatementBase importStatement = PsiTreeUtil.getParentOfType(anchor, PyImportStatementBase.class, false); insertParent = importStatement != null && importStatement.getContainingFile() == file ? importStatement.getParent() : file; } else { insertParent = insertBefore.getParent(); } try { if (anchor instanceof PyImportStatementBase) { insertParent.addAfter(importNodeToInsert, anchor); } else { final PsiElement position; if (insertBefore == null) { position = getInsertPosition(insertParent, anchor, importNodeToInsert, priority); } else { position = insertBefore; } insertParent.addBefore(importNodeToInsert, position); } } catch (IncorrectOperationException e) { LOG.error(e); } return true; }