boolean (@NotNull PsiFile file, @NotNull String from, @NotNull String name, @Nullable String asName, @Nullable ImportPriority priority, @Nullable PsiElement anchor, final @Nullable PsiElement insertBefore) { final PyFile pyFile = (PyFile)file; final List<PyFromImportStatement> existingImports = pyFile.getFromImports(); int relativeLevel = 0; PyRelativeImportData importData = null; if (priority == ImportPriority.PROJECT) { importData = PyRelativeImportData.fromString(from, pyFile); if (importData != null) { relativeLevel = importData.getRelativeLevel(); } } final List<PyImportStatementBase> importsAllowedToReuse = getImportsAllowedToReuse(insertBefore); if (!PythonCodeStyleService.getInstance().isOptimizeImportsAlwaysSplitFromImports(file)) { for (PyFromImportStatement existingImport : existingImports) { if (importsAllowedToReuse != null && !importsAllowedToReuse.contains(existingImport)) { continue; } if (existingImport.isStarImport()) { continue; } final String existingSource = Objects.toString(existingImport.getImportSourceQName(), ""); boolean updateExisting = false; final int currentRelativeLevel = existingImport.getRelativeLevel(); if (currentRelativeLevel == 0) { updateExisting = from.equals(existingSource); } else if (relativeLevel != 0) { updateExisting = currentRelativeLevel == relativeLevel && existingSource.equals(importData.getRelativeLocation()); } if (updateExisting) { return addNameToFromImportStatement(existingImport, name, asName); } } } if (!PyUtil.hasIfNameEqualsMain(pyFile)) { final int maxRelativeLevelInFile = StreamEx.of(pyFile.getFromImports()) .mapToInt(PyFromImportStatement::getRelativeLevel) .max() .orElse(0); if (maxRelativeLevelInFile > 0 && relativeLevel > 0) { int maxAllowedDepth = Math.max(maxRelativeLevelInFile, Registry.intValue("python.relative.import.depth")); if (maxAllowedDepth >= relativeLevel) { from = importData.getLocationWithDots(); } } } addFromImportStatement(file, from, name, asName, priority, anchor, insertBefore); return true; }