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

Function pythonImportsInScope

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

Source from the content-addressed store, hash-verified

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