Python packaging is about turning your code into a reusable, installable package that can be shared across projects or published on PyPI. A package typically includes:
__init__.py file.pyproject.toml).Once packaged, your project can be installed with tools like pip and imported just like any other library.
.py file.__init__.py).pyproject.toml – modern config file describing how to build/install a project.A minimal library project might look like this:
# Project directory structure
myproject/
pyproject.toml
README.md
src/
mypackage/
__init__.py
core.py
The src/mypackage directory is the actual package. Code inside core.py can be imported with:
# Import function from the package
from mypackage.core import some_function
Example of a simple package with one function.
# Define a greeting function
def greet(name: str) -> str:
return f"Hello, {name}!"
# Expose greet at the package level
from .core import greet
# Control what gets imported with *
__all__ = ["greet"]
pyproject.toml tells build tools how to build/install your package and includes metadata like name, version, and dependencies.
# Build system configuration
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
# Project metadata
[project]
name = "mypackage"
version = "0.1.0"
description = "A simple example package"
authors = [{ name = "Your Name", email = "you@example.com" }]
readme = "README.md"
requires-python = ">=3.8"
dependencies = []
Once your project is configured, you can build and install it locally.
# From the project root (where pyproject.toml is located)
# Build source and wheel distributions (requires build package)
python -m pip install --upgrade build
python -m build
# Install the built package locally
python -m pip install dist/mypackage-0.1.0-py3-none-any.whl
python -m build creates files like mypackage-0.1.0.tar.gz and a .whl file in the dist/ folder.pip install dist/mypackage-0.1.0-py3-none-any.whl copies the package into your Python environment.from mypackage import greet and then greet("World") to get "Hello, World!".This is the same behavior as any package you install from PyPI, but now it’s your own code being reused.
src/mypackage layout).pyproject.toml rather than custom scripts.requires-python to avoid compatibility issues.README.md so users understand how to install and use your package.__all__ in __init__.py to control what is exported from the package.src/mypackage and add at least two functions in core.py.pyproject.toml with your own name, description, and version.python -m build and install it locally with pip.utils.py) and re-build/re-install.