PsiFile (PsiFile existingImportFile, PyImportElement importElement, PsiElement source) { PyFile sourceFile = as(PyUtil.turnDirIntoInit(source), PyFile.class); if (sourceFile instanceof PyFileImpl) { PsiElement variant = sourceFile.findExportedName(myRefText); final String name = variant instanceof PyQualifiedNameOwner ? ((PyQualifiedNameOwner)variant).getQualifiedName() : null; if (name != null && seenCandidateNames.contains(name)) { return existingImportFile; } PsiNamedElement definition = as(variant, PsiNamedElement.class); // allow importing from this source if it either declares the name itself or represents a higher-level package that reexports the name if (definition != null && !(definition instanceof PyFile || definition instanceof PyImportElement) && definition.getContainingFile() != null && PsiTreeUtil.isAncestor(source, definition.getContainingFile(), false)) { existingImportFile = sourceFile; fix.addImport(definition, sourceFile, importElement); if (name != null) { seenCandidateNames.add(name); } } } return existingImportFile; }