The essentials
Quick reference
One focused task per row. Jump to the related section for complete, working examples.
| Use | Syntax | Examples |
|---|---|---|
| Import by name | module = importlib.import_module('package.module') | View examples |
| Resolve a relative import | module = importlib.import_module('.codec', package='app.plugins') | View examples |
| Find a module specification | spec = importlib.util.find_spec('package.module') | View examples |
| Invalidate finder caches | importlib.invalidate_caches() | View examples |
| Read a distribution version | release = importlib.metadata.version('distribution-name') | View examples |
| Read core metadata | details = importlib.metadata.metadata('distribution-name') | View examples |
| Read declared requirements | requirements = importlib.metadata.requires('distribution-name') or [] | View examples |
| Map import to distributions | owners = importlib.metadata.packages_distributions().get('import_name', []) | View examples |
| Get a resource root | root = importlib.resources.files('package_name') | View examples |
| Read a text resource | text = root.joinpath('data/defaults.ini').read_text(encoding='utf-8') | View examples |
| Materialize a resource path | with importlib.resources.as_file(resource) as path: consume(path) | View examples |
| Discover a plugin group | plugins = importlib.metadata.entry_points(group='acme.plugins') | View examples |
| Select one entry point | matches = plugins.select(name='formatter') | View examples |
| Load a plugin object | plugin = entry_point.load() | View examples |
| Handle missing distribution metadata | except 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
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 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) {"ready": true}
json
TrueKeep 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.
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) PackageNotFoundError
cmdmemo-package-that-does-not-existRead 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.
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()) __init__.py
True
TrueDiscover 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.
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) [('upper', 'builtins:str.upper')]
builtinsMake 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.
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)) 3
('length', 'builtins', 'len')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.
Press Run to load Python locally.
Sources and further reading
References
Authoritative documentation used to verify and expand this cheat sheet.
- Python Software Foundationimportlib — The implementation of importdocs.python.org
- Python Software Foundationimportlib.metadata — Accessing package metadatadocs.python.org
- Python Software Foundationimportlib.resources — Package resource reading, opening and accessdocs.python.org
- 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.



