CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-setuptools

Easily download, build, install, upgrade, and uninstall Python packages

Pending
Overview
Eval results
Files

pkg-resources.mddocs/

pkg_resources (Deprecated)

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.

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.

Core Imports

import pkg_resources

Common imports:

from pkg_resources import (
    require, get_distribution, load_entry_point,
    resource_string, resource_filename, working_set
)

Capabilities

Resource Access Functions

Functions for accessing files and data contained within Python packages at runtime.

def resource_string(package_or_requirement, resource_name):
    """
    Return the contents of a resource file as bytes.
    
    Parameters:
    - package_or_requirement (str | Requirement): Package name or requirement
    - resource_name (str): Path to resource within package
    
    Returns:
    bytes: Resource file contents
    
    Raises:
    ModuleNotFoundError: If package not found
    FileNotFoundError: If resource not found
    """

def resource_stream(package_or_requirement, resource_name):
    """
    Return a readable file-like object for a resource.
    
    Parameters:
    - package_or_requirement (str | Requirement): Package name or requirement
    - resource_name (str): Path to resource within package
    
    Returns:
    IO[bytes]: File-like object for reading resource
    """

def resource_filename(package_or_requirement, resource_name):
    """
    Return filesystem path to a resource, extracting if necessary.
    
    Parameters:
    - package_or_requirement (str | Requirement): Package name or requirement
    - resource_name (str): Path to resource within package
    
    Returns:
    str: Filesystem path to resource file
    """

def resource_listdir(package_or_requirement, resource_name):
    """
    List contents of a resource directory.
    
    Parameters:
    - package_or_requirement (str | Requirement): Package name or requirement
    - resource_name (str): Path to directory within package
    
    Returns:
    list[str]: List of resource names in directory
    """

def resource_exists(package_or_requirement, resource_name):
    """
    Check if a resource exists within a package.
    
    Parameters:
    - package_or_requirement (str | Requirement): Package name or requirement
    - resource_name (str): Path to resource within package
    
    Returns:
    bool: True if resource exists
    """

def resource_isdir(package_or_requirement, resource_name):
    """
    Check if a resource is a directory.
    
    Parameters:
    - package_or_requirement (str | Requirement): Package name or requirement
    - resource_name (str): Path to resource within package
    
    Returns:
    bool: True if resource is a directory
    """

Distribution Discovery

Functions for finding and working with installed Python distributions.

def get_distribution(requirement):
    """
    Get a Distribution object for an installed package.
    
    Parameters:
    - requirement (str | Requirement | Distribution): Package specification
    
    Returns:
    Distribution: Distribution object for the package
    
    Raises:
    DistributionNotFound: If package not found
    VersionConflict: If version requirements not met
    """

def require(*requirements):
    """
    Ensure that distributions matching requirements are available.
    
    Parameters:
    - *requirements (str | Requirement): Package requirements
    
    Returns:
    list[Distribution]: List of required distributions
    
    Raises:
    DistributionNotFound: If any requirement cannot be satisfied
    VersionConflict: If version conflicts exist
    """

def find_distributions(path_item, only=False):
    """
    Find distributions in a path item.
    
    Parameters:
    - path_item (str): Path to search for distributions
    - only (bool): If True, only return distributions in this exact path
    
    Returns:
    Iterator[Distribution]: Found distributions
    """

def get_provider(package_or_requirement):
    """
    Get resource provider for a package.
    
    Parameters:
    - package_or_requirement (str | Requirement): Package specification
    
    Returns:
    IResourceProvider: Resource provider for the package
    """

Entry Point Management

Functions for discovering and loading entry points defined by packages.

def load_entry_point(dist, group, name):
    """
    Load and return an entry point.
    
    Parameters:
    - dist (str | Requirement | Distribution): Distribution specification
    - group (str): Entry point group name
    - name (str): Entry point name
    
    Returns:
    Any: The loaded entry point object
    
    Raises:
    ImportError: If entry point cannot be loaded
    AttributeError: If entry point attribute not found
    """

def get_entry_map(dist, group=None):
    """
    Get entry point map for a distribution.
    
    Parameters:
    - dist (str | Requirement | Distribution): Distribution specification
    - group (str, optional): Specific group to get, or None for all groups
    
    Returns:
    dict: Entry point map (group -> name -> EntryPoint)
    """

def get_entry_info(dist, group, name):
    """
    Get entry point info without loading.
    
    Parameters:
    - dist (str | Requirement | Distribution): Distribution specification
    - group (str): Entry point group name
    - name (str): Entry point name
    
    Returns:
    EntryPoint | None: Entry point object or None if not found
    """

def iter_entry_points(group, name=None):
    """
    Iterate over entry points in working set.
    
    Parameters:
    - group (str): Entry point group name
    - name (str, optional): Specific entry point name
    
    Returns:
    Iterator[EntryPoint]: Matching entry points
    """

Environment Management

Functions for managing the Python environment and package working sets.

working_set: WorkingSet
    """Global working set of installed distributions."""

def add_activation_listener(callback, existing=True):
    """
    Add callback to be called when distributions are activated.
    
    Parameters:
    - callback (callable): Function to call on activation
    - existing (bool): Whether to call for existing distributions
    """

def declare_namespace(name):
    """
    Declare a namespace package.
    
    Parameters:
    - name (str): Namespace package name
    """

def set_extraction_path(path):
    """
    Set path for extracting resources from zip files.
    
    Parameters:
    - path (str): Directory path for extraction
    """

def cleanup_resources(force=False):
    """
    Clean up extracted resources.
    
    Parameters:
    - force (bool): Whether to force cleanup
    """

