| name | setup-python-library |
| description | Set up a Python library project with proper structure for PyPI publication. |
Python Library Setup
Overview
This guide covers the essential files and structure needed to create a Python library suitable for publication on PyPI. A properly structured project ensures installability, maintainability, and discoverability.
Required Project Structure
my-library/
├── src/
│ └── my_library/
│ ├── __init__.py
│ └── core.py
├── tests/
│ └── test_basic.py
├── pyproject.toml
├── README.md
├── LICENSE
└── .gitignore
Essential Files
1. Package init.py File
The __init__.py file is required for Python to recognize a directory as a package. Create src/<package_name>/__init__.py with:
"""A short description of your library."""
__version__ = "0.1.0"
from .core import main_function
Key elements for __init__.py:
- Docstring – Describes the package purpose
__version__ – Defines the package version string
- Public imports – Re-export key functions/classes for convenient access
Without an __init__.py file, Python won't recognize the directory as an importable package.
2. pyproject.toml
The modern standard for Python project configuration:
[project]
name = "my-library"
version = "0.1.0"
description = "A short description of your library"
readme = "README.md"
license = "MIT"
requires-python = ">=3.10"
authors = [
{ name = "Your Name", email = "you@example.com" },
]
dependencies = []
[project.optional-dependencies]
dev = ["pytest>=8.0", "ruff>=0.4"]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.hatch.build.targets.wheel]
packages = ["src/my_library"]
3. Test Setup
Create tests/test_basic.py:
from my_library import __version__
def test_version():
assert __version__ == "0.1.0"
Run tests with:
uv sync --extra dev
uv run pytest
4. Supporting Files
- README.md – Installation instructions and usage examples
- LICENSE – MIT, Apache 2.0, or other appropriate license
- .gitignore – Exclude
__pycache__/, dist/, *.egg-info/, .venv/, uv.lock
Development Workflow with uv
Initial Setup
uv init my-library --lib
uv sync
Installing Dependencies
uv sync --extra dev
uv add requests
uv add --optional dev mypy
Running Commands
uv run pytest
uv run ruff check .
uv run python -m my_library
Building and Publishing
uv build
uv publish
Checklist
Common Pitfalls
- Missing
__init__.py prevents Python from recognizing the package
- Forgetting to define
__version__ in __init__.py
- Version mismatch between
__init__.py and pyproject.toml
- Forgetting to run
uv sync after modifying dependencies in pyproject.toml