Easily download, build, install, upgrade, and uninstall Python packages
npx @tessl/cli install tessl/pypi-setuptools@80.9.0Setuptools is a comprehensive Python package management and distribution library that serves as the foundational tooling for building, packaging, and distributing Python packages. It provides essential functionality for package discovery, dependency resolution, entry point management, and installation automation, while extending Python's built-in distutils with enhanced capabilities including namespace packages, automatic package discovery, console script generation, and extensible command interfaces.
pip install setuptoolsimport setuptools
from setuptools import setup, find_packages, Extension, Distribution, CommandFor build backend functionality:
import setuptools.build_metaFor specific components:
from setuptools.command import build_py, build_ext, install, develop
from setuptools.extension import Extension, Library
from setuptools.dist import Distributionfrom setuptools import setup, find_packages
# Basic package setup
setup(
name="my-package",
version="1.0.0",
description="My Python package",
author="Author Name",
author_email="author@example.com",
packages=find_packages(),
install_requires=[
"requests>=2.0.0",
],
entry_points={
'console_scripts': [
'my-command=my_package.cli:main',
],
},
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
],
)Package discovery:
from setuptools import find_packages, find_namespace_packages
# Automatically find all packages
packages = find_packages()
# Find PEP 420 namespace packages
namespace_packages = find_namespace_packages()
# Find packages with exclusions
packages = find_packages(exclude=['tests*', 'docs*'])Setuptools extends Python's built-in distutils with a layered architecture:
setup() function and Distribution class handle package metadata and configurationfind_packages() and namespace package supportThis design enables setuptools to serve as both a traditional setup.py-based build tool and a modern pyproject.toml-based build backend, providing backward compatibility while supporting current Python packaging standards.
The fundamental setuptools functionality for package configuration, including the main setup() function and package discovery utilities that form the foundation of Python package building.
def setup(**attrs):
"""
Configure and build a Python package.
Parameters:
- name: Package name
- version: Package version
- description: Short package description
- long_description: Detailed package description
- author: Package author name
- author_email: Author email address
- url: Package homepage URL
- packages: List of packages to include
- py_modules: List of individual modules to include
- install_requires: List of required dependencies
- extras_require: Dictionary of optional dependencies
- entry_points: Dictionary defining entry points and console scripts
- classifiers: List of package classifiers
- python_requires: Python version requirements
- package_data: Dictionary of package data files
- data_files: List of data files to install
- scripts: List of script files
- ext_modules: List of C/C++ extension modules
- cmdclass: Dictionary of custom command classes
- zip_safe: Whether package can be run from a zip file
- include_package_data: Whether to include package data from MANIFEST.in
- **other_attrs: Additional attributes
Returns:
None (configures package for building/installation)
"""
def find_packages(where='.', exclude=(), include=('*',)):
"""
Automatically discover Python packages.
Parameters:
- where (str): Directory to search for packages (default: '.')
- exclude (tuple): Glob patterns for packages to exclude
- include (tuple): Glob patterns for packages to include (default: ('*',))
Returns:
list: List of discovered package names
"""
def find_namespace_packages(where='.', exclude=(), include=('*',)):
"""
Discover PEP 420 implicit namespace packages.
Parameters:
- where (str): Directory to search for packages (default: '.')
- exclude (tuple): Glob patterns for packages to exclude
- include (tuple): Glob patterns for packages to include (default: ('*',))
Returns:
list: List of discovered namespace package names
"""
def findall(dir='.'):
"""
Find all files under a directory.
Parameters:
- dir (str): Directory to search (default: '.')
Returns:
list: List of file paths
"""Essential setuptools classes that provide the foundation for package building, extension compilation, and command execution.
class Distribution:
"""
Enhanced version of distutils.Distribution for package metadata.
Key Methods:
- parse_config_files(): Parse configuration files
- get_command_class(command): Get command class by name
- run_command(command): Execute a command
- get_command_obj(command): Get command instance
"""
class Command:
"""
Base class for all setuptools commands.
Required Methods:
- initialize_options(): Set default option values
- finalize_options(): Validate and process options
- run(): Execute the command
"""
class Extension:
"""
Enhanced C/C++ extension module descriptor.
Parameters:
- name (str): Extension module name
- sources (list): List of source files
- include_dirs (list): Include directories
- library_dirs (list): Library directories
- libraries (list): Libraries to link against
- extra_compile_args (list): Additional compiler arguments
- extra_link_args (list): Additional linker arguments
- language (str): Programming language ('c' or 'c++')
- py_limited_api (bool): Whether to use stable ABI
"""
class Library:
"""
Like Extension but built as a library instead of a module.
Parameters: Same as Extension
"""PEP 517/518 compliant build backend functions for modern Python packaging workflows, enabling setuptools to work with build tools like pip, build, and other PEP 517 frontends.
def build_wheel(wheel_directory, config_settings=None, metadata_directory=None):
"""
Build a wheel distribution.
Parameters:
- wheel_directory (str): Directory to write wheel file
- config_settings (dict): Build configuration settings
- metadata_directory (str): Directory containing metadata
Returns:
str: Filename of built wheel
"""
def build_sdist(sdist_directory, config_settings=None):
"""
Build a source distribution.
Parameters:
- sdist_directory (str): Directory to write sdist file
- config_settings (dict): Build configuration settings
Returns:
str: Filename of built sdist
"""
def build_editable(wheel_directory, config_settings=None, metadata_directory=None):
"""
Build an editable wheel distribution.
Parameters:
- wheel_directory (str): Directory to write wheel file
- config_settings (dict): Build configuration settings
- metadata_directory (str): Directory containing metadata
Returns:
str: Filename of built editable wheel
"""Setuptools command system providing extensible build, installation, and distribution functionality through specialized command classes for every aspect of Python package lifecycle management.
# Build Commands
class build: # Enhanced build command
class build_py: # Python module builder
class build_ext: # C extension builder
class build_clib: # C library builder
# Distribution Commands
class bdist_egg: # Build .egg distribution
class bdist_wheel: # Build wheel distribution
class bdist_rpm: # Build RPM distribution
class sdist: # Source distribution builder
# Installation Commands
class install: # Enhanced install command
class develop: # Development installation
class easy_install: # Easy install functionality
# Metadata Commands
class egg_info: # Generate egg metadata
class dist_info: # Generate dist-info metadata
class editable_wheel: # Build editable wheelsComprehensive exception hierarchy for error handling in setuptools operations, including both setuptools-specific errors and re-exported distutils errors for compatibility.
class SetuptoolsDeprecationWarning(Warning):
"""Base class for setuptools deprecation warnings."""
class BaseError(Exception):
"""Root error class for setuptools errors."""
class InvalidConfigError(BaseError):
"""Invalid configuration errors."""
class RemovedConfigError(BaseError):
"""Deprecated configuration usage."""
class PackageDiscoveryError(BaseError):
"""Package discovery issues."""
class SetupRequirementsError(BaseError):
"""Setup requirement installation issues."""Additional utility functions for archive handling, file operations, and other common setuptools operations.
def unpack_archive(filename, extract_dir='.', drivers=None):
"""Extract various archive formats."""
def unpack_zipfile(filename, extract_dir='.'):
"""Extract ZIP files."""
def unpack_tarfile(filename, extract_dir='.'):
"""Extract TAR files."""
class sic(str):
"""String class for literal treatment."""Legacy package resource API for runtime package discovery and resource access. Though deprecated in favor of importlib.resources and importlib.metadata, it remains widely used for backward compatibility.
def require(*requirements):
"""Ensure distributions matching requirements are available."""
def get_distribution(requirement):
"""Get Distribution object for installed package."""
def resource_string(package, resource_name):
"""Return resource file contents as bytes."""
def resource_filename(package, resource_name):
"""Return filesystem path to resource."""
def load_entry_point(dist, group, name):
"""Load and return entry point."""
class WorkingSet:
"""Set of active distributions in runtime environment."""
class Distribution:
"""Metadata and resource access for installed package."""# Version information
__version__: str # Current setuptools version
# Package discovery classes
class PackageFinder:
"""Standard package discovery."""
@classmethod
def find(cls, where='.', exclude=(), include=('*',)): ...
class PEP420PackageFinder(PackageFinder):
"""PEP 420 namespace package discovery."""
@classmethod
def find(cls, where='.', exclude=(), include=('*',)): ...
class ModuleFinder:
"""Discovery for standalone Python modules."""
@classmethod
def find(cls, where='.', exclude=(), include=('*',)): ...
class ConfigDiscovery:
"""Automatic configuration discovery for setuptools."""
def __init__(self, distribution=None): ...
def __call__(self, dist=None): ...
# Requirement management
class Require:
"""Represents a prerequisite for building or installing."""
def __init__(self, name, requested_version, module_name, homepage='', attribute=None, format=None): ...
def version_ok(self, version): ...
def get_version(self, paths=None, default='unknown'): ...
def is_present(self, paths=None): ...
def is_current(self, paths=None): ...