On this page
  1. importlib
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Reading Packaged Data Files with importlib.resources
  7. 2. Explicit Plugin Discovery via importlib.metadata.entry_points
  8. Gotchas & Boundaries
  9. Common Functions

importlib

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


Import

import importlib

Overview

Programmatic interface to Python's import system (import_module), installed package metadata and entry points (importlib.metadata), and bundled non-code package assets (importlib.resources). Reach for importlib.metadata for plugin discovery and version lookup, and importlib.resources instead of fragile __file__ path hacks for reading packaged templates or schemas.

Quick Start

import importlib
from importlib import metadata

math_mod = importlib.import_module("math")
assert math_mod.sqrt(16) == 4.0

# Discover installed entry points for a plugin group:
eps = metadata.entry_points(group="console_scripts")
assert hasattr(eps, "select")

Implementation Walkthrough

1. Reading Packaged Data Files with importlib.resources

Works cleanly across editable installs, wheels, and zipapps without relying on __file__:

from importlib import resources

def read_packaged_text(package: str, filename: str) -> str:
    return resources.files(package).joinpath(filename).read_text(encoding="utf-8")

2. Explicit Plugin Discovery via importlib.metadata.entry_points

from importlib import metadata

def list_plugins(group: str) -> dict[str, str]:
    return {ep.name: ep.value for ep in metadata.entry_points(group=group)}

Gotchas & Boundaries

Common Functions

Linked from

Related notes