def get_default_cache():
    """
    Get default cache directory for extracted resources.
    
    Returns:
    str: Default cache directory path
    """

Parsing and Utilities

Utility functions for parsing requirements, versions, and handling package metadata.

def parse_requirements(strs):
    """
    Parse requirement strings.
    
    Parameters:
    - strs (str | Iterable[str]): Requirement string(s) to parse
    
    Returns:
    Iterator[Requirement]: Parsed requirement objects
    """

def parse_version(version):
    """
    Parse a version string.
    
    Parameters:
    - version (str): Version string to parse
    
    Returns:
    packaging.version.Version: Parsed version object
    """

def safe_name(name):
    """
    Convert arbitrary text to a PEP 508 safe name.
    
    Parameters:
    - name (str): Name to make safe
    
    Returns:
    str: Safe name suitable for requirements
    """

def safe_version(version):
    """
    Convert arbitrary text to a PEP 440 safe version.
    
    Parameters:
    - version (str): Version to make safe
    
    Returns:
    str: Safe version string
    """

def get_platform():
    """
    Get current platform identifier.
    
    Returns:
    str: Platform identifier string
    """

def compatible_platforms(provided, required):
    """
    Check if provided platform is compatible with required.
    
    Parameters:
    - provided (str | None): Provided platform identifier
    - required (str | None): Required platform identifier
    
    Returns:
    bool: True if compatible
    """

Core Classes

class WorkingSet:
    """
    Set of active distributions in the runtime environment.
    
    Key Methods:
    - add(dist): Add distribution to working set
    - require(*requirements): Ensure requirements are met
    - resolve(requirements): Resolve requirement conflicts
    - by_key: Dict mapping project names to distributions
    """

class Environment:
    """
    Searchable snapshot of distributions in path entries.
    
    Key Methods:
    - scan(search_path): Scan path for distributions
    - best_match(req, working_set): Find best distribution match
    - obtain(requirement): Get distribution for requirement
    """

class Distribution:
    """
    Metadata and resource access for an installed package.
    
    Key Attributes:
    - project_name: Package name
    - version: Package version
    - location: Installation location
    - py_version: Python version
    - platform: Platform identifier
    
    Key Methods:
    - requires(): Get package requirements
    - activate(): Add to working set
    - get_entry_map(): Get entry points
    - has_resource(name): Check if resource exists
    - get_resource_filename(name): Get resource path
    """

class Requirement:
    """
    Parsed requirement specification.
    
    Key Attributes:
    - project_name: Required project name
    - specs: Version specifiers
    - extras: Extra features requested
    - marker: Environment marker
    
    Key Methods:
    - __contains__(dist): Check if distribution satisfies requirement
    """

class EntryPoint:
    """
    Named entry point for plugin discovery.
    
    Key Attributes:
    - name: Entry point name
    - module_name: Module containing entry point
    - attrs: Attribute path within module
    - extras: Required extras
    - dist: Providing distribution
    
    Key Methods:
    - load(): Load and return the entry point object
    """

Exception Classes

class ResolutionError(Exception):
    """Base class for requirement resolution errors."""

class VersionConflict(ResolutionError):
    """
    Distribution version conflicts with requirements.
    
    Attributes:
    - dist: Conflicting distribution
    - req: Requirement that conflicts
    """

class DistributionNotFound(ResolutionError):
    """Required distribution was not found."""

class UnknownExtra(ResolutionError):
    """Unknown extra feature was requested."""

class ExtractionError(RuntimeError):
    """Error extracting resource from archive."""

class PEP440Warning(RuntimeWarning):
    """Warning about PEP 440 version parsing issues."""

class PkgResourcesDeprecationWarning(Warning):
    """Deprecation warning for pkg_resources usage."""

Provider Interfaces

class IMetadataProvider:
    """Interface for providing package metadata."""

class IResourceProvider:
    """Interface for providing package resources."""

class DefaultProvider:
    """Default resource provider for filesystem packages."""

class ZipProvider:
    """Resource provider for packages in zip files."""

class EggProvider:
    """Resource provider for .egg files."""

class EmptyProvider:
    """Provider for packages with no resources."""

class NullProvider:
    """Minimal provider implementation."""

Constants

# Distribution precedence constants
EGG_DIST: int       # .egg distributions
BINARY_DIST: int    # Built distributions  
SOURCE_DIST: int    # Source distributions
CHECKOUT_DIST: int  # VCS checkouts
DEVELOP_DIST: int   # Development installs

# Global instances
empty_provider: EmptyProvider  # Shared empty provider instance

Usage Examples

Basic Resource Access

import pkg_resources

# Read a data file from a package
data = pkg_resources.resource_string('mypackage', 'data/config.json')

# Get filesystem path to a resource
config_path = pkg_resources.resource_filename('mypackage', 'data/config.json')

# List resources in a package directory
files = pkg_resources.resource_listdir('mypackage', 'templates')

Distribution Discovery

# Get information about an installed package
dist = pkg_resources.get_distribution('requests')
print(f"Version: {dist.version}, Location: {dist.location}")

# Ensure required packages are available
pkg_resources.require('requests>=2.0', 'urllib3>=1.21.1')

Entry Point Loading

# Load a console script entry point
main_func = pkg_resources.load_entry_point('mypackage', 'console_scripts', 'mycli')

# Discover plugin entry points
for ep in pkg_resources.iter_entry_points('myapp.plugins'):
    plugin = ep.load()
    print(f"Loaded plugin: {ep.name}")

Install with Tessl CLI

npx tessl i tessl/pypi-setuptools

docs

build-backend.md

commands.md

core-classes.md

core-setup.md

exceptions.md

index.md

pkg-resources.md

utilities.md

tile.json