MCPcopy Create free account
hub / github.com/colbymchenry/codegraph / pythonImportsInScope

Function pythonImportsInScope

src/resolution/import-resolver.ts:3825–3857  ·  view source on GitHub ↗
(ref: UnresolvedRef, imports: ImportMapping[], context: ResolutionContext)

Source from the content-addressed store, hash-verified

3823 * mapping.
3824 */
3825export function pythonImportsInScope(ref: UnresolvedRef, imports: ImportMapping[], context: ResolutionContext): ImportMapping[] {
3826 if (ref.language !== 'python' || ref.referenceKind === 'imports') return imports;
3827 const dot = ref.referenceName.indexOf('.');
3828 if (dot < 0 && /^[A-Za-z_]\w*$/.test(ref.referenceName)) return pythonBareImportsInScope(ref, imports, context);
3829 if (dot <= 0) return imports;
3830 const receiver = ref.referenceName.slice(0, dot);
3831 // `import pkg.mod` binds `pkg`, under a mapping named after `mod`.
3832 const binds = (m: ImportMapping): boolean => m.localName === receiver ||
3833 (m.isNamespace && m.source.split('.')[0] === receiver && m.localName === m.source.split('.').pop());
3834 if (!imports.some(binds)) return imports;
3835 const binding = pythonReceiverBinding(receiver, ref, context);
3836 if (binding === 'module') {
3837 // Where nothing nearer binds the name, the module's own import of it
3838 // does — not a from-import written inside some other function, which the
3839 // mappings list too (first, ahead of the module's `import pkg.other as
3840 // other`). Asked only when the receiver's mappings disagree; with no
3841 // module-level one found, every mapping stays as it was.
3842 const keyOf = (m: ImportMapping): string => (m.isNamespace ? `${m.source}:*` : `${m.source}:${m.exportedName}`);
3843 if (new Set(imports.filter(binds).map(keyOf)).size < 2) return imports;
3844 const moduleLevel = pythonModuleImportKeys(receiver, ref.filePath, context);
3845 const kept = imports.filter((m) => !binds(m) || m.isNamespace || moduleLevel.has(keyOf(m)));
3846 return kept.some(binds) ? kept : imports;
3847 }
3848 return imports.filter((m) => {
3849 if (!binds(m)) return true;
3850 if (binding === 'local') return false;
3851 // The module a namespace mapping binds the receiver to: `import x as
3852 // receiver` / `import receiver` bind its source, `import receiver.sub`
3853 // the top-level `receiver`.
3854 if ('module' in binding) return m.isNamespace && (m.localName === receiver ? m.source : receiver) === binding.module;
3855 return !m.isNamespace && m.source === binding.source && m.exportedName === binding.exportedName;
3856 });
3857}
3858
3859/**
3860 * The file's import mappings as a bare Python name reads them (#3229). The

Callers 2

isPythonProjectModuleMethod · 0.90
resolveViaImportFunction · 0.85

Calls 5

pythonBareImportsInScopeFunction · 0.85
mapMethod · 0.80
hasMethod · 0.80
bindsFunction · 0.70
keyOfFunction · 0.70

Tested by

no test coverage detected