Skip to content

Classify imports in except* ImportError blocks as conditional #63

Description

@TristanKruse

Problem

On Python 3.11+, imports protected by except* ImportError remain in the graph but are labeled as ordinary imports rather than ImportKind.CONDITIONAL_IMPORT.

try:
    import optional_pkg
except* ImportError:
    pass

The equivalent except ImportError block is classified as conditional. In the current extractor, parsing the example above produces an ast.TryStar; _import_analysis_nodes retains only ast.Try among try nodes, and _find_conditional_import_ranges also accepts only ast.Try. A local reproduction returned an Import node and no conditional ranges. This behavior predates PRs #60–#62; it was exposed during their edge-case review, not caused by those optimizations.

Why it matters

The dependency is not missing. Its context metadata is wrong, so graph consumers or rules that distinguish ordinary from optional/conditional imports can misinterpret it. We should correct classification without broadening dynamic analysis or changing import resolution.

Suggested implementation

  1. Retain ast.TryStar as an import-analysis context node where the runtime provides it, while keeping Python 3.10 compatibility (no unconditional ast.TryStar reference at import time).
  2. Apply the existing ImportError/ModuleNotFoundError handler and statement-range logic to both ast.Try and ast.TryStar.
  3. Keep the current semantics: imports in the protected body and matching handler body are conditional; unrelated handlers and finally are not.

Acceptance tests

  • On Python 3.11+, except* ImportError and except* ModuleNotFoundError label the guarded import as CONDITIONAL_IMPORT while preserving its syntax kind and resolved target.
  • A non-import-error except* handler does not classify imports as conditional.
  • Mixed handlers classify only the relevant handler body; nesting, else, and finally follow the same rules as ordinary try blocks.
  • Existing ordinary try/except ImportError tests and the Python 3.10–3.13 CI matrix remain green.

Activity

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

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions