Open in VS Code: From your cloned
s26-06643repository, run in the terminal:code sse/04-python-packaging/04-python-packaging.ipynb
Module 04: Python Packaging#
Make your code installable and shareable.
Learning Objectives#
Understand Python package structure
Create pyproject.toml (modern approach)
Use AI to scaffold packages
Install packages in development mode
Publish to PyPI
Why Package Your Code?#
Reusability: Import in other projects
Distribution: Share with others via
pip installOrganization: Clean structure
Dependencies: Automatic installation
Modern Package Structure#
my_package/
├── pyproject.toml # Package configuration (modern)
├── README.md # Documentation
├── LICENSE # License file
├── src/
│ └── my_package/ # Source code
│ ├── __init__.py
│ └── core.py
└── tests/ # Tests
├── __init__.py
└── test_core.py
The src/ Layout#
Using src/ layout prevents accidentally importing local code instead of installed package.
Exercise 1: Explore an Installed Package (10 min)#
Before building your own package, let’s see how real packages are organized on disk.
Step 1: Find where the requests package lives:
python -c "import requests; print(requests.__file__)"
Step 2: List the contents of that package’s directory:
# Use the parent directory from Step 1, e.g.:
ls $(python -c "import requests; import os; print(os.path.dirname(requests.__file__))")
Step 3: Look at the __init__.py file in that directory. What does it do? (You can use head -50 to see the first 50 lines.)
Step 4: Now do the same for a standard library package:
python -c "import json; print(json.__file__)"
Questions to answer:
How does the directory structure of
requestscompare to what you saw in the slide above?Does
jsonhave asrc/layout? Why or why not?What does the
__init__.pyinrequestsimport?
pyproject.toml#
The modern way to configure Python packages:
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
[project]
name = "my-package"
version = "0.1.0"
description = "A brief description"
readme = "README.md"
license = {text = "MIT"}
authors = [
{name = "Your Name", email = "you@example.com"}
]
requires-python = ">=3.10"
dependencies = [
"requests>=2.28.0",
]
[project.optional-dependencies]
dev = [
"pytest>=7.0",
"black",
]
[project.scripts]
my-command = "my_package.cli:main"
Exercise 2: Create a Minimal Package (15 min)#
Now build a package from scratch — by hand, without AI (you need to understand each piece).
Step 1: Create the directory structure:
mkdir -p mypackage/src/mypackage
Step 2: Create mypackage/src/mypackage/__init__.py with one function:
def greet(name):
return f"Hello, {name}!"
Step 3: Create mypackage/pyproject.toml with minimal content:
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
[project]
name = "mypackage"
version = "0.1.0"
Step 4: Install it in editable mode:
cd mypackage
pip install -e .
Step 5: Test it:
python -c "from mypackage import greet; print(greet('World'))"
Expected output: Hello, World!
If it doesn’t work, debug it. Common issues: wrong directory structure, missing __init__.py, typos in pyproject.toml.
AI-Scaffolded Packages#
Let AI create the structure:
> Create a Python package called "openalex-tools" with:
- Functions to search works, authors, and institutions
- A CLI command "oalex" that takes a search query
- Modern pyproject.toml
- src/ layout
- Basic tests
AI generates all files; you review and customize.
init.py#
The __init__.py file:
Makes a directory a Python package
Runs when package is imported
Defines public API
# src/my_package/__init__.py
"""My Package - A brief description."""
__version__ = "0.1.0"
from .core import main_function, helper_function
__all__ = ["main_function", "helper_function"]
Virtual Environments#
Before installing packages in development mode, you should always work inside a virtual environment. A virtual environment is an isolated Python installation that keeps your project’s dependencies separate from other projects and your system Python.
Why Virtual Environments Matter#
Isolation: Each project gets its own dependencies, avoiding version conflicts
Reproducibility: You can recreate the exact environment on another machine
Safety: You won’t accidentally break system tools by upgrading a shared library
Cleanliness: Uninstalling is as simple as deleting the
.venvdirectory
Creating and Using a Virtual Environment#
# Create a virtual environment in your project directory
python -m venv .venv
# Activate it (macOS/Linux)
source .venv/bin/activate
# Activate it (Windows)
.venv\Scripts\activate
# Your prompt will change to show (.venv)
# Now pip install only affects this environment
# Deactivate when done
deactivate
Best Practice#
Always create a virtual environment before running pip install -e . or installing any project dependencies. Add .venv/ to your .gitignore (it should not be committed). For a more advanced environment manager, see the optional module on uv.
Development Installation#
Install your package in editable mode:
# From package root
pip install -e .
# With development dependencies
pip install -e ".[dev]"
Changes to source code are immediately available without reinstalling.
Exercise 3: The Edit-Test Loop (5 min)#
This exercise demonstrates why editable installs (pip install -e .) matter for development.
Prerequisite: You should still have mypackage installed in editable mode from Exercise 2.
Step 1: Open mypackage/src/mypackage/__init__.py and add a new function:
def farewell(name):
return f"Goodbye, {name}!"
Step 2: Without reinstalling, test it immediately:
python -c "from mypackage import farewell; print(farewell('World'))"
Expected output: Goodbye, World!
It works without reinstalling because editable mode links directly to your source code.
Step 3: Try modifying the greet function to return f"Hi there, {name}!" instead. Test it — the change should be reflected immediately.
Key takeaway: With editable installs, you get a fast edit-test loop. Without -e, you would need to run pip install . after every change.
Building and Publishing#
Build#
# Install build tool
pip install build
# Build package
python -m build
# Creates:
# dist/my_package-0.1.0.tar.gz (source)
# dist/my_package-0.1.0-py3-none-any.whl (wheel)
Publish to TestPyPI#
pip install twine
twine upload --repository testpypi dist/*
# Install from TestPyPI
pip install --index-url https://test.pypi.org/simple/ my-package
Publish to PyPI#
twine upload dist/*
Exercise 4: AI-Assisted Package Scaffolding (10 min)#
Now let AI do the heavy lifting — but you review everything critically.
Step 1: Ask your AI agent:
“Create a Python package called
scholartoolswith apyproject.toml,srclayout, and two modules:api.py(with asearch_worksfunction stub) andmetrics.py(with acalculate_h_indexfunction stub). Include type hints and docstrings.”
Step 2: Review what AI generates. Check each file:
Directory structure: Does it use
src/scholartools/layout?pyproject.toml: Does it have[build-system]and[project]sections? Is the package name correct?__init__.py: Does it import from the submodules?api.py: Doessearch_workshave type hints and a docstring?metrics.py: Doescalculate_h_indexhave type hints and a docstring?
Step 3: Fix any issues you find. Common AI mistakes:
Missing
[build-system]table inpyproject.tomlWrong package name (hyphens vs underscores)
Forgetting
__init__.pyIncomplete type hints
Step 4: Install and test:
cd scholartools
pip install -e .
python -c "from scholartools.api import search_works; print(search_works)"
python -c "from scholartools.metrics import calculate_h_index; print(calculate_h_index)"
Both imports should work without errors.
Exercise: Create Your Package#
Use AI to scaffold a package for your OpenAlex code
Review all generated files
Install in development mode
Test that imports work
Build and verify the dist files
AI Prompt#
Create a Python package called "scholartools" with:
- pyproject.toml with proper metadata
- src/scholartools/__init__.py exposing main functions
- src/scholartools/openalex.py with our API functions
- A README.md with installation and usage examples
- A .gitignore for Python projects
Summary#
File |
Purpose |
|---|---|
|
Package configuration |
|
Package marker, public API |
|
Prevents import issues |
|
Development install |
Tips and Tricks#
Prompt: “Generate a pyproject.toml for a package called [name] that depends on [libs]”: AI writes good boilerplate for this.
Always use
pip install -e .: Editable installs let you develop without reinstalling after every change.Ask the agent to verify your package structure: “Check if this directory layout follows Python packaging conventions.”
Keep
pyproject.tomlas the single source of truth: Version, dependencies, metadata — all in one file.Prompt: “Add a console_scripts entry point for [function]”: Entry points are easy to get wrong; let AI scaffold them.
Test your package installs from scratch: Create a fresh virtual environment and
pip install .to catch missing dependencies.Use semantic versioning from the start: Even for v0.1.0 — it costs nothing and signals professionalism.
Prompt: “Write a MANIFEST.in to include [files]”: If you need non-Python files in your distribution, AI knows the syntax.
Foundational Concepts to Commit to Memory#
pyproject.tomlis the single configuration file for modern Python packages – it replacessetup.py,setup.cfg, and most other config filessrc/layout means your source code lives insrc/package_name/, which prevents you from accidentally importing your local directory instead of the installed package__init__.pyis what makes a directory a Python package; it runs on import and is where you define your package’s public API via imports and__all__Editable installs (
pip install -e .) link your installed package to your source code so changes take effect immediately without reinstallingSemantic versioning follows
MAJOR.MINOR.PATCH– breaking changes bump MAJOR, new features bump MINOR, bug fixes bump PATCH[project.scripts]inpyproject.tomlcreates command-line entry points that get installed as executables when userspip installyour packageWheels (
.whl) are the modern binary distribution format; sdists (.tar.gz) are source distributions –python -m buildcreates bothPackage name vs. import name: hyphens in package names (on PyPI) map to underscores in import names (
my-packageinstalls,my_packageimports)
Knowing vs. Doing: Reflection#
Packaging is one of those topics where the gap between “I’ve heard of pyproject.toml” and “I can set up a working package from scratch” is surprisingly wide. There are dozens of configuration options, multiple build backends, editable install edge cases, and an entire ecosystem of tools that have evolved over 20+ years. You could spend weeks reading PEPs and packaging guides. But here is the honest truth: you do not need to master all of it before you start shipping code. You need to know enough to set up a basic package, understand what the key files do, and recognize when something is wrong. That baseline knowledge lets you move fast and ask the right questions when you hit a wall.
This is where AI agents become genuinely useful. You can ask an AI to scaffold your entire package structure, generate a pyproject.toml with the right metadata, and even set up entry points – all in seconds. But if you have zero understanding of what src/ layout means or why __init__.py matters, you will not be able to tell when the AI gets it wrong (and it will). The students who do best are the ones who learn the fundamentals deeply enough to verify AI output, then let the AI handle the boilerplate so they can focus on the code that actually matters.
Think about what you are building and for whom. If this is a personal utility script, a quick AI-scaffolded package is fine. If this is a library other researchers will depend on, you need to understand versioning, dependency specification, and distribution well enough to make good decisions. The value you bring is not in memorizing TOML syntax – it is in knowing what a well-structured package looks like and why it matters. There is always more to learn about packaging, and the ecosystem keeps changing. Stay curious, but do not let the learning stop you from shipping.
Additional Resources#
Python Packaging User Guide – the official, comprehensive guide to packaging in Python
Setuptools Documentation – reference for the most widely used build backend
PyPI – Python Package Index – the official repository where Python packages are published
Semantic Versioning – the versioning standard used by most Python packages
Next Steps#
In the next module, we’ll add comprehensive tests to our package.