Skip to content

Python: import-module + module.func() calls silently dropped outside package roots (module-arm resolver never matches, dangling import-edge id) #3430

Closed

Description

@LucasPedroso96

Summary

import module + module.func() calls (as opposed to from module import func) silently produce no calls edge whenever the importing file lives in a directory one or more levels below the scan root and that directory has no __init__.py — i.e. any flat/namespace-style module layout, which is extremely common (a scripts/, src/, or tool directory of sibling .py files with no package markers). The qualified call is dropped with no warning; the callee node simply has in-degree 0, indistinguishable from genuine dead code.

This is a real regression in an otherwise-working feature, not a "we don't support this" limitation — _resolve_python_member_calls's module arm (extract.py, PR-referenced as #1883 in its comments) is specifically designed to resolve exactly this pattern. It's an ID-generation mismatch upstream of it that starves it of a match.

Root cause

  1. File nodes get a directory-prefixed id. _file_node_id() (extract.py:187) builds a file's own node id as {parent_dir}_{stem} — one parent directory level, e.g. scripts/greeter.py → scripts_greeter.

  2. Plain import edges don't. _import_python()'s import_statement branch (extract.py:325-348) builds the import edge's target id from the bare module name alone:

    module_name = raw_module.strip().lstrip(".")
    tgt_nid = _make_id(module_name)  # "greeter" -> "greeter", NOT "scripts_greeter"

    No filesystem lookup, no directory context — make_id() (ids.py:86) just normalizes the literal string. So for import greeter inside scripts/main.py, the edge becomes scripts_main --imports--> greeter, while the actual file node is scripts_greeter. They never match.

  3. The module-arm resolver depends on that match. _resolve_python_member_calls() (extract.py:3310), when it sees a qualified call greeter.say_hello(), looks up the caller file's imported targets and keeps only the ones present in contains_children — i.e. the ones that are real, resolvable file nodes:

    mods = [t for t in imported_by_filenode.get(caller_file, ())
            if t in contains_children
            and (_module_stem_key(t) == rkey or file_aliases.get(t) == rkey)]
    if len(mods) != 1:
        continue

    Since the import edge's target is greeter and the real file node is scripts_greeter, t in contains_children is False for every candidate, mods ends up empty, and the resolver bails silently. No edge is emitted anywhere — symbol_resolution.py's fallback resolvers also explicitly skip member calls (is_member_call guard, by design, since a bare receiver-less method name is ambiguous), so there is no second chance to catch it.

  4. A fix for the analogous case already exists, but its guard excludes this shape. _repoint_python_package_imports() (extract.py:197, referenced as #2072) was added to repoint exactly this kind of dangling import-edge id — but only for real Python packages:

    while levels < len(parts) - 1 and (d / "__init__.py").is_file():
        levels += 1
        d = d.parent
    if levels == 0:
        continue  # not inside a package (namespace pkg / loose module)

    A directory with no __init__.py — a plain script folder, or a PEP 420 namespace package, both common — takes levels == 0 and is skipped entirely. The repoint logic that would fix this never runs for it.

Minimal reproduction

repo/
└── scripts/
    ├── greeter.py
    └── main.py

scripts/greeter.py:

def say_hello(name: str) -> str:
    return f"Hello, {name}!"

scripts/main.py:

import greeter

def run() -> None:
    print(greeter.say_hello("world"))

Running graphify.extract.extract() from repo/ (i.e. repo/ is the scan root, scripts/ is not a package — no __init__.py) on both files produces:

nodes: scripts_greeter, scripts_greeter_say_hello, scripts_main, scripts_main_run
edges:
  scripts_greeter -- contains --> scripts_greeter_say_hello
  scripts_main -- imports --> greeter          # <- dangling: no node has this id
  scripts_main -- contains --> scripts_main_run

Expected: a fourth edge, scripts_main_run -- calls --> scripts_greeter_say_hello.
Actual: it's absent. scripts_greeter_say_hello has in-degree 0.

Confirmed this is scan-root-relative, not something inherent to member calls in general: running extract() with scripts/ itself passed as the scan root (so both files sit at the "top level" and get unprefixed ids greeter/main) produces the calls edge correctly — same two files, same call, only the root changed.

Impact

Any codebase organized as a flat directory of sibling scripts (no __init__.py) that prefers import module + module.func() over from module import func — which is arguably the more idiomatic form, since it keeps call sites self-documenting and avoids polluting the caller's namespace — will have its cross-file call edges for that directory systematically dropped whenever the tool is pointed at the directory's parent rather than the directory itself. Since graphify's dead-code/god-node/community-detection output is exactly what a user leans on to find unused code, this produces false-positive "orphan" signals for modules that are, in fact, actively called — the more central and widely-used a module is (a shared utils/paths/config-style module imported by many siblings), the worse the apparent disconnect looks, which is the opposite of what such a module's graph position should show.

Suggested fix

Extend _repoint_python_package_imports() (or add a sibling pass using the same alias-map machinery) to also cover the no-__init__.py case: when a bare import X edge's target make_id(X) doesn't match any node id, but the importing file's own directory contains a sibling X.py that is in the scanned corpus, repoint the edge to that sibling's real file-node id. This can stay conservative — same directory only, single unambiguous candidate only — mirroring the existing pass's len(fs) == 1 guard, so it wouldn't need to solve general sys.path resolution, just the common "importing a sibling in the same loose directory" case that today falls through the levels == 0 gap.

Environment

  • graphifyy 0.9.56 (PyPI)
  • Windows 11, Python 3.13.6
  • Reproduced from scratch on the two-file layout above — not dependent on any project-specific configuration, cache, or prior state.

Activity

  1. Ashfaqbs commented on Sep 10, 2026

    @Ashfaqbs

    Reproduced the outward symptom — a plain import module + module.func() call genuinely produces no calls edge — but on current main (91f4d12) none of the functions/mechanism cited here (_file_node_id, _repoint_python_package_imports, _resolve_python_member_calls, contains_children, symbol_resolution.py) exist. I couldn't find any of them anywhere in the tree, so I want to share what I actually found before anyone builds against the description above.

    What extract_python (graphify/extract.py) actually does today:

    • File-level ids are always the bare stem (_make_id(stem), extract.py:64) — there is no directory-prefixed id anywhere, so the "scripts_greeter vs greeter" id-mismatch this issue describes doesn't apply. I confirmed this directly: on your exact two-file repro, main.py's imports edge target (greeter) and greeter.py's real file-node id (greeter) are identical strings — no dangling id.
    • The actual reason no calls edge appears: the call-graph pass (extract.py:152-198) builds label_to_nid purely from the nodes collected while walking this one file (see the nodes list built during walk(root) a few lines above it). extract_python is invoked once per file with no cross-file context, so say_hello is simply never in main.py's own label_to_nid — it's not an id-mismatch, there's no cross-file call resolution at all for attribute-style calls, regardless of directory layout or __init__.py presence.
    • This is a different limitation than _resolve_cross_file_imports (extract.py:2123), which does have cross-file logic, but only for from .module import Name → it emits uses edges from same-file classes to the imported name, and never looks at call expressions. Plain import module (no from) isn't part of that pass, and neither from- nor plain-import attribute calls get a calls edge produced anywhere.

    Repro (ran against current main, tree-sitter-python installed locally):

    greeter.py nodes: ['greeter', 'greeter_say_hello']
    main.py nodes: ['main', 'main_run']
    main.py edges: [imports main->greeter, contains main->main_run]
    

    No calls edge, as you described — just not for the id-mismatch reason.

    Proposed direction, scoped to what's actually here: extend _resolve_cross_file_imports's two-pass shape (or add a sibling pass reusing its stem_to_entities map) to also index top-level functions, not just classes, and to handle plain import module targets (matching attribute call nodes like module.func() against stem_to_entities[module]), the same way it currently matches from module import func names against local classes. That reuses the existing merge point in the pipeline that already has all per-file results in hand, rather than trying to make single-file extract_python calls aware of each other.

    Happy to put together a PR for this if useful — wanted to flag the mismatch between the description and current source first, in case this was drafted against a different branch/fork or an older version, since a fix built on the cited functions wouldn't apply to what's actually running.

  2. safishamsi commented on Sep 10, 2026

    @safishamsi
    Member
  3. Ashfaqbs commented on Sep 11, 2026

    @Ashfaqbs

    Correction to my earlier comment for the record: I'd checked main, not realizing this repo actually develops on v8 (main is ~1699 commits behind) — the functions I said didn't exist were real, just on the branch I hadn't checked. Doesn't change the outcome here since this already shipped in v0.9.58, but didn't want the wrong "fabricated" claim to stand uncorrected. I'll check v8 first for anything else in this repo.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions