On this page
  1. modulefinder
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Detecting Missing or Optional Dependencies
  7. Gotchas & Boundaries
  8. Common Functions
  9. Classes & Objects
  10. Constants & Attributes

modulefinder

Prev: mmap | Up: stdlib_module | Next: msvcrt
Rel: sys, sysconfig, builtins, warnings, dataclasses
Ref: docs.python.org — modulefinder
Tags: #public #python3 #stdlib


Import

import modulefinder

Overview

Static import-graph analyzer (ModuleFinder) that inspects bytecode to discover all modules a Python script imports, along with missing (badmodules) imports. Use modulefinder to audit script dependencies, build custom bundlers/packagers, or verify that a standalone script has no unexpected third-party imports.

Quick Start

import modulefinder
from pathlib import Path
import tempfile

with tempfile.TemporaryDirectory() as tmp:
    script = Path(tmp) / "app.py"
    script.write_text("import json\nimport pathlib\n", encoding="utf-8")

    finder = modulefinder.ModuleFinder()
    finder.run_script(str(script))
    assert "json" in finder.modules and "pathlib" in finder.modules

Implementation Walkthrough

1. Detecting Missing or Optional Dependencies

finder.badmodules maps unresolved module names to the modules that tried to import them:

import modulefinder
from pathlib import Path
import tempfile

with tempfile.TemporaryDirectory() as tmp:
    script = Path(tmp) / "check.py"
    script.write_text("import nonexistent_pkg_xyz\n", encoding="utf-8")

    finder = modulefinder.ModuleFinder()
    finder.run_script(str(script))
    assert "nonexistent_pkg_xyz" in finder.badmodules

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes