void (@NotNull List<PyImportStatementBase> result, @NotNull PyFromImportStatement fromImport) { // We can neither sort, nor combine star imports if (fromImport.isStarImport()) { addImportAsIs(result, fromImport); return; } final String source = getNormalizedFromImportSource(fromImport); final PyImportElement[] importedFromNames = fromImport.getImportElements(); final List<PyImportElement> newFromImportNames = new ArrayList<>(); final Comparator<PyImportElement> fromNamesComparator = getFromNamesComparator(); final Collection<PyFromImportStatement> sameSourceImports = myOldFromImportBySources.get(source); if (sameSourceImports.isEmpty()) { return; } // Keep existing parentheses if we only re-order names inside the import boolean forceParentheses = sameSourceImports.size() == 1 && fromImport.getLeftParen() != null; // Join multiple "from" imports with the same source, like "from module import foo; from module import bar as b" final boolean shouldJoinImports = myPySettings.OPTIMIZE_IMPORTS_JOIN_FROM_IMPORTS_WITH_SAME_SOURCE && sameSourceImports.size() > 1; final boolean shouldSplitImport = myPySettings.OPTIMIZE_IMPORTS_ALWAYS_SPLIT_FROM_IMPORTS && importedFromNames.length > 1; if (shouldJoinImports) { for (PyFromImportStatement sameSourceImport : sameSourceImports) { ContainerUtil.addAll(newFromImportNames, sameSourceImport.getImportElements()); } // Remember that we have checked imports with this source already myOldFromImportBySources.remove(source); } else if (!shouldSplitImport && myPySettings.OPTIMIZE_IMPORTS_SORT_NAMES_IN_FROM_IMPORTS) { if (!Ordering.from(fromNamesComparator).isOrdered(Arrays.asList(importedFromNames))) { ContainerUtil.addAll(newFromImportNames, importedFromNames); } } final boolean shouldGenerateNewFromImport = !newFromImportNames.isEmpty(); if (shouldGenerateNewFromImport) { if (myPySettings.OPTIMIZE_IMPORTS_SORT_NAMES_IN_FROM_IMPORTS) { newFromImportNames.sort(fromNamesComparator); } String importedNames = StringUtil.join(newFromImportNames, ImportSorter::getNormalizedImportElementText, ", "); if (forceParentheses) { importedNames = "(" + importedNames + ")"; } final PyFromImportStatement combinedImport = myGenerator.createFromImportStatement(myLangLevel, source, importedNames, null); final Set<PyImportStatementBase> oldImports = ContainerUtil.map2LinkedSet(newFromImportNames, e -> (PyImportStatementBase)e.getParent()); replaceSeveralImportsWithOne(result, oldImports, combinedImport); } else if (shouldSplitImport) { final List<PyFromImportStatement> newFromImports = ContainerUtil.map(importedFromNames, importElem -> { final String name = Objects.toString(importElem.getImportedQName(), ""); final String alias = importElem.getAsName(); return myGenerator.createFromImportStatement(myLangLevel, source, name, alias); }); replaceOneImportWithSeveral(result, fromImport, newFromImports); } else { addImportAsIs(result, fromImport); } }