The essentials

Quick reference

One focused task per row. Jump to the related section for complete, working examples.

UseSyntaxExamples
Import by namemodule = importlib.import_module('package.module')View examples
Resolve a relative importmodule = importlib.import_module('.codec', package='app.plugins')View examples
Find a module specificationspec = importlib.util.find_spec('package.module')View examples
Invalidate finder cachesimportlib.invalidate_caches()View examples
Read a distribution versionrelease = importlib.metadata.version('distribution-name')View examples
Read core metadatadetails = importlib.metadata.metadata('distribution-name')View examples
Read declared requirementsrequirements = importlib.metadata.requires('distribution-name') or []View examples
Map import to distributionsowners = importlib.metadata.packages_distributions().get('import_name', [])View examples
Get a resource rootroot = importlib.resources.files('package_name')View examples
Read a text resourcetext = root.joinpath('data/defaults.ini').read_text(encoding='utf-8')View examples
Materialize a resource pathwith importlib.resources.as_file(resource) as path: consume(path)View examples
Discover a plugin groupplugins = importlib.metadata.entry_points(group='acme.plugins')View examples
Select one entry pointmatches = plugins.select(name='formatter')View examples
Load a plugin objectplugin = entry_point.load()View examples
Handle missing distribution metadataexcept importlib.metadata.PackageNotFoundError: use_fallback()View examples

importlib exposes Python's import machinery while metadata and resources provide supported ways to inspect installed distributions and package data. Dynamic importing and entry-point loading execute code, so discovery can be broad but loading must be governed by explicit trust, compatibility, isolation, and failure policy.

Step by step

Detailed examples

01

Import modules through the supported public API

Use import_module rather than calling __import__ directly. Imported top-level code runs once per module object and the result is cached in sys.modules. Validate dynamic names against an allowlist; importing arbitrary user input is arbitrary code execution. find_spec is useful for capability checks, though searching a dotted name may import its parent package.

Import and inspect a standard-library module
import importlib
import importlib.util

module = importlib.import_module('json')
spec = importlib.util.find_spec('json')
print(module.dumps({'ready': True}, sort_keys=True))
print(spec.name)
print(spec.loader is not None)
Output
{"ready": true}
json
True
Back to quick reference ↑
02

Keep distribution names separate from import names

importlib.metadata reads discoverable dist-info or egg-info records from installed distributions. A distribution can provide several import packages, and a namespace package can be supplied by several distributions, so names are not a one-to-one mapping. Treat version strings as opaque packaging versions unless a standards-aware parser interprets them, and handle PackageNotFoundError for optional dependencies.

Handle absent distribution metadata
from importlib.metadata import PackageNotFoundError, version

try:
    version('cmdmemo-package-that-does-not-exist')
except PackageNotFoundError as error:
    print(type(error).__name__)
    print(error.name)
Output
PackageNotFoundError
cmdmemo-package-that-does-not-exist
Back to quick reference ↑
03

Read data without assuming a filesystem layout

resources.files returns a Traversable tree that can represent a directory, zip import, or custom loader. Join trusted relative components and use read_text, read_bytes, or open methods. When an external API demands pathlib.Path, as_file materializes a resource for the context duration; do not retain that temporary path after the context closes. The anchor parameter name replaced package in Python 3.12, while positional use remains the broad compatibility choice.

Inspect a resource in the email package
from importlib.resources import files

resource = files('email').joinpath('__init__.py')
print(resource.name)
print(resource.is_file())
print('email' in resource.read_text(encoding='utf-8').lower())
Output
__init__.py
True
True
Back to quick reference ↑
04

Discover plugins through a private entry-point group

Entry points are distribution metadata records with a group, name, and import target. Use a namespaced group owned by the host application and select that group directly. Python 3.10 introduced the selectable interface, Python 3.12 standardized returning EntryPoints, and Python 3.13 removed tuple-like EntryPoint access; use named attributes and select rather than legacy dictionary or index behavior.

Select entry-point records without importing them
from importlib.metadata import EntryPoint, EntryPoints

points = EntryPoints([
    EntryPoint(name='upper', value='builtins:str.upper', group='demo.formatters'),
    EntryPoint(name='size', value='builtins:len', group='demo.metrics'),
])
selected = points.select(group='demo.formatters')
print([(point.name, point.value) for point in selected])
print(next(iter(selected)).module)
Output
[('upper', 'builtins:str.upper')]
builtins
Back to quick reference ↑
05

Make loading an explicit trust decision

EntryPoint.load imports the target module and resolves its object, so a malicious or compromised installed distribution gets code execution. Validate allowed distributions and API versions before loading; then isolate plugins in a separate process or stronger sandbox when the threat model requires it. Catch failures per plugin, avoid exposing host secrets by default, and define startup, timeout, shutdown, and compatibility contracts.

Load a controlled entry-point target
from importlib.metadata import EntryPoint

point = EntryPoint(name='length', value='builtins:len', group='demo.safe')
plugin = point.load()
print(plugin(['a', 'b', 'c']))
print((point.name, point.module, point.attr))
Output
3
('length', 'builtins', 'len')
Back to quick reference ↑

Local code tester

Discover and load one controlled plugin

Create entry-point metadata in memory, select the application group, and load a trusted standard-library target.

Runs in your browser
Output
Press Run to load Python locally.

Sources and further reading

References

Authoritative documentation used to verify and expand this cheat sheet.

  1. Python Software Foundationimportlib — The implementation of importdocs.python.org
  2. Python Software Foundationimportlib.metadata — Accessing package metadatadocs.python.org
  3. Python Software Foundationimportlib.resources — Package resource reading, opening and accessdocs.python.org
  4. Python Packaging AuthorityEntry points specificationpackaging.python.org

Help us improve

Found a typo or missing example?

Tell us what would make this cheat sheet clearer, more complete, or more useful.

Share feedback