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

Function pythonImportsInScope

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

Source from the content-addressed store, hash-verified

3648 * mapping.
3649 */
3650export function pythonImportsInScope(ref: UnresolvedRef, imports: ImportMapping[], context: ResolutionContext): ImportMapping[] {
3651 if (ref.language !== 'python' || ref.referenceKind === 'imports') return imports;
3652 const dot = ref.referenceName.indexOf('.');
3653 if (dot <= 0) return imports;
3654 const receiver = ref.referenceName.slice(0, dot);
3655 // `import pkg.mod` binds `pkg`, under a mapping named after `mod`.
3656 const binds = (m: ImportMapping): boolean => m.localName === receiver ||
3657 (m.isNamespace && m.source.split('.')[0] === receiver && m.localName === m.source.split('.').pop());
3658 if (!imports.some(binds)) return imports;
3659 const binding = pythonReceiverBinding(receiver, ref, context);
3660 if (binding === 'module') {
3661 // Where nothing nearer binds the name, the module's own import of it
3662 // does — not a from-import written inside some other function, which the
3663 // mappings list too (first, ahead of the module's `import pkg.other as
3664 // other`). Asked only when the receiver's mappings disagree; with no
3665 // module-level one found, every mapping stays as it was.
3666 const keyOf = (m: ImportMapping): string => (m.isNamespace ? `${m.source}:*` : `${m.source}:${m.exportedName}`);
3667 if (new Set(imports.filter(binds).map(keyOf)).size < 2) return imports;
3668 const moduleLevel = pythonModuleImportKeys(receiver, ref.filePath, context);
3669 const kept = imports.filter((m) => !binds(m) || m.isNamespace || moduleLevel.has(keyOf(m)));
3670 return kept.some(binds) ? kept : imports;
3671 }
3672 return imports.filter((m) => {
3673 if (!binds(m)) return true;
3674 if (binding === 'local') return false;
3675 // The module a namespace mapping binds the receiver to: `import x as
3676 // receiver` / `import receiver` bind its source, `import receiver.sub`
3677 // the top-level `receiver`.
3678 if ('module' in binding) return m.isNamespace && (m.localName === receiver ? m.source : receiver) === binding.module;
3679 return !m.isNamespace && m.source === binding.source && m.exportedName === binding.exportedName;
3680 });
3681}
3682
3683/**
3684 * Resolve a Python qualified reference whose receiver is an imported MODULE:

Callers 2

isPythonProjectModuleMethod · 0.90
resolveViaImportFunction · 0.85

Calls 4

mapMethod · 0.80
hasMethod · 0.80
bindsFunction · 0.70
keyOfFunction · 0.70

Tested by

no test coverage detected