boolean (@NotNull PyFromImportStatement fromImport, @NotNull String name, @Nullable String asName) { final PsiFile file = fromImport.getContainingFile(); final Comparator<String> nameComparator = getImportTextComparator(file); final PythonCodeStyleService pyCodeStyle = PythonCodeStyleService.getInstance(); final boolean shouldSort = pyCodeStyle.isOptimizeImportsSortImports(file) && pyCodeStyle.isOptimizeImportsSortNamesInFromImports(file); PyImportElement followingNameElement = null; for (PyImportElement existingNameElement : fromImport.getImportElements()) { final String existingName = Objects.toString(existingNameElement.getImportedQName(), ""); if (name.equals(existingName) && Objects.equals(asName, existingNameElement.getAsName())) { return false; } if (shouldSort && followingNameElement == null && nameComparator.compare(existingName, name) > 0) { followingNameElement = existingNameElement; } } final PyElementGenerator generator = PyElementGenerator.getInstance(fromImport.getProject()); final PyImportElement newNameElement = generator.createImportElement(LanguageLevel.forElement(fromImport), name, asName); // addBefore(newNameElement, null) is the same as inserting at the end fromImport.addBefore(newNameElement, followingNameElement); // May need to add parentheses, trailing comma, etc. CodeStyleManager.getInstance(fromImport.getProject()).reformat(fromImport); return true; }