importExpert Examples

Loads a module or package into the current namespace

Import machinery internals

How Python's import system works under the hood.

python
import sys
import importlib

# Module cache
print(f"Cached modules: {len(sys.modules)}")
print(f"json cached: {'json' in sys.modules}")

import json
print(f"json cached after import: {'json' in sys.modules}")

# Import hooks and finders
print(f"\nMeta path finders:")
for finder in sys.meta_path:
    print(f"  {type(finder).__name__}")

print(f"\nPath hooks:")
for hook in sys.path_hooks:
    print(f"  {type(hook).__name__}")

# Module spec
spec = importlib.util.find_spec("json")
print(f"\njson spec: {spec}")
print(f"  origin: {spec.origin}")

Python's import system uses finders and loaders. sys.meta_path holds finders that locate modules. sys.modules caches imported modules. Understanding this enables custom import hooks.

Want to try these examples interactively?

Open Expert Playground