importlib Imports Modules By Dotted Name

Load a module by dotted name with importlib, reload it in place, and inspect a spec with find_spec without executing the module.

PythonConfig Management

Code

pythonsnippet
34 lines
import importlib
import importlib.util
import sys
import tempfile
from pathlib import Path


def main() -> None:
    with tempfile.TemporaryDirectory() as tmp:
        module_path = Path(tmp) / 'inventory.py'
        module_path.write_text(
            'STOCK = {"bolt": 12}\n\n'
            'def count(sku):\n'
            '    return STOCK.get(sku, 0)\n',
            encoding='utf-8',
        )
        sys.path.insert(0, tmp)
        try:
            module = importlib.import_module('inventory')
            print('module file:', Path(module.__file__).name)
            print('count:', module.count('bolt'))
            print('reload keeps object:', importlib.reload(module) is module)
        finally:
            sys.path.remove(tmp)
            sys.modules.pop('inventory', None)

    # find_spec 只探测模块位置,不执行模块代码
    spec = importlib.util.find_spec('json')
    print('json spec found:', spec is not None)
    print('json origin:', Path(spec.origin).name if spec and spec.origin else None)


if __name__ == '__main__':
    main()

How it works

Count the functions main and count as the entire surface area of importlib Imports Modules By Dotted Name.

From importlib it pulls Path — the imports name exactly which library surface the snippet touches.

Points of care

  • Plan for an install step: importlib is a real dependency, resolved by the package manager.

Applying it

Look for the module file:, count:, reload keeps object: prefixes when the file runs; they tie each line to its step.

Launch the file; main takes over and steps through count.

Interactive Tools for This Topic

FAQ

Which packages must be installed first?
Yes. The imports resolve to `importlib`, which the package manager must provide.