0
# pkg_resources (Deprecated)
1
2
**DEPRECATED:** The pkg_resources module is deprecated and users are directed to use `importlib.resources`, `importlib.metadata`, and the `packaging` library instead. However, it remains available for backward compatibility and is still widely used in existing codebases.
3
4
pkg_resources provides runtime package discovery and resource access capabilities for Python packages, including distribution discovery, entry point loading, resource file access, and namespace package management.
5
6
## Core Imports
7
8
```python
9
import pkg_resources
10
```
11
12
Common imports:
13
```python
14
from pkg_resources import (
15
require, get_distribution, load_entry_point,
16
resource_string, resource_filename, working_set
17
)
18
```
19
20
## Capabilities
21
22
### Resource Access Functions
23
24
Functions for accessing files and data contained within Python packages at runtime.
25
26
```python { .api }
27
def resource_string(package_or_requirement, resource_name):
28
"""
29
Return the contents of a resource file as bytes.
30
31
Parameters:
32
- package_or_requirement (str | Requirement): Package name or requirement
33
- resource_name (str): Path to resource within package
34
35
Returns:
36
bytes: Resource file contents
37
38
Raises:
39
ModuleNotFoundError: If package not found
40
FileNotFoundError: If resource not found
41
"""
42
43
def resource_stream(package_or_requirement, resource_name):
44
"""
45
Return a readable file-like object for a resource.
46
47
Parameters:
48
- package_or_requirement (str | Requirement): Package name or requirement
49
- resource_name (str): Path to resource within package
50
51
Returns:
52
IO[bytes]: File-like object for reading resource
53
"""
54
55
def resource_filename(package_or_requirement, resource_name):
56
"""
57
Return filesystem path to a resource, extracting if necessary.
58
59
Parameters:
60
- package_or_requirement (str | Requirement): Package name or requirement
61
- resource_name (str): Path to resource within package
62
63
Returns:
64
str: Filesystem path to resource file
65
"""
66
67
def resource_listdir(package_or_requirement, resource_name):
68
"""
69
List contents of a resource directory.
70
71
Parameters:
72
- package_or_requirement (str | Requirement): Package name or requirement
73
- resource_name (str): Path to directory within package
74
75
Returns:
76
list[str]: List of resource names in directory
77
"""
78
79
def resource_exists(package_or_requirement, resource_name):
80
"""
81
Check if a resource exists within a package.
82
83
Parameters:
84
- package_or_requirement (str | Requirement): Package name or requirement
85
- resource_name (str): Path to resource within package
86
87
Returns:
88
bool: True if resource exists
89
"""
90
91
def resource_isdir(package_or_requirement, resource_name):
92
"""
93
Check if a resource is a directory.
94
95
Parameters:
96
- package_or_requirement (str | Requirement): Package name or requirement
97
- resource_name (str): Path to resource within package
98
99
Returns:
100
bool: True if resource is a directory
101
"""
102
```
103
104
### Distribution Discovery
105
106
Functions for finding and working with installed Python distributions.
107
108
```python { .api }
109
def get_distribution(requirement):
110
"""
111
Get a Distribution object for an installed package.
112
113
Parameters:
114
- requirement (str | Requirement | Distribution): Package specification
115
116
Returns:
117
Distribution: Distribution object for the package
118
119
Raises:
120
DistributionNotFound: If package not found
121
VersionConflict: If version requirements not met
122
"""
123
124
def require(*requirements):
125
"""
126
Ensure that distributions matching requirements are available.
127
128
Parameters:
129
- *requirements (str | Requirement): Package requirements
130
131
Returns:
132
list[Distribution]: List of required distributions
133
134
Raises:
135
DistributionNotFound: If any requirement cannot be satisfied
136
VersionConflict: If version conflicts exist
137
"""
138
139
def find_distributions(path_item, only=False):
140
"""
141
Find distributions in a path item.
142
143
Parameters:
144
- path_item (str): Path to search for distributions
145
- only (bool): If True, only return distributions in this exact path
146
147
Returns:
148
Iterator[Distribution]: Found distributions
149
"""
150
151
def get_provider(package_or_requirement):
152
"""
153
Get resource provider for a package.
154
155
Parameters:
156
- package_or_requirement (str | Requirement): Package specification
157
158
Returns:
159
IResourceProvider: Resource provider for the package
160
"""
161
```
162
163
### Entry Point Management
164
165
Functions for discovering and loading entry points defined by packages.
166
167
```python { .api }
168
def load_entry_point(dist, group, name):
169
"""
170
Load and return an entry point.
171
172
Parameters:
173
- dist (str | Requirement | Distribution): Distribution specification
174
- group (str): Entry point group name
175
- name (str): Entry point name
176
177
Returns:
178
Any: The loaded entry point object
179
180
Raises:
181
ImportError: If entry point cannot be loaded
182
AttributeError: If entry point attribute not found
183
"""
184
185
def get_entry_map(dist, group=None):
186
"""
187
Get entry point map for a distribution.
188
189
Parameters:
190
- dist (str | Requirement | Distribution): Distribution specification
191
- group (str, optional): Specific group to get, or None for all groups
192
193
Returns:
194
dict: Entry point map (group -> name -> EntryPoint)
195
"""
196
197
def get_entry_info(dist, group, name):
198
"""
199
Get entry point info without loading.
200
201
Parameters:
202
- dist (str | Requirement | Distribution): Distribution specification
203
- group (str): Entry point group name
204
- name (str): Entry point name
205
206
Returns:
207
EntryPoint | None: Entry point object or None if not found
208
"""
209
210
def iter_entry_points(group, name=None):
211
"""
212
Iterate over entry points in working set.
213
214
Parameters:
215
- group (str): Entry point group name
216
- name (str, optional): Specific entry point name
217
218
Returns:
219
Iterator[EntryPoint]: Matching entry points
220
"""
221
```
222
223
### Environment Management
224
225
Functions for managing the Python environment and package working sets.
226
227
```python { .api }
228
working_set: WorkingSet
229
"""Global working set of installed distributions."""
230
231
def add_activation_listener(callback, existing=True):
232
"""
233
Add callback to be called when distributions are activated.
234
235
Parameters:
236
- callback (callable): Function to call on activation
237
- existing (bool): Whether to call for existing distributions
238
"""
239
240
def declare_namespace(name):
241
"""
242
Declare a namespace package.
243
244
Parameters:
245
- name (str): Namespace package name
246
"""
247
248
def set_extraction_path(path):
249
"""
250
Set path for extracting resources from zip files.
251
252
Parameters:
253
- path (str): Directory path for extraction
254
"""
255
256
def cleanup_resources(force=False):
257
"""
258
Clean up extracted resources.
259
260
Parameters:
261
- force (bool): Whether to force cleanup
262
"""
263
264
def get_default_cache():
265
"""
266
Get default cache directory for extracted resources.
267
268
Returns:
269
str: Default cache directory path
270
"""
271
```
272
273
### Parsing and Utilities
274
275
Utility functions for parsing requirements, versions, and handling package metadata.
276
277
```python { .api }
278
def parse_requirements(strs):
279
"""
280
Parse requirement strings.
281
282
Parameters:
283
- strs (str | Iterable[str]): Requirement string(s) to parse
284
285
Returns:
286
Iterator[Requirement]: Parsed requirement objects
287
"""
288
289
def parse_version(version):
290
"""
291
Parse a version string.
292
293
Parameters:
294
- version (str): Version string to parse
295
296
Returns:
297
packaging.version.Version: Parsed version object
298
"""
299
300
def safe_name(name):
301
"""
302
Convert arbitrary text to a PEP 508 safe name.
303
304
Parameters:
305
- name (str): Name to make safe
306
307
Returns:
308
str: Safe name suitable for requirements
309
"""
310
311
def safe_version(version):
312
"""
313
Convert arbitrary text to a PEP 440 safe version.
314
315
Parameters:
316
- version (str): Version to make safe
317
318
Returns:
319
str: Safe version string
320
"""
321
322
def get_platform():
323
"""
324
Get current platform identifier.
325
326
Returns:
327
str: Platform identifier string
328
"""
329
330
def compatible_platforms(provided, required):
331
"""
332
Check if provided platform is compatible with required.
333
334
Parameters:
335
- provided (str | None): Provided platform identifier
336
- required (str | None): Required platform identifier
337
338
Returns:
339
bool: True if compatible
340
"""
341
```
342
343
## Core Classes
344
345
```python { .api }
346
class WorkingSet:
347
"""
348
Set of active distributions in the runtime environment.
349
350
Key Methods:
351
- add(dist): Add distribution to working set
352
- require(*requirements): Ensure requirements are met
353
- resolve(requirements): Resolve requirement conflicts
354
- by_key: Dict mapping project names to distributions
355
"""
356
357
class Environment:
358
"""
359
Searchable snapshot of distributions in path entries.
360
361
Key Methods:
362
- scan(search_path): Scan path for distributions
363
- best_match(req, working_set): Find best distribution match
364
- obtain(requirement): Get distribution for requirement
365
"""
366
367
class Distribution:
368
"""
369
Metadata and resource access for an installed package.
370
371
Key Attributes:
372
- project_name: Package name
373
- version: Package version
374
- location: Installation location
375
- py_version: Python version
376
- platform: Platform identifier
377
378
Key Methods:
379
- requires(): Get package requirements
380
- activate(): Add to working set
381
- get_entry_map(): Get entry points
382
- has_resource(name): Check if resource exists
383
- get_resource_filename(name): Get resource path
384
"""
385
386
class Requirement:
387
"""
388
Parsed requirement specification.
389
390
Key Attributes:
391
- project_name: Required project name
392
- specs: Version specifiers
393
- extras: Extra features requested
394
- marker: Environment marker
395
396
Key Methods:
397
- __contains__(dist): Check if distribution satisfies requirement
398
"""
399
400
class EntryPoint:
401
"""
402
Named entry point for plugin discovery.
403
404
Key Attributes:
405
- name: Entry point name
406
- module_name: Module containing entry point
407
- attrs: Attribute path within module
408
- extras: Required extras
409
- dist: Providing distribution
410
411
Key Methods:
412
- load(): Load and return the entry point object
413
"""
414
```
415
416
## Exception Classes
417
418
```python { .api }
419
class ResolutionError(Exception):
420
"""Base class for requirement resolution errors."""
421
422
class VersionConflict(ResolutionError):
423
"""
424
Distribution version conflicts with requirements.
425
426
Attributes:
427
- dist: Conflicting distribution
428
- req: Requirement that conflicts
429
"""
430
431
class DistributionNotFound(ResolutionError):
432
"""Required distribution was not found."""
433
434
class UnknownExtra(ResolutionError):
435
"""Unknown extra feature was requested."""
436
437
class ExtractionError(RuntimeError):
438
"""Error extracting resource from archive."""
439
440
class PEP440Warning(RuntimeWarning):
441
"""Warning about PEP 440 version parsing issues."""
442
443
class PkgResourcesDeprecationWarning(Warning):
444
"""Deprecation warning for pkg_resources usage."""
445
```
446
447
## Provider Interfaces
448
449
```python { .api }
450
class IMetadataProvider:
451
"""Interface for providing package metadata."""
452
453
class IResourceProvider:
454
"""Interface for providing package resources."""
455
456
class DefaultProvider:
457
"""Default resource provider for filesystem packages."""
458
459
class ZipProvider:
460
"""Resource provider for packages in zip files."""
461
462
class EggProvider:
463
"""Resource provider for .egg files."""
464
465
class EmptyProvider:
466
"""Provider for packages with no resources."""
467
468
class NullProvider:
469
"""Minimal provider implementation."""
470
```
471
472
## Constants
473
474
```python { .api }
475
# Distribution precedence constants
476
EGG_DIST: int # .egg distributions
477
BINARY_DIST: int # Built distributions
478
SOURCE_DIST: int # Source distributions
479
CHECKOUT_DIST: int # VCS checkouts
480
DEVELOP_DIST: int # Development installs
481
482
# Global instances
483
empty_provider: EmptyProvider # Shared empty provider instance
484
```
485
486
## Usage Examples
487
488
### Basic Resource Access
489
```python
490
import pkg_resources
491
492
# Read a data file from a package
493
data = pkg_resources.resource_string('mypackage', 'data/config.json')
494
495
# Get filesystem path to a resource
496
config_path = pkg_resources.resource_filename('mypackage', 'data/config.json')
497
498
# List resources in a package directory
499
files = pkg_resources.resource_listdir('mypackage', 'templates')
500
```
501
502
### Distribution Discovery
503
```python
504
# Get information about an installed package
505
dist = pkg_resources.get_distribution('requests')
506
print(f"Version: {dist.version}, Location: {dist.location}")
507
508
# Ensure required packages are available
509
pkg_resources.require('requests>=2.0', 'urllib3>=1.21.1')
510
```
511
512
### Entry Point Loading
513
```python
514
# Load a console script entry point
515
main_func = pkg_resources.load_entry_point('mypackage', 'console_scripts', 'mycli')
516
517
# Discover plugin entry points
518
for ep in pkg_resources.iter_entry_points('myapp.plugins'):
519
plugin = ep.load()
520
print(f"Loaded plugin: {ep.name}")
521
```