Read metadata from Python packages, providing third-party access to importlib.metadata functionality
npx @tessl/cli install tessl/pypi-importlib-metadata@8.7.00
# importlib_metadata
1
2
A library providing third-party access to the functionality of `importlib.metadata`, allowing Python applications to read metadata from installed packages. It serves as a backport and enhancement of the standard library's `importlib.metadata` module, offering compatibility across different Python versions and additional features.
3
4
The library enables developers to discover package metadata, entry points, files, and dependencies programmatically, making it essential for tools that need to introspect installed packages. It supports both modern package formats (dist-info) and legacy formats (egg-info), provides efficient path searching and caching mechanisms, and offers a comprehensive API for package discovery and metadata extraction.
5
6
## Package Information
7
8
- **Package Name**: importlib_metadata
9
- **Language**: Python
10
- **Installation**: `pip install importlib_metadata`
11
- **Requires**: Python >=3.9
12
13
## Core Imports
14
15
```python
16
import importlib_metadata
17
```
18
19
Common imports for specific functionality:
20
21
```python
22
from importlib_metadata import (
23
Distribution,
24
PackageNotFoundError,
25
distribution,
26
distributions,
27
entry_points,
28
files,
29
metadata,
30
packages_distributions,
31
requires,
32
version
33
)
34
```
35
36
## Basic Usage
37
38
```python
39
import importlib_metadata
40
41
# Get version of an installed package
42
pkg_version = importlib_metadata.version('requests')
43
print(f"requests version: {pkg_version}")
44
45
# Get distribution object for a package
46
dist = importlib_metadata.distribution('requests')
47
print(f"Package name: {dist.name}")
48
print(f"Version: {dist.version}")
49
50
# Get package metadata
51
meta = importlib_metadata.metadata('requests')
52
print(f"Summary: {meta['Summary']}")
53
print(f"Author: {meta['Author']}")
54
55
# Get entry points from all packages
56
eps = importlib_metadata.entry_points()
57
console_scripts = eps.select(group='console_scripts')
58
for ep in console_scripts:
59
print(f"Script: {ep.name} -> {ep.value}")
60
61
# Get files in a package
62
package_files = importlib_metadata.files('requests')
63
if package_files:
64
for file_path in package_files[:5]: # Show first 5 files
65
print(f"File: {file_path}")
66
67
# Get package dependencies
68
deps = importlib_metadata.requires('requests')
69
if deps:
70
for dep in deps:
71
print(f"Dependency: {dep}")
72
```
73
74
## Architecture
75
76
The importlib_metadata library follows a layered architecture:
77
78
- **Distribution Classes**: Abstract and concrete implementations for accessing package metadata
79
- **Entry Point System**: Comprehensive handling of package entry points with selection and filtering
80
- **Path and File Management**: Efficient traversal and caching of package installation paths
81
- **Metadata Protocols**: Type-safe interfaces for accessing package metadata
82
- **Finder System**: Pluggable discovery mechanism for locating package distributions
83
84
This design allows the library to work across different package installation methods, Python versions, and package formats while maintaining performance through caching and lazy loading.
85
86
## Capabilities
87
88
### Core Functions
89
90
Primary API functions for accessing package information including version lookup, distribution objects, metadata access, entry points, files, and dependencies.
91
92
```python
93
def distribution(distribution_name: str) -> Distribution: ...
94
def distributions(**kwargs) -> Iterable[Distribution]: ...
95
def metadata(distribution_name: str) -> PackageMetadata | None: ...
96
def version(distribution_name: str) -> str: ...
97
def entry_points(**params) -> EntryPoints: ...
98
def files(distribution_name: str) -> list[PackagePath] | None: ...
99
def requires(distribution_name: str) -> list[str] | None: ...
100
def packages_distributions() -> Mapping[str, list[str]]: ...
101
``` { .api }
102
103
[Core Functions](./core-functions.md)
104
105
### Distribution Classes
106
107
Distribution classes provide object-oriented access to package metadata, including abstract base classes and concrete implementations for different package formats.
108
109
```python { .api }
110
class Distribution(metaclass=abc.ABCMeta):
111
@abc.abstractmethod
112
def read_text(self, filename) -> str | None: ...
113
@abc.abstractmethod
114
def locate_file(self, path: str | os.PathLike[str]) -> SimplePath: ...
115
116
@classmethod
117
def from_name(cls, name: str) -> Distribution: ...
118
@classmethod
119
def discover(cls, *, context=None, **kwargs) -> Iterable[Distribution]: ...
120
121
@property
122
def metadata(self) -> PackageMetadata | None: ...
123
@property
124
def name(self) -> str: ...
125
@property
126
def version(self) -> str: ...
127
```
128
129
[Distribution Classes](./distribution-classes.md)
130
131
### Entry Points System
132
133
Comprehensive entry point discovery and management, including entry point objects, collections, and selection mechanisms for package-defined executable scripts and plugins.
134
135
```python { .api }
136
class EntryPoint:
137
name: str
138
value: str
139
group: str
140
dist: Distribution | None
141
142
def load(self) -> Any: ...
143
def matches(self, **params) -> bool: ...
144
145
class EntryPoints(tuple):
146
def select(self, **params) -> EntryPoints: ...
147
def __getitem__(self, name: str) -> EntryPoint: ...
148
149
@property
150
def names(self) -> set[str]: ...
151
@property
152
def groups(self) -> set[str]: ...
153
```
154
155
[Entry Points System](./entry-points.md)
156
157
### Path and File Management
158
159
File path handling and package file enumeration, including path objects, file hashing, and file access methods for package contents.
160
161
```python { .api }
162
class PackagePath(pathlib.PurePosixPath):
163
hash: FileHash | None
164
size: int
165
dist: Distribution
166
167
def read_text(self, encoding: str = 'utf-8') -> str: ...
168
def read_binary(self) -> bytes: ...
169
def locate(self) -> SimplePath: ...
170
171
class FileHash:
172
mode: str
173
value: str
174
```
175
176
[Path and File Management](./path-file-management.md)
177
178
## Types
179
180
Core type definitions used throughout the API:
181
182
```python { .api }
183
class PackageNotFoundError(ModuleNotFoundError):
184
"""Exception raised when package metadata cannot be found."""
185
@property
186
def name(self) -> str: ...
187
188
# Protocol interfaces
189
class PackageMetadata(Protocol):
190
"""
191
Protocol for accessing package metadata as a mapping-like object.
192
193
This protocol defines the interface for metadata objects returned by
194
Distribution.metadata, providing dictionary-like access to package
195
metadata fields as defined by Python packaging standards.
196
"""
197
198
def __len__(self) -> int:
199
"""Return the number of metadata fields."""
200
201
def __contains__(self, item: str) -> bool:
202
"""Check if a metadata field exists."""
203
204
def __getitem__(self, key: str) -> str:
205
"""Get a metadata field value. Raises KeyError if not found."""
206
207
def __iter__(self) -> Iterator[str]:
208
"""Iterate over metadata field names."""
209
210
def get(self, name: str, failobj=None) -> str | None:
211
"""Get a metadata field value, returning failobj if not found."""
212
213
def get_all(self, name: str, failobj=None) -> list[Any] | None:
214
"""Get all values for a metadata field (for multi-valued fields)."""
215
216
@property
217
def json(self) -> dict[str, str | list[str]]:
218
"""Return metadata as a JSON-serializable dictionary."""
219
220
class SimplePath(Protocol):
221
"""
222
A minimal subset of pathlib.Path required by Distribution.
223
224
This protocol defines the interface that path objects must implement
225
to work with the importlib_metadata system. It provides the essential
226
path operations needed for accessing package files and metadata.
227
"""
228
229
def joinpath(self, other: str | os.PathLike[str]) -> SimplePath:
230
"""
231
Join this path with another path component.
232
233
Parameters:
234
- other: Path component to join
235
236
Returns:
237
SimplePath: New path with component joined
238
"""
239
240
def __truediv__(self, other: str | os.PathLike[str]) -> SimplePath:
241
"""
242
Path division operator (/) for joining paths.
243
244
Parameters:
245
- other: Path component to join
246
247
Returns:
248
SimplePath: New path with component joined
249
"""
250
251
@property
252
def parent(self) -> SimplePath:
253
"""
254
Return the parent directory of this path.
255
256
Returns:
257
SimplePath: Parent directory path
258
"""
259
260
def read_text(self, encoding=None) -> str:
261
"""
262
Read the file as text.
263
264
Parameters:
265
- encoding: Text encoding (optional, defaults to locale encoding)
266
267
Returns:
268
str: File contents as text
269
270
Raises:
271
FileNotFoundError: If file doesn't exist
272
UnicodeDecodeError: If file cannot be decoded as text
273
"""
274
275
def read_bytes(self) -> bytes:
276
"""
277
Read the file as binary data.
278
279
Returns:
280
bytes: File contents as bytes
281
282
Raises:
283
FileNotFoundError: If file doesn't exist
284
"""
285
286
def exists(self) -> bool:
287
"""
288
Check if the path exists.
289
290
Returns:
291
bool: True if path exists, False otherwise
292
"""
293
```